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->getName() 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).first; 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.getAsString() << RD->getName() << Base->getName(); 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 else 3056 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3057 << Name << SS.getRange(); 3058 3059 SS.clear(); 3060 } 3061 3062 if (MSPropertyAttr) { 3063 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3064 BitWidth, InitStyle, AS, MSPropertyAttr); 3065 if (!Member) 3066 return nullptr; 3067 isInstField = false; 3068 } else { 3069 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3070 BitWidth, InitStyle, AS); 3071 if (!Member) 3072 return nullptr; 3073 } 3074 3075 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3076 } else { 3077 Member = HandleDeclarator(S, D, TemplateParameterLists); 3078 if (!Member) 3079 return nullptr; 3080 3081 // Non-instance-fields can't have a bitfield. 3082 if (BitWidth) { 3083 if (Member->isInvalidDecl()) { 3084 // don't emit another diagnostic. 3085 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3086 // C++ 9.6p3: A bit-field shall not be a static member. 3087 // "static member 'A' cannot be a bit-field" 3088 Diag(Loc, diag::err_static_not_bitfield) 3089 << Name << BitWidth->getSourceRange(); 3090 } else if (isa<TypedefDecl>(Member)) { 3091 // "typedef member 'x' cannot be a bit-field" 3092 Diag(Loc, diag::err_typedef_not_bitfield) 3093 << Name << BitWidth->getSourceRange(); 3094 } else { 3095 // A function typedef ("typedef int f(); f a;"). 3096 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3097 Diag(Loc, diag::err_not_integral_type_bitfield) 3098 << Name << cast<ValueDecl>(Member)->getType() 3099 << BitWidth->getSourceRange(); 3100 } 3101 3102 BitWidth = nullptr; 3103 Member->setInvalidDecl(); 3104 } 3105 3106 Member->setAccess(AS); 3107 3108 // If we have declared a member function template or static data member 3109 // template, set the access of the templated declaration as well. 3110 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3111 FunTmpl->getTemplatedDecl()->setAccess(AS); 3112 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3113 VarTmpl->getTemplatedDecl()->setAccess(AS); 3114 } 3115 3116 if (VS.isOverrideSpecified()) 3117 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3118 if (VS.isFinalSpecified()) 3119 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3120 VS.isFinalSpelledSealed())); 3121 3122 if (VS.getLastLocation().isValid()) { 3123 // Update the end location of a method that has a virt-specifiers. 3124 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3125 MD->setRangeEnd(VS.getLastLocation()); 3126 } 3127 3128 CheckOverrideControl(Member); 3129 3130 assert((Name || isInstField) && "No identifier for non-field ?"); 3131 3132 if (isInstField) { 3133 FieldDecl *FD = cast<FieldDecl>(Member); 3134 FieldCollector->Add(FD); 3135 3136 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3137 // Remember all explicit private FieldDecls that have a name, no side 3138 // effects and are not part of a dependent type declaration. 3139 if (!FD->isImplicit() && FD->getDeclName() && 3140 FD->getAccess() == AS_private && 3141 !FD->hasAttr<UnusedAttr>() && 3142 !FD->getParent()->isDependentContext() && 3143 !InitializationHasSideEffects(*FD)) 3144 UnusedPrivateFields.insert(FD); 3145 } 3146 } 3147 3148 return Member; 3149 } 3150 3151 namespace { 3152 class UninitializedFieldVisitor 3153 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3154 Sema &S; 3155 // List of Decls to generate a warning on. Also remove Decls that become 3156 // initialized. 3157 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3158 // List of base classes of the record. Classes are removed after their 3159 // initializers. 3160 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3161 // Vector of decls to be removed from the Decl set prior to visiting the 3162 // nodes. These Decls may have been initialized in the prior initializer. 3163 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3164 // If non-null, add a note to the warning pointing back to the constructor. 3165 const CXXConstructorDecl *Constructor; 3166 // Variables to hold state when processing an initializer list. When 3167 // InitList is true, special case initialization of FieldDecls matching 3168 // InitListFieldDecl. 3169 bool InitList; 3170 FieldDecl *InitListFieldDecl; 3171 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3172 3173 public: 3174 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3175 UninitializedFieldVisitor(Sema &S, 3176 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3177 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3178 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3179 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3180 3181 // Returns true if the use of ME is not an uninitialized use. 3182 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3183 bool CheckReferenceOnly) { 3184 llvm::SmallVector<FieldDecl*, 4> Fields; 3185 bool ReferenceField = false; 3186 while (ME) { 3187 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3188 if (!FD) 3189 return false; 3190 Fields.push_back(FD); 3191 if (FD->getType()->isReferenceType()) 3192 ReferenceField = true; 3193 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3194 } 3195 3196 // Binding a reference to an unintialized field is not an 3197 // uninitialized use. 3198 if (CheckReferenceOnly && !ReferenceField) 3199 return true; 3200 3201 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3202 // Discard the first field since it is the field decl that is being 3203 // initialized. 3204 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3205 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3206 } 3207 3208 for (auto UsedIter = UsedFieldIndex.begin(), 3209 UsedEnd = UsedFieldIndex.end(), 3210 OrigIter = InitFieldIndex.begin(), 3211 OrigEnd = InitFieldIndex.end(); 3212 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3213 if (*UsedIter < *OrigIter) 3214 return true; 3215 if (*UsedIter > *OrigIter) 3216 break; 3217 } 3218 3219 return false; 3220 } 3221 3222 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3223 bool AddressOf) { 3224 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3225 return; 3226 3227 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3228 // or union. 3229 MemberExpr *FieldME = ME; 3230 3231 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3232 3233 Expr *Base = ME; 3234 while (MemberExpr *SubME = 3235 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3236 3237 if (isa<VarDecl>(SubME->getMemberDecl())) 3238 return; 3239 3240 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3241 if (!FD->isAnonymousStructOrUnion()) 3242 FieldME = SubME; 3243 3244 if (!FieldME->getType().isPODType(S.Context)) 3245 AllPODFields = false; 3246 3247 Base = SubME->getBase(); 3248 } 3249 3250 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3251 return; 3252 3253 if (AddressOf && AllPODFields) 3254 return; 3255 3256 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3257 3258 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3259 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3260 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3261 } 3262 3263 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3264 QualType T = BaseCast->getType(); 3265 if (T->isPointerType() && 3266 BaseClasses.count(T->getPointeeType())) { 3267 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3268 << T->getPointeeType() << FoundVD; 3269 } 3270 } 3271 } 3272 3273 if (!Decls.count(FoundVD)) 3274 return; 3275 3276 const bool IsReference = FoundVD->getType()->isReferenceType(); 3277 3278 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3279 // Special checking for initializer lists. 3280 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3281 return; 3282 } 3283 } else { 3284 // Prevent double warnings on use of unbounded references. 3285 if (CheckReferenceOnly && !IsReference) 3286 return; 3287 } 3288 3289 unsigned diag = IsReference 3290 ? diag::warn_reference_field_is_uninit 3291 : diag::warn_field_is_uninit; 3292 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3293 if (Constructor) 3294 S.Diag(Constructor->getLocation(), 3295 diag::note_uninit_in_this_constructor) 3296 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3297 3298 } 3299 3300 void HandleValue(Expr *E, bool AddressOf) { 3301 E = E->IgnoreParens(); 3302 3303 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3304 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3305 AddressOf /*AddressOf*/); 3306 return; 3307 } 3308 3309 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3310 Visit(CO->getCond()); 3311 HandleValue(CO->getTrueExpr(), AddressOf); 3312 HandleValue(CO->getFalseExpr(), AddressOf); 3313 return; 3314 } 3315 3316 if (BinaryConditionalOperator *BCO = 3317 dyn_cast<BinaryConditionalOperator>(E)) { 3318 Visit(BCO->getCond()); 3319 HandleValue(BCO->getFalseExpr(), AddressOf); 3320 return; 3321 } 3322 3323 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3324 HandleValue(OVE->getSourceExpr(), AddressOf); 3325 return; 3326 } 3327 3328 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3329 switch (BO->getOpcode()) { 3330 default: 3331 break; 3332 case(BO_PtrMemD): 3333 case(BO_PtrMemI): 3334 HandleValue(BO->getLHS(), AddressOf); 3335 Visit(BO->getRHS()); 3336 return; 3337 case(BO_Comma): 3338 Visit(BO->getLHS()); 3339 HandleValue(BO->getRHS(), AddressOf); 3340 return; 3341 } 3342 } 3343 3344 Visit(E); 3345 } 3346 3347 void CheckInitListExpr(InitListExpr *ILE) { 3348 InitFieldIndex.push_back(0); 3349 for (auto Child : ILE->children()) { 3350 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3351 CheckInitListExpr(SubList); 3352 } else { 3353 Visit(Child); 3354 } 3355 ++InitFieldIndex.back(); 3356 } 3357 InitFieldIndex.pop_back(); 3358 } 3359 3360 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3361 FieldDecl *Field, const Type *BaseClass) { 3362 // Remove Decls that may have been initialized in the previous 3363 // initializer. 3364 for (ValueDecl* VD : DeclsToRemove) 3365 Decls.erase(VD); 3366 DeclsToRemove.clear(); 3367 3368 Constructor = FieldConstructor; 3369 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3370 3371 if (ILE && Field) { 3372 InitList = true; 3373 InitListFieldDecl = Field; 3374 InitFieldIndex.clear(); 3375 CheckInitListExpr(ILE); 3376 } else { 3377 InitList = false; 3378 Visit(E); 3379 } 3380 3381 if (Field) 3382 Decls.erase(Field); 3383 if (BaseClass) 3384 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3385 } 3386 3387 void VisitMemberExpr(MemberExpr *ME) { 3388 // All uses of unbounded reference fields will warn. 3389 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3390 } 3391 3392 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3393 if (E->getCastKind() == CK_LValueToRValue) { 3394 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3395 return; 3396 } 3397 3398 Inherited::VisitImplicitCastExpr(E); 3399 } 3400 3401 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3402 if (E->getConstructor()->isCopyConstructor()) { 3403 Expr *ArgExpr = E->getArg(0); 3404 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3405 if (ILE->getNumInits() == 1) 3406 ArgExpr = ILE->getInit(0); 3407 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3408 if (ICE->getCastKind() == CK_NoOp) 3409 ArgExpr = ICE->getSubExpr(); 3410 HandleValue(ArgExpr, false /*AddressOf*/); 3411 return; 3412 } 3413 Inherited::VisitCXXConstructExpr(E); 3414 } 3415 3416 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3417 Expr *Callee = E->getCallee(); 3418 if (isa<MemberExpr>(Callee)) { 3419 HandleValue(Callee, false /*AddressOf*/); 3420 for (auto Arg : E->arguments()) 3421 Visit(Arg); 3422 return; 3423 } 3424 3425 Inherited::VisitCXXMemberCallExpr(E); 3426 } 3427 3428 void VisitCallExpr(CallExpr *E) { 3429 // Treat std::move as a use. 3430 if (E->isCallToStdMove()) { 3431 HandleValue(E->getArg(0), /*AddressOf=*/false); 3432 return; 3433 } 3434 3435 Inherited::VisitCallExpr(E); 3436 } 3437 3438 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3439 Expr *Callee = E->getCallee(); 3440 3441 if (isa<UnresolvedLookupExpr>(Callee)) 3442 return Inherited::VisitCXXOperatorCallExpr(E); 3443 3444 Visit(Callee); 3445 for (auto Arg : E->arguments()) 3446 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3447 } 3448 3449 void VisitBinaryOperator(BinaryOperator *E) { 3450 // If a field assignment is detected, remove the field from the 3451 // uninitiailized field set. 3452 if (E->getOpcode() == BO_Assign) 3453 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3454 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3455 if (!FD->getType()->isReferenceType()) 3456 DeclsToRemove.push_back(FD); 3457 3458 if (E->isCompoundAssignmentOp()) { 3459 HandleValue(E->getLHS(), false /*AddressOf*/); 3460 Visit(E->getRHS()); 3461 return; 3462 } 3463 3464 Inherited::VisitBinaryOperator(E); 3465 } 3466 3467 void VisitUnaryOperator(UnaryOperator *E) { 3468 if (E->isIncrementDecrementOp()) { 3469 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3470 return; 3471 } 3472 if (E->getOpcode() == UO_AddrOf) { 3473 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3474 HandleValue(ME->getBase(), true /*AddressOf*/); 3475 return; 3476 } 3477 } 3478 3479 Inherited::VisitUnaryOperator(E); 3480 } 3481 }; 3482 3483 // Diagnose value-uses of fields to initialize themselves, e.g. 3484 // foo(foo) 3485 // where foo is not also a parameter to the constructor. 3486 // Also diagnose across field uninitialized use such as 3487 // x(y), y(x) 3488 // TODO: implement -Wuninitialized and fold this into that framework. 3489 static void DiagnoseUninitializedFields( 3490 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3491 3492 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3493 Constructor->getLocation())) { 3494 return; 3495 } 3496 3497 if (Constructor->isInvalidDecl()) 3498 return; 3499 3500 const CXXRecordDecl *RD = Constructor->getParent(); 3501 3502 if (RD->getDescribedClassTemplate()) 3503 return; 3504 3505 // Holds fields that are uninitialized. 3506 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3507 3508 // At the beginning, all fields are uninitialized. 3509 for (auto *I : RD->decls()) { 3510 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3511 UninitializedFields.insert(FD); 3512 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3513 UninitializedFields.insert(IFD->getAnonField()); 3514 } 3515 } 3516 3517 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3518 for (auto I : RD->bases()) 3519 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3520 3521 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3522 return; 3523 3524 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3525 UninitializedFields, 3526 UninitializedBaseClasses); 3527 3528 for (const auto *FieldInit : Constructor->inits()) { 3529 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3530 break; 3531 3532 Expr *InitExpr = FieldInit->getInit(); 3533 if (!InitExpr) 3534 continue; 3535 3536 if (CXXDefaultInitExpr *Default = 3537 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3538 InitExpr = Default->getExpr(); 3539 if (!InitExpr) 3540 continue; 3541 // In class initializers will point to the constructor. 3542 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3543 FieldInit->getAnyMember(), 3544 FieldInit->getBaseClass()); 3545 } else { 3546 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3547 FieldInit->getAnyMember(), 3548 FieldInit->getBaseClass()); 3549 } 3550 } 3551 } 3552 } // namespace 3553 3554 /// \brief Enter a new C++ default initializer scope. After calling this, the 3555 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3556 /// parsing or instantiating the initializer failed. 3557 void Sema::ActOnStartCXXInClassMemberInitializer() { 3558 // Create a synthetic function scope to represent the call to the constructor 3559 // that notionally surrounds a use of this initializer. 3560 PushFunctionScope(); 3561 } 3562 3563 /// \brief This is invoked after parsing an in-class initializer for a 3564 /// non-static C++ class member, and after instantiating an in-class initializer 3565 /// in a class template. Such actions are deferred until the class is complete. 3566 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3567 SourceLocation InitLoc, 3568 Expr *InitExpr) { 3569 // Pop the notional constructor scope we created earlier. 3570 PopFunctionScopeInfo(nullptr, D); 3571 3572 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3573 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3574 "must set init style when field is created"); 3575 3576 if (!InitExpr) { 3577 D->setInvalidDecl(); 3578 if (FD) 3579 FD->removeInClassInitializer(); 3580 return; 3581 } 3582 3583 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3584 FD->setInvalidDecl(); 3585 FD->removeInClassInitializer(); 3586 return; 3587 } 3588 3589 ExprResult Init = InitExpr; 3590 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3591 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3592 InitializationKind Kind = 3593 FD->getInClassInitStyle() == ICIS_ListInit 3594 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(), 3595 InitExpr->getLocStart(), 3596 InitExpr->getLocEnd()) 3597 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3598 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3599 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3600 if (Init.isInvalid()) { 3601 FD->setInvalidDecl(); 3602 return; 3603 } 3604 } 3605 3606 // C++11 [class.base.init]p7: 3607 // The initialization of each base and member constitutes a 3608 // full-expression. 3609 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3610 if (Init.isInvalid()) { 3611 FD->setInvalidDecl(); 3612 return; 3613 } 3614 3615 InitExpr = Init.get(); 3616 3617 FD->setInClassInitializer(InitExpr); 3618 } 3619 3620 /// \brief Find the direct and/or virtual base specifiers that 3621 /// correspond to the given base type, for use in base initialization 3622 /// within a constructor. 3623 static bool FindBaseInitializer(Sema &SemaRef, 3624 CXXRecordDecl *ClassDecl, 3625 QualType BaseType, 3626 const CXXBaseSpecifier *&DirectBaseSpec, 3627 const CXXBaseSpecifier *&VirtualBaseSpec) { 3628 // First, check for a direct base class. 3629 DirectBaseSpec = nullptr; 3630 for (const auto &Base : ClassDecl->bases()) { 3631 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3632 // We found a direct base of this type. That's what we're 3633 // initializing. 3634 DirectBaseSpec = &Base; 3635 break; 3636 } 3637 } 3638 3639 // Check for a virtual base class. 3640 // FIXME: We might be able to short-circuit this if we know in advance that 3641 // there are no virtual bases. 3642 VirtualBaseSpec = nullptr; 3643 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3644 // We haven't found a base yet; search the class hierarchy for a 3645 // virtual base class. 3646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3647 /*DetectVirtual=*/false); 3648 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3649 SemaRef.Context.getTypeDeclType(ClassDecl), 3650 BaseType, Paths)) { 3651 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3652 Path != Paths.end(); ++Path) { 3653 if (Path->back().Base->isVirtual()) { 3654 VirtualBaseSpec = Path->back().Base; 3655 break; 3656 } 3657 } 3658 } 3659 } 3660 3661 return DirectBaseSpec || VirtualBaseSpec; 3662 } 3663 3664 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3665 MemInitResult 3666 Sema::ActOnMemInitializer(Decl *ConstructorD, 3667 Scope *S, 3668 CXXScopeSpec &SS, 3669 IdentifierInfo *MemberOrBase, 3670 ParsedType TemplateTypeTy, 3671 const DeclSpec &DS, 3672 SourceLocation IdLoc, 3673 Expr *InitList, 3674 SourceLocation EllipsisLoc) { 3675 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3676 DS, IdLoc, InitList, 3677 EllipsisLoc); 3678 } 3679 3680 /// \brief Handle a C++ member initializer using parentheses syntax. 3681 MemInitResult 3682 Sema::ActOnMemInitializer(Decl *ConstructorD, 3683 Scope *S, 3684 CXXScopeSpec &SS, 3685 IdentifierInfo *MemberOrBase, 3686 ParsedType TemplateTypeTy, 3687 const DeclSpec &DS, 3688 SourceLocation IdLoc, 3689 SourceLocation LParenLoc, 3690 ArrayRef<Expr *> Args, 3691 SourceLocation RParenLoc, 3692 SourceLocation EllipsisLoc) { 3693 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3694 Args, RParenLoc); 3695 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3696 DS, IdLoc, List, EllipsisLoc); 3697 } 3698 3699 namespace { 3700 3701 // Callback to only accept typo corrections that can be a valid C++ member 3702 // intializer: either a non-static field member or a base class. 3703 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3704 public: 3705 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3706 : ClassDecl(ClassDecl) {} 3707 3708 bool ValidateCandidate(const TypoCorrection &candidate) override { 3709 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3710 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3711 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3712 return isa<TypeDecl>(ND); 3713 } 3714 return false; 3715 } 3716 3717 private: 3718 CXXRecordDecl *ClassDecl; 3719 }; 3720 3721 } 3722 3723 /// \brief Handle a C++ member initializer. 3724 MemInitResult 3725 Sema::BuildMemInitializer(Decl *ConstructorD, 3726 Scope *S, 3727 CXXScopeSpec &SS, 3728 IdentifierInfo *MemberOrBase, 3729 ParsedType TemplateTypeTy, 3730 const DeclSpec &DS, 3731 SourceLocation IdLoc, 3732 Expr *Init, 3733 SourceLocation EllipsisLoc) { 3734 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3735 if (!Res.isUsable()) 3736 return true; 3737 Init = Res.get(); 3738 3739 if (!ConstructorD) 3740 return true; 3741 3742 AdjustDeclIfTemplate(ConstructorD); 3743 3744 CXXConstructorDecl *Constructor 3745 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3746 if (!Constructor) { 3747 // The user wrote a constructor initializer on a function that is 3748 // not a C++ constructor. Ignore the error for now, because we may 3749 // have more member initializers coming; we'll diagnose it just 3750 // once in ActOnMemInitializers. 3751 return true; 3752 } 3753 3754 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3755 3756 // C++ [class.base.init]p2: 3757 // Names in a mem-initializer-id are looked up in the scope of the 3758 // constructor's class and, if not found in that scope, are looked 3759 // up in the scope containing the constructor's definition. 3760 // [Note: if the constructor's class contains a member with the 3761 // same name as a direct or virtual base class of the class, a 3762 // mem-initializer-id naming the member or base class and composed 3763 // of a single identifier refers to the class member. A 3764 // mem-initializer-id for the hidden base class may be specified 3765 // using a qualified name. ] 3766 if (!SS.getScopeRep() && !TemplateTypeTy) { 3767 // Look for a member, first. 3768 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3769 if (!Result.empty()) { 3770 ValueDecl *Member; 3771 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3772 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3773 if (EllipsisLoc.isValid()) 3774 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3775 << MemberOrBase 3776 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3777 3778 return BuildMemberInitializer(Member, Init, IdLoc); 3779 } 3780 } 3781 } 3782 // It didn't name a member, so see if it names a class. 3783 QualType BaseType; 3784 TypeSourceInfo *TInfo = nullptr; 3785 3786 if (TemplateTypeTy) { 3787 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3788 } else if (DS.getTypeSpecType() == TST_decltype) { 3789 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3790 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3791 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3792 return true; 3793 } else { 3794 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3795 LookupParsedName(R, S, &SS); 3796 3797 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3798 if (!TyD) { 3799 if (R.isAmbiguous()) return true; 3800 3801 // We don't want access-control diagnostics here. 3802 R.suppressDiagnostics(); 3803 3804 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3805 bool NotUnknownSpecialization = false; 3806 DeclContext *DC = computeDeclContext(SS, false); 3807 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3808 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3809 3810 if (!NotUnknownSpecialization) { 3811 // When the scope specifier can refer to a member of an unknown 3812 // specialization, we take it as a type name. 3813 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3814 SS.getWithLocInContext(Context), 3815 *MemberOrBase, IdLoc); 3816 if (BaseType.isNull()) 3817 return true; 3818 3819 TInfo = Context.CreateTypeSourceInfo(BaseType); 3820 DependentNameTypeLoc TL = 3821 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3822 if (!TL.isNull()) { 3823 TL.setNameLoc(IdLoc); 3824 TL.setElaboratedKeywordLoc(SourceLocation()); 3825 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3826 } 3827 3828 R.clear(); 3829 R.setLookupName(MemberOrBase); 3830 } 3831 } 3832 3833 // If no results were found, try to correct typos. 3834 TypoCorrection Corr; 3835 if (R.empty() && BaseType.isNull() && 3836 (Corr = CorrectTypo( 3837 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3838 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3839 CTK_ErrorRecovery, ClassDecl))) { 3840 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3841 // We have found a non-static data member with a similar 3842 // name to what was typed; complain and initialize that 3843 // member. 3844 diagnoseTypo(Corr, 3845 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3846 << MemberOrBase << true); 3847 return BuildMemberInitializer(Member, Init, IdLoc); 3848 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3849 const CXXBaseSpecifier *DirectBaseSpec; 3850 const CXXBaseSpecifier *VirtualBaseSpec; 3851 if (FindBaseInitializer(*this, ClassDecl, 3852 Context.getTypeDeclType(Type), 3853 DirectBaseSpec, VirtualBaseSpec)) { 3854 // We have found a direct or virtual base class with a 3855 // similar name to what was typed; complain and initialize 3856 // that base class. 3857 diagnoseTypo(Corr, 3858 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3859 << MemberOrBase << false, 3860 PDiag() /*Suppress note, we provide our own.*/); 3861 3862 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3863 : VirtualBaseSpec; 3864 Diag(BaseSpec->getLocStart(), 3865 diag::note_base_class_specified_here) 3866 << BaseSpec->getType() 3867 << BaseSpec->getSourceRange(); 3868 3869 TyD = Type; 3870 } 3871 } 3872 } 3873 3874 if (!TyD && BaseType.isNull()) { 3875 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3876 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3877 return true; 3878 } 3879 } 3880 3881 if (BaseType.isNull()) { 3882 BaseType = Context.getTypeDeclType(TyD); 3883 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3884 if (SS.isSet()) { 3885 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3886 BaseType); 3887 TInfo = Context.CreateTypeSourceInfo(BaseType); 3888 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3889 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3890 TL.setElaboratedKeywordLoc(SourceLocation()); 3891 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3892 } 3893 } 3894 } 3895 3896 if (!TInfo) 3897 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3898 3899 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3900 } 3901 3902 /// Checks a member initializer expression for cases where reference (or 3903 /// pointer) members are bound to by-value parameters (or their addresses). 3904 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3905 Expr *Init, 3906 SourceLocation IdLoc) { 3907 QualType MemberTy = Member->getType(); 3908 3909 // We only handle pointers and references currently. 3910 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3911 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3912 return; 3913 3914 const bool IsPointer = MemberTy->isPointerType(); 3915 if (IsPointer) { 3916 if (const UnaryOperator *Op 3917 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3918 // The only case we're worried about with pointers requires taking the 3919 // address. 3920 if (Op->getOpcode() != UO_AddrOf) 3921 return; 3922 3923 Init = Op->getSubExpr(); 3924 } else { 3925 // We only handle address-of expression initializers for pointers. 3926 return; 3927 } 3928 } 3929 3930 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3931 // We only warn when referring to a non-reference parameter declaration. 3932 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3933 if (!Parameter || Parameter->getType()->isReferenceType()) 3934 return; 3935 3936 S.Diag(Init->getExprLoc(), 3937 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3938 : diag::warn_bind_ref_member_to_parameter) 3939 << Member << Parameter << Init->getSourceRange(); 3940 } else { 3941 // Other initializers are fine. 3942 return; 3943 } 3944 3945 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3946 << (unsigned)IsPointer; 3947 } 3948 3949 MemInitResult 3950 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3951 SourceLocation IdLoc) { 3952 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3953 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3954 assert((DirectMember || IndirectMember) && 3955 "Member must be a FieldDecl or IndirectFieldDecl"); 3956 3957 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3958 return true; 3959 3960 if (Member->isInvalidDecl()) 3961 return true; 3962 3963 MultiExprArg Args; 3964 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3965 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3966 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3967 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3968 } else { 3969 // Template instantiation doesn't reconstruct ParenListExprs for us. 3970 Args = Init; 3971 } 3972 3973 SourceRange InitRange = Init->getSourceRange(); 3974 3975 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3976 // Can't check initialization for a member of dependent type or when 3977 // any of the arguments are type-dependent expressions. 3978 DiscardCleanupsInEvaluationContext(); 3979 } else { 3980 bool InitList = false; 3981 if (isa<InitListExpr>(Init)) { 3982 InitList = true; 3983 Args = Init; 3984 } 3985 3986 // Initialize the member. 3987 InitializedEntity MemberEntity = 3988 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3989 : InitializedEntity::InitializeMember(IndirectMember, 3990 nullptr); 3991 InitializationKind Kind = 3992 InitList ? InitializationKind::CreateDirectList( 3993 IdLoc, Init->getLocStart(), Init->getLocEnd()) 3994 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3995 InitRange.getEnd()); 3996 3997 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3998 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3999 nullptr); 4000 if (MemberInit.isInvalid()) 4001 return true; 4002 4003 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 4004 4005 // C++11 [class.base.init]p7: 4006 // The initialization of each base and member constitutes a 4007 // full-expression. 4008 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 4009 if (MemberInit.isInvalid()) 4010 return true; 4011 4012 Init = MemberInit.get(); 4013 } 4014 4015 if (DirectMember) { 4016 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4017 InitRange.getBegin(), Init, 4018 InitRange.getEnd()); 4019 } else { 4020 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4021 InitRange.getBegin(), Init, 4022 InitRange.getEnd()); 4023 } 4024 } 4025 4026 MemInitResult 4027 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4028 CXXRecordDecl *ClassDecl) { 4029 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4030 if (!LangOpts.CPlusPlus11) 4031 return Diag(NameLoc, diag::err_delegating_ctor) 4032 << TInfo->getTypeLoc().getLocalSourceRange(); 4033 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4034 4035 bool InitList = true; 4036 MultiExprArg Args = Init; 4037 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4038 InitList = false; 4039 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4040 } 4041 4042 SourceRange InitRange = Init->getSourceRange(); 4043 // Initialize the object. 4044 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4045 QualType(ClassDecl->getTypeForDecl(), 0)); 4046 InitializationKind Kind = 4047 InitList ? InitializationKind::CreateDirectList( 4048 NameLoc, Init->getLocStart(), Init->getLocEnd()) 4049 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4050 InitRange.getEnd()); 4051 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4052 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4053 Args, nullptr); 4054 if (DelegationInit.isInvalid()) 4055 return true; 4056 4057 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4058 "Delegating constructor with no target?"); 4059 4060 // C++11 [class.base.init]p7: 4061 // The initialization of each base and member constitutes a 4062 // full-expression. 4063 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4064 InitRange.getBegin()); 4065 if (DelegationInit.isInvalid()) 4066 return true; 4067 4068 // If we are in a dependent context, template instantiation will 4069 // perform this type-checking again. Just save the arguments that we 4070 // received in a ParenListExpr. 4071 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4072 // of the information that we have about the base 4073 // initializer. However, deconstructing the ASTs is a dicey process, 4074 // and this approach is far more likely to get the corner cases right. 4075 if (CurContext->isDependentContext()) 4076 DelegationInit = Init; 4077 4078 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4079 DelegationInit.getAs<Expr>(), 4080 InitRange.getEnd()); 4081 } 4082 4083 MemInitResult 4084 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4085 Expr *Init, CXXRecordDecl *ClassDecl, 4086 SourceLocation EllipsisLoc) { 4087 SourceLocation BaseLoc 4088 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4089 4090 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4091 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4092 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4093 4094 // C++ [class.base.init]p2: 4095 // [...] Unless the mem-initializer-id names a nonstatic data 4096 // member of the constructor's class or a direct or virtual base 4097 // of that class, the mem-initializer is ill-formed. A 4098 // mem-initializer-list can initialize a base class using any 4099 // name that denotes that base class type. 4100 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4101 4102 SourceRange InitRange = Init->getSourceRange(); 4103 if (EllipsisLoc.isValid()) { 4104 // This is a pack expansion. 4105 if (!BaseType->containsUnexpandedParameterPack()) { 4106 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4107 << SourceRange(BaseLoc, InitRange.getEnd()); 4108 4109 EllipsisLoc = SourceLocation(); 4110 } 4111 } else { 4112 // Check for any unexpanded parameter packs. 4113 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4114 return true; 4115 4116 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4117 return true; 4118 } 4119 4120 // Check for direct and virtual base classes. 4121 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4122 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4123 if (!Dependent) { 4124 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4125 BaseType)) 4126 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4127 4128 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4129 VirtualBaseSpec); 4130 4131 // C++ [base.class.init]p2: 4132 // Unless the mem-initializer-id names a nonstatic data member of the 4133 // constructor's class or a direct or virtual base of that class, the 4134 // mem-initializer is ill-formed. 4135 if (!DirectBaseSpec && !VirtualBaseSpec) { 4136 // If the class has any dependent bases, then it's possible that 4137 // one of those types will resolve to the same type as 4138 // BaseType. Therefore, just treat this as a dependent base 4139 // class initialization. FIXME: Should we try to check the 4140 // initialization anyway? It seems odd. 4141 if (ClassDecl->hasAnyDependentBases()) 4142 Dependent = true; 4143 else 4144 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4145 << BaseType << Context.getTypeDeclType(ClassDecl) 4146 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4147 } 4148 } 4149 4150 if (Dependent) { 4151 DiscardCleanupsInEvaluationContext(); 4152 4153 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4154 /*IsVirtual=*/false, 4155 InitRange.getBegin(), Init, 4156 InitRange.getEnd(), EllipsisLoc); 4157 } 4158 4159 // C++ [base.class.init]p2: 4160 // If a mem-initializer-id is ambiguous because it designates both 4161 // a direct non-virtual base class and an inherited virtual base 4162 // class, the mem-initializer is ill-formed. 4163 if (DirectBaseSpec && VirtualBaseSpec) 4164 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4165 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4166 4167 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4168 if (!BaseSpec) 4169 BaseSpec = VirtualBaseSpec; 4170 4171 // Initialize the base. 4172 bool InitList = true; 4173 MultiExprArg Args = Init; 4174 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4175 InitList = false; 4176 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4177 } 4178 4179 InitializedEntity BaseEntity = 4180 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4181 InitializationKind Kind = 4182 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4183 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4184 InitRange.getEnd()); 4185 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4186 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4187 if (BaseInit.isInvalid()) 4188 return true; 4189 4190 // C++11 [class.base.init]p7: 4191 // The initialization of each base and member constitutes a 4192 // full-expression. 4193 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4194 if (BaseInit.isInvalid()) 4195 return true; 4196 4197 // If we are in a dependent context, template instantiation will 4198 // perform this type-checking again. Just save the arguments that we 4199 // received in a ParenListExpr. 4200 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4201 // of the information that we have about the base 4202 // initializer. However, deconstructing the ASTs is a dicey process, 4203 // and this approach is far more likely to get the corner cases right. 4204 if (CurContext->isDependentContext()) 4205 BaseInit = Init; 4206 4207 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4208 BaseSpec->isVirtual(), 4209 InitRange.getBegin(), 4210 BaseInit.getAs<Expr>(), 4211 InitRange.getEnd(), EllipsisLoc); 4212 } 4213 4214 // Create a static_cast\<T&&>(expr). 4215 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4216 if (T.isNull()) T = E->getType(); 4217 QualType TargetType = SemaRef.BuildReferenceType( 4218 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4219 SourceLocation ExprLoc = E->getLocStart(); 4220 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4221 TargetType, ExprLoc); 4222 4223 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4224 SourceRange(ExprLoc, ExprLoc), 4225 E->getSourceRange()).get(); 4226 } 4227 4228 /// ImplicitInitializerKind - How an implicit base or member initializer should 4229 /// initialize its base or member. 4230 enum ImplicitInitializerKind { 4231 IIK_Default, 4232 IIK_Copy, 4233 IIK_Move, 4234 IIK_Inherit 4235 }; 4236 4237 static bool 4238 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4239 ImplicitInitializerKind ImplicitInitKind, 4240 CXXBaseSpecifier *BaseSpec, 4241 bool IsInheritedVirtualBase, 4242 CXXCtorInitializer *&CXXBaseInit) { 4243 InitializedEntity InitEntity 4244 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4245 IsInheritedVirtualBase); 4246 4247 ExprResult BaseInit; 4248 4249 switch (ImplicitInitKind) { 4250 case IIK_Inherit: 4251 case IIK_Default: { 4252 InitializationKind InitKind 4253 = InitializationKind::CreateDefault(Constructor->getLocation()); 4254 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4255 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4256 break; 4257 } 4258 4259 case IIK_Move: 4260 case IIK_Copy: { 4261 bool Moving = ImplicitInitKind == IIK_Move; 4262 ParmVarDecl *Param = Constructor->getParamDecl(0); 4263 QualType ParamType = Param->getType().getNonReferenceType(); 4264 4265 Expr *CopyCtorArg = 4266 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4267 SourceLocation(), Param, false, 4268 Constructor->getLocation(), ParamType, 4269 VK_LValue, nullptr); 4270 4271 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4272 4273 // Cast to the base class to avoid ambiguities. 4274 QualType ArgTy = 4275 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4276 ParamType.getQualifiers()); 4277 4278 if (Moving) { 4279 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4280 } 4281 4282 CXXCastPath BasePath; 4283 BasePath.push_back(BaseSpec); 4284 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4285 CK_UncheckedDerivedToBase, 4286 Moving ? VK_XValue : VK_LValue, 4287 &BasePath).get(); 4288 4289 InitializationKind InitKind 4290 = InitializationKind::CreateDirect(Constructor->getLocation(), 4291 SourceLocation(), SourceLocation()); 4292 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4293 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4294 break; 4295 } 4296 } 4297 4298 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4299 if (BaseInit.isInvalid()) 4300 return true; 4301 4302 CXXBaseInit = 4303 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4304 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4305 SourceLocation()), 4306 BaseSpec->isVirtual(), 4307 SourceLocation(), 4308 BaseInit.getAs<Expr>(), 4309 SourceLocation(), 4310 SourceLocation()); 4311 4312 return false; 4313 } 4314 4315 static bool RefersToRValueRef(Expr *MemRef) { 4316 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4317 return Referenced->getType()->isRValueReferenceType(); 4318 } 4319 4320 static bool 4321 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4322 ImplicitInitializerKind ImplicitInitKind, 4323 FieldDecl *Field, IndirectFieldDecl *Indirect, 4324 CXXCtorInitializer *&CXXMemberInit) { 4325 if (Field->isInvalidDecl()) 4326 return true; 4327 4328 SourceLocation Loc = Constructor->getLocation(); 4329 4330 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4331 bool Moving = ImplicitInitKind == IIK_Move; 4332 ParmVarDecl *Param = Constructor->getParamDecl(0); 4333 QualType ParamType = Param->getType().getNonReferenceType(); 4334 4335 // Suppress copying zero-width bitfields. 4336 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4337 return false; 4338 4339 Expr *MemberExprBase = 4340 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4341 SourceLocation(), Param, false, 4342 Loc, ParamType, VK_LValue, nullptr); 4343 4344 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4345 4346 if (Moving) { 4347 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4348 } 4349 4350 // Build a reference to this field within the parameter. 4351 CXXScopeSpec SS; 4352 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4353 Sema::LookupMemberName); 4354 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4355 : cast<ValueDecl>(Field), AS_public); 4356 MemberLookup.resolveKind(); 4357 ExprResult CtorArg 4358 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4359 ParamType, Loc, 4360 /*IsArrow=*/false, 4361 SS, 4362 /*TemplateKWLoc=*/SourceLocation(), 4363 /*FirstQualifierInScope=*/nullptr, 4364 MemberLookup, 4365 /*TemplateArgs=*/nullptr, 4366 /*S*/nullptr); 4367 if (CtorArg.isInvalid()) 4368 return true; 4369 4370 // C++11 [class.copy]p15: 4371 // - if a member m has rvalue reference type T&&, it is direct-initialized 4372 // with static_cast<T&&>(x.m); 4373 if (RefersToRValueRef(CtorArg.get())) { 4374 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4375 } 4376 4377 InitializedEntity Entity = 4378 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4379 /*Implicit*/ true) 4380 : InitializedEntity::InitializeMember(Field, nullptr, 4381 /*Implicit*/ true); 4382 4383 // Direct-initialize to use the copy constructor. 4384 InitializationKind InitKind = 4385 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4386 4387 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4388 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4389 ExprResult MemberInit = 4390 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4391 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4392 if (MemberInit.isInvalid()) 4393 return true; 4394 4395 if (Indirect) 4396 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4397 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4398 else 4399 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4400 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4401 return false; 4402 } 4403 4404 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4405 "Unhandled implicit init kind!"); 4406 4407 QualType FieldBaseElementType = 4408 SemaRef.Context.getBaseElementType(Field->getType()); 4409 4410 if (FieldBaseElementType->isRecordType()) { 4411 InitializedEntity InitEntity = 4412 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4413 /*Implicit*/ true) 4414 : InitializedEntity::InitializeMember(Field, nullptr, 4415 /*Implicit*/ true); 4416 InitializationKind InitKind = 4417 InitializationKind::CreateDefault(Loc); 4418 4419 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4420 ExprResult MemberInit = 4421 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4422 4423 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4424 if (MemberInit.isInvalid()) 4425 return true; 4426 4427 if (Indirect) 4428 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4429 Indirect, Loc, 4430 Loc, 4431 MemberInit.get(), 4432 Loc); 4433 else 4434 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4435 Field, Loc, Loc, 4436 MemberInit.get(), 4437 Loc); 4438 return false; 4439 } 4440 4441 if (!Field->getParent()->isUnion()) { 4442 if (FieldBaseElementType->isReferenceType()) { 4443 SemaRef.Diag(Constructor->getLocation(), 4444 diag::err_uninitialized_member_in_ctor) 4445 << (int)Constructor->isImplicit() 4446 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4447 << 0 << Field->getDeclName(); 4448 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4449 return true; 4450 } 4451 4452 if (FieldBaseElementType.isConstQualified()) { 4453 SemaRef.Diag(Constructor->getLocation(), 4454 diag::err_uninitialized_member_in_ctor) 4455 << (int)Constructor->isImplicit() 4456 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4457 << 1 << Field->getDeclName(); 4458 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4459 return true; 4460 } 4461 } 4462 4463 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4464 // ARC and Weak: 4465 // Default-initialize Objective-C pointers to NULL. 4466 CXXMemberInit 4467 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4468 Loc, Loc, 4469 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4470 Loc); 4471 return false; 4472 } 4473 4474 // Nothing to initialize. 4475 CXXMemberInit = nullptr; 4476 return false; 4477 } 4478 4479 namespace { 4480 struct BaseAndFieldInfo { 4481 Sema &S; 4482 CXXConstructorDecl *Ctor; 4483 bool AnyErrorsInInits; 4484 ImplicitInitializerKind IIK; 4485 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4486 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4487 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4488 4489 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4490 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4491 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4492 if (Ctor->getInheritedConstructor()) 4493 IIK = IIK_Inherit; 4494 else if (Generated && Ctor->isCopyConstructor()) 4495 IIK = IIK_Copy; 4496 else if (Generated && Ctor->isMoveConstructor()) 4497 IIK = IIK_Move; 4498 else 4499 IIK = IIK_Default; 4500 } 4501 4502 bool isImplicitCopyOrMove() const { 4503 switch (IIK) { 4504 case IIK_Copy: 4505 case IIK_Move: 4506 return true; 4507 4508 case IIK_Default: 4509 case IIK_Inherit: 4510 return false; 4511 } 4512 4513 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4514 } 4515 4516 bool addFieldInitializer(CXXCtorInitializer *Init) { 4517 AllToInit.push_back(Init); 4518 4519 // Check whether this initializer makes the field "used". 4520 if (Init->getInit()->HasSideEffects(S.Context)) 4521 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4522 4523 return false; 4524 } 4525 4526 bool isInactiveUnionMember(FieldDecl *Field) { 4527 RecordDecl *Record = Field->getParent(); 4528 if (!Record->isUnion()) 4529 return false; 4530 4531 if (FieldDecl *Active = 4532 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4533 return Active != Field->getCanonicalDecl(); 4534 4535 // In an implicit copy or move constructor, ignore any in-class initializer. 4536 if (isImplicitCopyOrMove()) 4537 return true; 4538 4539 // If there's no explicit initialization, the field is active only if it 4540 // has an in-class initializer... 4541 if (Field->hasInClassInitializer()) 4542 return false; 4543 // ... or it's an anonymous struct or union whose class has an in-class 4544 // initializer. 4545 if (!Field->isAnonymousStructOrUnion()) 4546 return true; 4547 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4548 return !FieldRD->hasInClassInitializer(); 4549 } 4550 4551 /// \brief Determine whether the given field is, or is within, a union member 4552 /// that is inactive (because there was an initializer given for a different 4553 /// member of the union, or because the union was not initialized at all). 4554 bool isWithinInactiveUnionMember(FieldDecl *Field, 4555 IndirectFieldDecl *Indirect) { 4556 if (!Indirect) 4557 return isInactiveUnionMember(Field); 4558 4559 for (auto *C : Indirect->chain()) { 4560 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4561 if (Field && isInactiveUnionMember(Field)) 4562 return true; 4563 } 4564 return false; 4565 } 4566 }; 4567 } 4568 4569 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4570 /// array type. 4571 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4572 if (T->isIncompleteArrayType()) 4573 return true; 4574 4575 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4576 if (!ArrayT->getSize()) 4577 return true; 4578 4579 T = ArrayT->getElementType(); 4580 } 4581 4582 return false; 4583 } 4584 4585 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4586 FieldDecl *Field, 4587 IndirectFieldDecl *Indirect = nullptr) { 4588 if (Field->isInvalidDecl()) 4589 return false; 4590 4591 // Overwhelmingly common case: we have a direct initializer for this field. 4592 if (CXXCtorInitializer *Init = 4593 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4594 return Info.addFieldInitializer(Init); 4595 4596 // C++11 [class.base.init]p8: 4597 // if the entity is a non-static data member that has a 4598 // brace-or-equal-initializer and either 4599 // -- the constructor's class is a union and no other variant member of that 4600 // union is designated by a mem-initializer-id or 4601 // -- the constructor's class is not a union, and, if the entity is a member 4602 // of an anonymous union, no other member of that union is designated by 4603 // a mem-initializer-id, 4604 // the entity is initialized as specified in [dcl.init]. 4605 // 4606 // We also apply the same rules to handle anonymous structs within anonymous 4607 // unions. 4608 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4609 return false; 4610 4611 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4612 ExprResult DIE = 4613 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4614 if (DIE.isInvalid()) 4615 return true; 4616 CXXCtorInitializer *Init; 4617 if (Indirect) 4618 Init = new (SemaRef.Context) 4619 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4620 SourceLocation(), DIE.get(), SourceLocation()); 4621 else 4622 Init = new (SemaRef.Context) 4623 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4624 SourceLocation(), DIE.get(), SourceLocation()); 4625 return Info.addFieldInitializer(Init); 4626 } 4627 4628 // Don't initialize incomplete or zero-length arrays. 4629 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4630 return false; 4631 4632 // Don't try to build an implicit initializer if there were semantic 4633 // errors in any of the initializers (and therefore we might be 4634 // missing some that the user actually wrote). 4635 if (Info.AnyErrorsInInits) 4636 return false; 4637 4638 CXXCtorInitializer *Init = nullptr; 4639 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4640 Indirect, Init)) 4641 return true; 4642 4643 if (!Init) 4644 return false; 4645 4646 return Info.addFieldInitializer(Init); 4647 } 4648 4649 bool 4650 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4651 CXXCtorInitializer *Initializer) { 4652 assert(Initializer->isDelegatingInitializer()); 4653 Constructor->setNumCtorInitializers(1); 4654 CXXCtorInitializer **initializer = 4655 new (Context) CXXCtorInitializer*[1]; 4656 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4657 Constructor->setCtorInitializers(initializer); 4658 4659 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4660 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4661 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4662 } 4663 4664 DelegatingCtorDecls.push_back(Constructor); 4665 4666 DiagnoseUninitializedFields(*this, Constructor); 4667 4668 return false; 4669 } 4670 4671 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4672 ArrayRef<CXXCtorInitializer *> Initializers) { 4673 if (Constructor->isDependentContext()) { 4674 // Just store the initializers as written, they will be checked during 4675 // instantiation. 4676 if (!Initializers.empty()) { 4677 Constructor->setNumCtorInitializers(Initializers.size()); 4678 CXXCtorInitializer **baseOrMemberInitializers = 4679 new (Context) CXXCtorInitializer*[Initializers.size()]; 4680 memcpy(baseOrMemberInitializers, Initializers.data(), 4681 Initializers.size() * sizeof(CXXCtorInitializer*)); 4682 Constructor->setCtorInitializers(baseOrMemberInitializers); 4683 } 4684 4685 // Let template instantiation know whether we had errors. 4686 if (AnyErrors) 4687 Constructor->setInvalidDecl(); 4688 4689 return false; 4690 } 4691 4692 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4693 4694 // We need to build the initializer AST according to order of construction 4695 // and not what user specified in the Initializers list. 4696 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4697 if (!ClassDecl) 4698 return true; 4699 4700 bool HadError = false; 4701 4702 for (unsigned i = 0; i < Initializers.size(); i++) { 4703 CXXCtorInitializer *Member = Initializers[i]; 4704 4705 if (Member->isBaseInitializer()) 4706 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4707 else { 4708 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4709 4710 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4711 for (auto *C : F->chain()) { 4712 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4713 if (FD && FD->getParent()->isUnion()) 4714 Info.ActiveUnionMember.insert(std::make_pair( 4715 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4716 } 4717 } else if (FieldDecl *FD = Member->getMember()) { 4718 if (FD->getParent()->isUnion()) 4719 Info.ActiveUnionMember.insert(std::make_pair( 4720 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4721 } 4722 } 4723 } 4724 4725 // Keep track of the direct virtual bases. 4726 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4727 for (auto &I : ClassDecl->bases()) { 4728 if (I.isVirtual()) 4729 DirectVBases.insert(&I); 4730 } 4731 4732 // Push virtual bases before others. 4733 for (auto &VBase : ClassDecl->vbases()) { 4734 if (CXXCtorInitializer *Value 4735 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4736 // [class.base.init]p7, per DR257: 4737 // A mem-initializer where the mem-initializer-id names a virtual base 4738 // class is ignored during execution of a constructor of any class that 4739 // is not the most derived class. 4740 if (ClassDecl->isAbstract()) { 4741 // FIXME: Provide a fixit to remove the base specifier. This requires 4742 // tracking the location of the associated comma for a base specifier. 4743 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4744 << VBase.getType() << ClassDecl; 4745 DiagnoseAbstractType(ClassDecl); 4746 } 4747 4748 Info.AllToInit.push_back(Value); 4749 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4750 // [class.base.init]p8, per DR257: 4751 // If a given [...] base class is not named by a mem-initializer-id 4752 // [...] and the entity is not a virtual base class of an abstract 4753 // class, then [...] the entity is default-initialized. 4754 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4755 CXXCtorInitializer *CXXBaseInit; 4756 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4757 &VBase, IsInheritedVirtualBase, 4758 CXXBaseInit)) { 4759 HadError = true; 4760 continue; 4761 } 4762 4763 Info.AllToInit.push_back(CXXBaseInit); 4764 } 4765 } 4766 4767 // Non-virtual bases. 4768 for (auto &Base : ClassDecl->bases()) { 4769 // Virtuals are in the virtual base list and already constructed. 4770 if (Base.isVirtual()) 4771 continue; 4772 4773 if (CXXCtorInitializer *Value 4774 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4775 Info.AllToInit.push_back(Value); 4776 } else if (!AnyErrors) { 4777 CXXCtorInitializer *CXXBaseInit; 4778 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4779 &Base, /*IsInheritedVirtualBase=*/false, 4780 CXXBaseInit)) { 4781 HadError = true; 4782 continue; 4783 } 4784 4785 Info.AllToInit.push_back(CXXBaseInit); 4786 } 4787 } 4788 4789 // Fields. 4790 for (auto *Mem : ClassDecl->decls()) { 4791 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4792 // C++ [class.bit]p2: 4793 // A declaration for a bit-field that omits the identifier declares an 4794 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4795 // initialized. 4796 if (F->isUnnamedBitfield()) 4797 continue; 4798 4799 // If we're not generating the implicit copy/move constructor, then we'll 4800 // handle anonymous struct/union fields based on their individual 4801 // indirect fields. 4802 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4803 continue; 4804 4805 if (CollectFieldInitializer(*this, Info, F)) 4806 HadError = true; 4807 continue; 4808 } 4809 4810 // Beyond this point, we only consider default initialization. 4811 if (Info.isImplicitCopyOrMove()) 4812 continue; 4813 4814 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4815 if (F->getType()->isIncompleteArrayType()) { 4816 assert(ClassDecl->hasFlexibleArrayMember() && 4817 "Incomplete array type is not valid"); 4818 continue; 4819 } 4820 4821 // Initialize each field of an anonymous struct individually. 4822 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4823 HadError = true; 4824 4825 continue; 4826 } 4827 } 4828 4829 unsigned NumInitializers = Info.AllToInit.size(); 4830 if (NumInitializers > 0) { 4831 Constructor->setNumCtorInitializers(NumInitializers); 4832 CXXCtorInitializer **baseOrMemberInitializers = 4833 new (Context) CXXCtorInitializer*[NumInitializers]; 4834 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4835 NumInitializers * sizeof(CXXCtorInitializer*)); 4836 Constructor->setCtorInitializers(baseOrMemberInitializers); 4837 4838 // Constructors implicitly reference the base and member 4839 // destructors. 4840 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4841 Constructor->getParent()); 4842 } 4843 4844 return HadError; 4845 } 4846 4847 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4848 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4849 const RecordDecl *RD = RT->getDecl(); 4850 if (RD->isAnonymousStructOrUnion()) { 4851 for (auto *Field : RD->fields()) 4852 PopulateKeysForFields(Field, IdealInits); 4853 return; 4854 } 4855 } 4856 IdealInits.push_back(Field->getCanonicalDecl()); 4857 } 4858 4859 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4860 return Context.getCanonicalType(BaseType).getTypePtr(); 4861 } 4862 4863 static const void *GetKeyForMember(ASTContext &Context, 4864 CXXCtorInitializer *Member) { 4865 if (!Member->isAnyMemberInitializer()) 4866 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4867 4868 return Member->getAnyMember()->getCanonicalDecl(); 4869 } 4870 4871 static void DiagnoseBaseOrMemInitializerOrder( 4872 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4873 ArrayRef<CXXCtorInitializer *> Inits) { 4874 if (Constructor->getDeclContext()->isDependentContext()) 4875 return; 4876 4877 // Don't check initializers order unless the warning is enabled at the 4878 // location of at least one initializer. 4879 bool ShouldCheckOrder = false; 4880 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4881 CXXCtorInitializer *Init = Inits[InitIndex]; 4882 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4883 Init->getSourceLocation())) { 4884 ShouldCheckOrder = true; 4885 break; 4886 } 4887 } 4888 if (!ShouldCheckOrder) 4889 return; 4890 4891 // Build the list of bases and members in the order that they'll 4892 // actually be initialized. The explicit initializers should be in 4893 // this same order but may be missing things. 4894 SmallVector<const void*, 32> IdealInitKeys; 4895 4896 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4897 4898 // 1. Virtual bases. 4899 for (const auto &VBase : ClassDecl->vbases()) 4900 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4901 4902 // 2. Non-virtual bases. 4903 for (const auto &Base : ClassDecl->bases()) { 4904 if (Base.isVirtual()) 4905 continue; 4906 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4907 } 4908 4909 // 3. Direct fields. 4910 for (auto *Field : ClassDecl->fields()) { 4911 if (Field->isUnnamedBitfield()) 4912 continue; 4913 4914 PopulateKeysForFields(Field, IdealInitKeys); 4915 } 4916 4917 unsigned NumIdealInits = IdealInitKeys.size(); 4918 unsigned IdealIndex = 0; 4919 4920 CXXCtorInitializer *PrevInit = nullptr; 4921 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4922 CXXCtorInitializer *Init = Inits[InitIndex]; 4923 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4924 4925 // Scan forward to try to find this initializer in the idealized 4926 // initializers list. 4927 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4928 if (InitKey == IdealInitKeys[IdealIndex]) 4929 break; 4930 4931 // If we didn't find this initializer, it must be because we 4932 // scanned past it on a previous iteration. That can only 4933 // happen if we're out of order; emit a warning. 4934 if (IdealIndex == NumIdealInits && PrevInit) { 4935 Sema::SemaDiagnosticBuilder D = 4936 SemaRef.Diag(PrevInit->getSourceLocation(), 4937 diag::warn_initializer_out_of_order); 4938 4939 if (PrevInit->isAnyMemberInitializer()) 4940 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4941 else 4942 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4943 4944 if (Init->isAnyMemberInitializer()) 4945 D << 0 << Init->getAnyMember()->getDeclName(); 4946 else 4947 D << 1 << Init->getTypeSourceInfo()->getType(); 4948 4949 // Move back to the initializer's location in the ideal list. 4950 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4951 if (InitKey == IdealInitKeys[IdealIndex]) 4952 break; 4953 4954 assert(IdealIndex < NumIdealInits && 4955 "initializer not found in initializer list"); 4956 } 4957 4958 PrevInit = Init; 4959 } 4960 } 4961 4962 namespace { 4963 bool CheckRedundantInit(Sema &S, 4964 CXXCtorInitializer *Init, 4965 CXXCtorInitializer *&PrevInit) { 4966 if (!PrevInit) { 4967 PrevInit = Init; 4968 return false; 4969 } 4970 4971 if (FieldDecl *Field = Init->getAnyMember()) 4972 S.Diag(Init->getSourceLocation(), 4973 diag::err_multiple_mem_initialization) 4974 << Field->getDeclName() 4975 << Init->getSourceRange(); 4976 else { 4977 const Type *BaseClass = Init->getBaseClass(); 4978 assert(BaseClass && "neither field nor base"); 4979 S.Diag(Init->getSourceLocation(), 4980 diag::err_multiple_base_initialization) 4981 << QualType(BaseClass, 0) 4982 << Init->getSourceRange(); 4983 } 4984 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4985 << 0 << PrevInit->getSourceRange(); 4986 4987 return true; 4988 } 4989 4990 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4991 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4992 4993 bool CheckRedundantUnionInit(Sema &S, 4994 CXXCtorInitializer *Init, 4995 RedundantUnionMap &Unions) { 4996 FieldDecl *Field = Init->getAnyMember(); 4997 RecordDecl *Parent = Field->getParent(); 4998 NamedDecl *Child = Field; 4999 5000 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5001 if (Parent->isUnion()) { 5002 UnionEntry &En = Unions[Parent]; 5003 if (En.first && En.first != Child) { 5004 S.Diag(Init->getSourceLocation(), 5005 diag::err_multiple_mem_union_initialization) 5006 << Field->getDeclName() 5007 << Init->getSourceRange(); 5008 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5009 << 0 << En.second->getSourceRange(); 5010 return true; 5011 } 5012 if (!En.first) { 5013 En.first = Child; 5014 En.second = Init; 5015 } 5016 if (!Parent->isAnonymousStructOrUnion()) 5017 return false; 5018 } 5019 5020 Child = Parent; 5021 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5022 } 5023 5024 return false; 5025 } 5026 } 5027 5028 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5029 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5030 SourceLocation ColonLoc, 5031 ArrayRef<CXXCtorInitializer*> MemInits, 5032 bool AnyErrors) { 5033 if (!ConstructorDecl) 5034 return; 5035 5036 AdjustDeclIfTemplate(ConstructorDecl); 5037 5038 CXXConstructorDecl *Constructor 5039 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5040 5041 if (!Constructor) { 5042 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5043 return; 5044 } 5045 5046 // Mapping for the duplicate initializers check. 5047 // For member initializers, this is keyed with a FieldDecl*. 5048 // For base initializers, this is keyed with a Type*. 5049 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5050 5051 // Mapping for the inconsistent anonymous-union initializers check. 5052 RedundantUnionMap MemberUnions; 5053 5054 bool HadError = false; 5055 for (unsigned i = 0; i < MemInits.size(); i++) { 5056 CXXCtorInitializer *Init = MemInits[i]; 5057 5058 // Set the source order index. 5059 Init->setSourceOrder(i); 5060 5061 if (Init->isAnyMemberInitializer()) { 5062 const void *Key = GetKeyForMember(Context, Init); 5063 if (CheckRedundantInit(*this, Init, Members[Key]) || 5064 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5065 HadError = true; 5066 } else if (Init->isBaseInitializer()) { 5067 const void *Key = GetKeyForMember(Context, Init); 5068 if (CheckRedundantInit(*this, Init, Members[Key])) 5069 HadError = true; 5070 } else { 5071 assert(Init->isDelegatingInitializer()); 5072 // This must be the only initializer 5073 if (MemInits.size() != 1) { 5074 Diag(Init->getSourceLocation(), 5075 diag::err_delegating_initializer_alone) 5076 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5077 // We will treat this as being the only initializer. 5078 } 5079 SetDelegatingInitializer(Constructor, MemInits[i]); 5080 // Return immediately as the initializer is set. 5081 return; 5082 } 5083 } 5084 5085 if (HadError) 5086 return; 5087 5088 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5089 5090 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5091 5092 DiagnoseUninitializedFields(*this, Constructor); 5093 } 5094 5095 void 5096 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5097 CXXRecordDecl *ClassDecl) { 5098 // Ignore dependent contexts. Also ignore unions, since their members never 5099 // have destructors implicitly called. 5100 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5101 return; 5102 5103 // FIXME: all the access-control diagnostics are positioned on the 5104 // field/base declaration. That's probably good; that said, the 5105 // user might reasonably want to know why the destructor is being 5106 // emitted, and we currently don't say. 5107 5108 // Non-static data members. 5109 for (auto *Field : ClassDecl->fields()) { 5110 if (Field->isInvalidDecl()) 5111 continue; 5112 5113 // Don't destroy incomplete or zero-length arrays. 5114 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5115 continue; 5116 5117 QualType FieldType = Context.getBaseElementType(Field->getType()); 5118 5119 const RecordType* RT = FieldType->getAs<RecordType>(); 5120 if (!RT) 5121 continue; 5122 5123 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5124 if (FieldClassDecl->isInvalidDecl()) 5125 continue; 5126 if (FieldClassDecl->hasIrrelevantDestructor()) 5127 continue; 5128 // The destructor for an implicit anonymous union member is never invoked. 5129 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5130 continue; 5131 5132 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5133 assert(Dtor && "No dtor found for FieldClassDecl!"); 5134 CheckDestructorAccess(Field->getLocation(), Dtor, 5135 PDiag(diag::err_access_dtor_field) 5136 << Field->getDeclName() 5137 << FieldType); 5138 5139 MarkFunctionReferenced(Location, Dtor); 5140 DiagnoseUseOfDecl(Dtor, Location); 5141 } 5142 5143 // We only potentially invoke the destructors of potentially constructed 5144 // subobjects. 5145 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5146 5147 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5148 5149 // Bases. 5150 for (const auto &Base : ClassDecl->bases()) { 5151 // Bases are always records in a well-formed non-dependent class. 5152 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5153 5154 // Remember direct virtual bases. 5155 if (Base.isVirtual()) { 5156 if (!VisitVirtualBases) 5157 continue; 5158 DirectVirtualBases.insert(RT); 5159 } 5160 5161 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5162 // If our base class is invalid, we probably can't get its dtor anyway. 5163 if (BaseClassDecl->isInvalidDecl()) 5164 continue; 5165 if (BaseClassDecl->hasIrrelevantDestructor()) 5166 continue; 5167 5168 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5169 assert(Dtor && "No dtor found for BaseClassDecl!"); 5170 5171 // FIXME: caret should be on the start of the class name 5172 CheckDestructorAccess(Base.getLocStart(), Dtor, 5173 PDiag(diag::err_access_dtor_base) 5174 << Base.getType() 5175 << Base.getSourceRange(), 5176 Context.getTypeDeclType(ClassDecl)); 5177 5178 MarkFunctionReferenced(Location, Dtor); 5179 DiagnoseUseOfDecl(Dtor, Location); 5180 } 5181 5182 if (!VisitVirtualBases) 5183 return; 5184 5185 // Virtual bases. 5186 for (const auto &VBase : ClassDecl->vbases()) { 5187 // Bases are always records in a well-formed non-dependent class. 5188 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5189 5190 // Ignore direct virtual bases. 5191 if (DirectVirtualBases.count(RT)) 5192 continue; 5193 5194 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5195 // If our base class is invalid, we probably can't get its dtor anyway. 5196 if (BaseClassDecl->isInvalidDecl()) 5197 continue; 5198 if (BaseClassDecl->hasIrrelevantDestructor()) 5199 continue; 5200 5201 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5202 assert(Dtor && "No dtor found for BaseClassDecl!"); 5203 if (CheckDestructorAccess( 5204 ClassDecl->getLocation(), Dtor, 5205 PDiag(diag::err_access_dtor_vbase) 5206 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5207 Context.getTypeDeclType(ClassDecl)) == 5208 AR_accessible) { 5209 CheckDerivedToBaseConversion( 5210 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5211 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5212 SourceRange(), DeclarationName(), nullptr); 5213 } 5214 5215 MarkFunctionReferenced(Location, Dtor); 5216 DiagnoseUseOfDecl(Dtor, Location); 5217 } 5218 } 5219 5220 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5221 if (!CDtorDecl) 5222 return; 5223 5224 if (CXXConstructorDecl *Constructor 5225 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5226 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5227 DiagnoseUninitializedFields(*this, Constructor); 5228 } 5229 } 5230 5231 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5232 if (!getLangOpts().CPlusPlus) 5233 return false; 5234 5235 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5236 if (!RD) 5237 return false; 5238 5239 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5240 // class template specialization here, but doing so breaks a lot of code. 5241 5242 // We can't answer whether something is abstract until it has a 5243 // definition. If it's currently being defined, we'll walk back 5244 // over all the declarations when we have a full definition. 5245 const CXXRecordDecl *Def = RD->getDefinition(); 5246 if (!Def || Def->isBeingDefined()) 5247 return false; 5248 5249 return RD->isAbstract(); 5250 } 5251 5252 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5253 TypeDiagnoser &Diagnoser) { 5254 if (!isAbstractType(Loc, T)) 5255 return false; 5256 5257 T = Context.getBaseElementType(T); 5258 Diagnoser.diagnose(*this, Loc, T); 5259 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5260 return true; 5261 } 5262 5263 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5264 // Check if we've already emitted the list of pure virtual functions 5265 // for this class. 5266 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5267 return; 5268 5269 // If the diagnostic is suppressed, don't emit the notes. We're only 5270 // going to emit them once, so try to attach them to a diagnostic we're 5271 // actually going to show. 5272 if (Diags.isLastDiagnosticIgnored()) 5273 return; 5274 5275 CXXFinalOverriderMap FinalOverriders; 5276 RD->getFinalOverriders(FinalOverriders); 5277 5278 // Keep a set of seen pure methods so we won't diagnose the same method 5279 // more than once. 5280 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5281 5282 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5283 MEnd = FinalOverriders.end(); 5284 M != MEnd; 5285 ++M) { 5286 for (OverridingMethods::iterator SO = M->second.begin(), 5287 SOEnd = M->second.end(); 5288 SO != SOEnd; ++SO) { 5289 // C++ [class.abstract]p4: 5290 // A class is abstract if it contains or inherits at least one 5291 // pure virtual function for which the final overrider is pure 5292 // virtual. 5293 5294 // 5295 if (SO->second.size() != 1) 5296 continue; 5297 5298 if (!SO->second.front().Method->isPure()) 5299 continue; 5300 5301 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5302 continue; 5303 5304 Diag(SO->second.front().Method->getLocation(), 5305 diag::note_pure_virtual_function) 5306 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5307 } 5308 } 5309 5310 if (!PureVirtualClassDiagSet) 5311 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5312 PureVirtualClassDiagSet->insert(RD); 5313 } 5314 5315 namespace { 5316 struct AbstractUsageInfo { 5317 Sema &S; 5318 CXXRecordDecl *Record; 5319 CanQualType AbstractType; 5320 bool Invalid; 5321 5322 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5323 : S(S), Record(Record), 5324 AbstractType(S.Context.getCanonicalType( 5325 S.Context.getTypeDeclType(Record))), 5326 Invalid(false) {} 5327 5328 void DiagnoseAbstractType() { 5329 if (Invalid) return; 5330 S.DiagnoseAbstractType(Record); 5331 Invalid = true; 5332 } 5333 5334 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5335 }; 5336 5337 struct CheckAbstractUsage { 5338 AbstractUsageInfo &Info; 5339 const NamedDecl *Ctx; 5340 5341 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5342 : Info(Info), Ctx(Ctx) {} 5343 5344 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5345 switch (TL.getTypeLocClass()) { 5346 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5347 #define TYPELOC(CLASS, PARENT) \ 5348 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5349 #include "clang/AST/TypeLocNodes.def" 5350 } 5351 } 5352 5353 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5354 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5355 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5356 if (!TL.getParam(I)) 5357 continue; 5358 5359 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5360 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5361 } 5362 } 5363 5364 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5365 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5366 } 5367 5368 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5369 // Visit the type parameters from a permissive context. 5370 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5371 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5372 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5373 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5374 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5375 // TODO: other template argument types? 5376 } 5377 } 5378 5379 // Visit pointee types from a permissive context. 5380 #define CheckPolymorphic(Type) \ 5381 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5382 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5383 } 5384 CheckPolymorphic(PointerTypeLoc) 5385 CheckPolymorphic(ReferenceTypeLoc) 5386 CheckPolymorphic(MemberPointerTypeLoc) 5387 CheckPolymorphic(BlockPointerTypeLoc) 5388 CheckPolymorphic(AtomicTypeLoc) 5389 5390 /// Handle all the types we haven't given a more specific 5391 /// implementation for above. 5392 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5393 // Every other kind of type that we haven't called out already 5394 // that has an inner type is either (1) sugar or (2) contains that 5395 // inner type in some way as a subobject. 5396 if (TypeLoc Next = TL.getNextTypeLoc()) 5397 return Visit(Next, Sel); 5398 5399 // If there's no inner type and we're in a permissive context, 5400 // don't diagnose. 5401 if (Sel == Sema::AbstractNone) return; 5402 5403 // Check whether the type matches the abstract type. 5404 QualType T = TL.getType(); 5405 if (T->isArrayType()) { 5406 Sel = Sema::AbstractArrayType; 5407 T = Info.S.Context.getBaseElementType(T); 5408 } 5409 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5410 if (CT != Info.AbstractType) return; 5411 5412 // It matched; do some magic. 5413 if (Sel == Sema::AbstractArrayType) { 5414 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5415 << T << TL.getSourceRange(); 5416 } else { 5417 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5418 << Sel << T << TL.getSourceRange(); 5419 } 5420 Info.DiagnoseAbstractType(); 5421 } 5422 }; 5423 5424 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5425 Sema::AbstractDiagSelID Sel) { 5426 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5427 } 5428 5429 } 5430 5431 /// Check for invalid uses of an abstract type in a method declaration. 5432 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5433 CXXMethodDecl *MD) { 5434 // No need to do the check on definitions, which require that 5435 // the return/param types be complete. 5436 if (MD->doesThisDeclarationHaveABody()) 5437 return; 5438 5439 // For safety's sake, just ignore it if we don't have type source 5440 // information. This should never happen for non-implicit methods, 5441 // but... 5442 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5443 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5444 } 5445 5446 /// Check for invalid uses of an abstract type within a class definition. 5447 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5448 CXXRecordDecl *RD) { 5449 for (auto *D : RD->decls()) { 5450 if (D->isImplicit()) continue; 5451 5452 // Methods and method templates. 5453 if (isa<CXXMethodDecl>(D)) { 5454 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5455 } else if (isa<FunctionTemplateDecl>(D)) { 5456 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5457 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5458 5459 // Fields and static variables. 5460 } else if (isa<FieldDecl>(D)) { 5461 FieldDecl *FD = cast<FieldDecl>(D); 5462 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5463 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5464 } else if (isa<VarDecl>(D)) { 5465 VarDecl *VD = cast<VarDecl>(D); 5466 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5467 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5468 5469 // Nested classes and class templates. 5470 } else if (isa<CXXRecordDecl>(D)) { 5471 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5472 } else if (isa<ClassTemplateDecl>(D)) { 5473 CheckAbstractClassUsage(Info, 5474 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5475 } 5476 } 5477 } 5478 5479 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5480 Attr *ClassAttr = getDLLAttr(Class); 5481 if (!ClassAttr) 5482 return; 5483 5484 assert(ClassAttr->getKind() == attr::DLLExport); 5485 5486 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5487 5488 if (TSK == TSK_ExplicitInstantiationDeclaration) 5489 // Don't go any further if this is just an explicit instantiation 5490 // declaration. 5491 return; 5492 5493 for (Decl *Member : Class->decls()) { 5494 // Defined static variables that are members of an exported base 5495 // class must be marked export too. 5496 auto *VD = dyn_cast<VarDecl>(Member); 5497 if (VD && Member->getAttr<DLLExportAttr>() && 5498 VD->getStorageClass() == SC_Static && 5499 TSK == TSK_ImplicitInstantiation) 5500 S.MarkVariableReferenced(VD->getLocation(), VD); 5501 5502 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5503 if (!MD) 5504 continue; 5505 5506 if (Member->getAttr<DLLExportAttr>()) { 5507 if (MD->isUserProvided()) { 5508 // Instantiate non-default class member functions ... 5509 5510 // .. except for certain kinds of template specializations. 5511 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5512 continue; 5513 5514 S.MarkFunctionReferenced(Class->getLocation(), MD); 5515 5516 // The function will be passed to the consumer when its definition is 5517 // encountered. 5518 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5519 MD->isCopyAssignmentOperator() || 5520 MD->isMoveAssignmentOperator()) { 5521 // Synthesize and instantiate non-trivial implicit methods, explicitly 5522 // defaulted methods, and the copy and move assignment operators. The 5523 // latter are exported even if they are trivial, because the address of 5524 // an operator can be taken and should compare equal across libraries. 5525 DiagnosticErrorTrap Trap(S.Diags); 5526 S.MarkFunctionReferenced(Class->getLocation(), MD); 5527 if (Trap.hasErrorOccurred()) { 5528 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5529 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5530 break; 5531 } 5532 5533 // There is no later point when we will see the definition of this 5534 // function, so pass it to the consumer now. 5535 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5536 } 5537 } 5538 } 5539 } 5540 5541 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5542 CXXRecordDecl *Class) { 5543 // Only the MS ABI has default constructor closures, so we don't need to do 5544 // this semantic checking anywhere else. 5545 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5546 return; 5547 5548 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5549 for (Decl *Member : Class->decls()) { 5550 // Look for exported default constructors. 5551 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5552 if (!CD || !CD->isDefaultConstructor()) 5553 continue; 5554 auto *Attr = CD->getAttr<DLLExportAttr>(); 5555 if (!Attr) 5556 continue; 5557 5558 // If the class is non-dependent, mark the default arguments as ODR-used so 5559 // that we can properly codegen the constructor closure. 5560 if (!Class->isDependentContext()) { 5561 for (ParmVarDecl *PD : CD->parameters()) { 5562 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5563 S.DiscardCleanupsInEvaluationContext(); 5564 } 5565 } 5566 5567 if (LastExportedDefaultCtor) { 5568 S.Diag(LastExportedDefaultCtor->getLocation(), 5569 diag::err_attribute_dll_ambiguous_default_ctor) 5570 << Class; 5571 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5572 << CD->getDeclName(); 5573 return; 5574 } 5575 LastExportedDefaultCtor = CD; 5576 } 5577 } 5578 5579 /// \brief Check class-level dllimport/dllexport attribute. 5580 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5581 Attr *ClassAttr = getDLLAttr(Class); 5582 5583 // MSVC inherits DLL attributes to partial class template specializations. 5584 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5585 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5586 if (Attr *TemplateAttr = 5587 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5588 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5589 A->setInherited(true); 5590 ClassAttr = A; 5591 } 5592 } 5593 } 5594 5595 if (!ClassAttr) 5596 return; 5597 5598 if (!Class->isExternallyVisible()) { 5599 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5600 << Class << ClassAttr; 5601 return; 5602 } 5603 5604 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5605 !ClassAttr->isInherited()) { 5606 // Diagnose dll attributes on members of class with dll attribute. 5607 for (Decl *Member : Class->decls()) { 5608 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5609 continue; 5610 InheritableAttr *MemberAttr = getDLLAttr(Member); 5611 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5612 continue; 5613 5614 Diag(MemberAttr->getLocation(), 5615 diag::err_attribute_dll_member_of_dll_class) 5616 << MemberAttr << ClassAttr; 5617 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5618 Member->setInvalidDecl(); 5619 } 5620 } 5621 5622 if (Class->getDescribedClassTemplate()) 5623 // Don't inherit dll attribute until the template is instantiated. 5624 return; 5625 5626 // The class is either imported or exported. 5627 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5628 5629 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5630 5631 // Ignore explicit dllexport on explicit class template instantiation declarations. 5632 if (ClassExported && !ClassAttr->isInherited() && 5633 TSK == TSK_ExplicitInstantiationDeclaration) { 5634 Class->dropAttr<DLLExportAttr>(); 5635 return; 5636 } 5637 5638 // Force declaration of implicit members so they can inherit the attribute. 5639 ForceDeclarationOfImplicitMembers(Class); 5640 5641 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5642 // seem to be true in practice? 5643 5644 for (Decl *Member : Class->decls()) { 5645 VarDecl *VD = dyn_cast<VarDecl>(Member); 5646 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5647 5648 // Only methods and static fields inherit the attributes. 5649 if (!VD && !MD) 5650 continue; 5651 5652 if (MD) { 5653 // Don't process deleted methods. 5654 if (MD->isDeleted()) 5655 continue; 5656 5657 if (MD->isInlined()) { 5658 // MinGW does not import or export inline methods. 5659 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5660 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5661 continue; 5662 5663 // MSVC versions before 2015 don't export the move assignment operators 5664 // and move constructor, so don't attempt to import/export them if 5665 // we have a definition. 5666 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5667 if ((MD->isMoveAssignmentOperator() || 5668 (Ctor && Ctor->isMoveConstructor())) && 5669 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5670 continue; 5671 5672 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5673 // operator is exported anyway. 5674 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5675 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5676 continue; 5677 } 5678 } 5679 5680 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5681 continue; 5682 5683 if (!getDLLAttr(Member)) { 5684 auto *NewAttr = 5685 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5686 NewAttr->setInherited(true); 5687 Member->addAttr(NewAttr); 5688 5689 if (MD) { 5690 // Propagate DLLAttr to friend re-declarations of MD that have already 5691 // been constructed. 5692 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5693 FD = FD->getPreviousDecl()) { 5694 if (FD->getFriendObjectKind() == Decl::FOK_None) 5695 continue; 5696 assert(!getDLLAttr(FD) && 5697 "friend re-decl should not already have a DLLAttr"); 5698 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5699 NewAttr->setInherited(true); 5700 FD->addAttr(NewAttr); 5701 } 5702 } 5703 } 5704 } 5705 5706 if (ClassExported) 5707 DelayedDllExportClasses.push_back(Class); 5708 } 5709 5710 /// \brief Perform propagation of DLL attributes from a derived class to a 5711 /// templated base class for MS compatibility. 5712 void Sema::propagateDLLAttrToBaseClassTemplate( 5713 CXXRecordDecl *Class, Attr *ClassAttr, 5714 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5715 if (getDLLAttr( 5716 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5717 // If the base class template has a DLL attribute, don't try to change it. 5718 return; 5719 } 5720 5721 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5722 if (!getDLLAttr(BaseTemplateSpec) && 5723 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5724 TSK == TSK_ImplicitInstantiation)) { 5725 // The template hasn't been instantiated yet (or it has, but only as an 5726 // explicit instantiation declaration or implicit instantiation, which means 5727 // we haven't codegenned any members yet), so propagate the attribute. 5728 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5729 NewAttr->setInherited(true); 5730 BaseTemplateSpec->addAttr(NewAttr); 5731 5732 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5733 // needs to be run again to work see the new attribute. Otherwise this will 5734 // get run whenever the template is instantiated. 5735 if (TSK != TSK_Undeclared) 5736 checkClassLevelDLLAttribute(BaseTemplateSpec); 5737 5738 return; 5739 } 5740 5741 if (getDLLAttr(BaseTemplateSpec)) { 5742 // The template has already been specialized or instantiated with an 5743 // attribute, explicitly or through propagation. We should not try to change 5744 // it. 5745 return; 5746 } 5747 5748 // The template was previously instantiated or explicitly specialized without 5749 // a dll attribute, It's too late for us to add an attribute, so warn that 5750 // this is unsupported. 5751 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5752 << BaseTemplateSpec->isExplicitSpecialization(); 5753 Diag(ClassAttr->getLocation(), diag::note_attribute); 5754 if (BaseTemplateSpec->isExplicitSpecialization()) { 5755 Diag(BaseTemplateSpec->getLocation(), 5756 diag::note_template_class_explicit_specialization_was_here) 5757 << BaseTemplateSpec; 5758 } else { 5759 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5760 diag::note_template_class_instantiation_was_here) 5761 << BaseTemplateSpec; 5762 } 5763 } 5764 5765 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5766 SourceLocation DefaultLoc) { 5767 switch (S.getSpecialMember(MD)) { 5768 case Sema::CXXDefaultConstructor: 5769 S.DefineImplicitDefaultConstructor(DefaultLoc, 5770 cast<CXXConstructorDecl>(MD)); 5771 break; 5772 case Sema::CXXCopyConstructor: 5773 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5774 break; 5775 case Sema::CXXCopyAssignment: 5776 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5777 break; 5778 case Sema::CXXDestructor: 5779 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5780 break; 5781 case Sema::CXXMoveConstructor: 5782 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5783 break; 5784 case Sema::CXXMoveAssignment: 5785 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5786 break; 5787 case Sema::CXXInvalid: 5788 llvm_unreachable("Invalid special member."); 5789 } 5790 } 5791 5792 /// Determine whether a type is permitted to be passed or returned in 5793 /// registers, per C++ [class.temporary]p3. 5794 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5795 if (D->isDependentType() || D->isInvalidDecl()) 5796 return false; 5797 5798 // Per C++ [class.temporary]p3, the relevant condition is: 5799 // each copy constructor, move constructor, and destructor of X is 5800 // either trivial or deleted, and X has at least one non-deleted copy 5801 // or move constructor 5802 bool HasNonDeletedCopyOrMove = false; 5803 5804 if (D->needsImplicitCopyConstructor() && 5805 !D->defaultedCopyConstructorIsDeleted()) { 5806 if (!D->hasTrivialCopyConstructorForCall()) 5807 return false; 5808 HasNonDeletedCopyOrMove = true; 5809 } 5810 5811 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5812 !D->defaultedMoveConstructorIsDeleted()) { 5813 if (!D->hasTrivialMoveConstructorForCall()) 5814 return false; 5815 HasNonDeletedCopyOrMove = true; 5816 } 5817 5818 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5819 !D->hasTrivialDestructorForCall()) 5820 return false; 5821 5822 for (const CXXMethodDecl *MD : D->methods()) { 5823 if (MD->isDeleted()) 5824 continue; 5825 5826 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5827 if (CD && CD->isCopyOrMoveConstructor()) 5828 HasNonDeletedCopyOrMove = true; 5829 else if (!isa<CXXDestructorDecl>(MD)) 5830 continue; 5831 5832 if (!MD->isTrivialForCall()) 5833 return false; 5834 } 5835 5836 return HasNonDeletedCopyOrMove; 5837 } 5838 5839 /// \brief Perform semantic checks on a class definition that has been 5840 /// completing, introducing implicitly-declared members, checking for 5841 /// abstract types, etc. 5842 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5843 if (!Record) 5844 return; 5845 5846 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5847 AbstractUsageInfo Info(*this, Record); 5848 CheckAbstractClassUsage(Info, Record); 5849 } 5850 5851 // If this is not an aggregate type and has no user-declared constructor, 5852 // complain about any non-static data members of reference or const scalar 5853 // type, since they will never get initializers. 5854 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5855 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5856 !Record->isLambda()) { 5857 bool Complained = false; 5858 for (const auto *F : Record->fields()) { 5859 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5860 continue; 5861 5862 if (F->getType()->isReferenceType() || 5863 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5864 if (!Complained) { 5865 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5866 << Record->getTagKind() << Record; 5867 Complained = true; 5868 } 5869 5870 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5871 << F->getType()->isReferenceType() 5872 << F->getDeclName(); 5873 } 5874 } 5875 } 5876 5877 if (Record->getIdentifier()) { 5878 // C++ [class.mem]p13: 5879 // If T is the name of a class, then each of the following shall have a 5880 // name different from T: 5881 // - every member of every anonymous union that is a member of class T. 5882 // 5883 // C++ [class.mem]p14: 5884 // In addition, if class T has a user-declared constructor (12.1), every 5885 // non-static data member of class T shall have a name different from T. 5886 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5887 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5888 ++I) { 5889 NamedDecl *D = *I; 5890 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5891 isa<IndirectFieldDecl>(D)) { 5892 Diag(D->getLocation(), diag::err_member_name_of_class) 5893 << D->getDeclName(); 5894 break; 5895 } 5896 } 5897 } 5898 5899 // Warn if the class has virtual methods but non-virtual public destructor. 5900 if (Record->isPolymorphic() && !Record->isDependentType()) { 5901 CXXDestructorDecl *dtor = Record->getDestructor(); 5902 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5903 !Record->hasAttr<FinalAttr>()) 5904 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5905 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5906 } 5907 5908 if (Record->isAbstract()) { 5909 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5910 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5911 << FA->isSpelledAsSealed(); 5912 DiagnoseAbstractType(Record); 5913 } 5914 } 5915 5916 // Set HasTrivialSpecialMemberForCall if the record has attribute 5917 // "trivial_abi". 5918 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 5919 5920 if (HasTrivialABI) 5921 Record->setHasTrivialSpecialMemberForCall(); 5922 5923 bool HasMethodWithOverrideControl = false, 5924 HasOverridingMethodWithoutOverrideControl = false; 5925 if (!Record->isDependentType()) { 5926 for (auto *M : Record->methods()) { 5927 // See if a method overloads virtual methods in a base 5928 // class without overriding any. 5929 if (!M->isStatic()) 5930 DiagnoseHiddenVirtualMethods(M); 5931 if (M->hasAttr<OverrideAttr>()) 5932 HasMethodWithOverrideControl = true; 5933 else if (M->size_overridden_methods() > 0) 5934 HasOverridingMethodWithoutOverrideControl = true; 5935 // Check whether the explicitly-defaulted special members are valid. 5936 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5937 CheckExplicitlyDefaultedSpecialMember(M); 5938 5939 // For an explicitly defaulted or deleted special member, we defer 5940 // determining triviality until the class is complete. That time is now! 5941 CXXSpecialMember CSM = getSpecialMember(M); 5942 if (!M->isImplicit() && !M->isUserProvided()) { 5943 if (CSM != CXXInvalid) { 5944 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5945 // Inform the class that we've finished declaring this member. 5946 Record->finishedDefaultedOrDeletedMember(M); 5947 M->setTrivialForCall( 5948 HasTrivialABI || 5949 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 5950 Record->setTrivialForCallFlags(M); 5951 } 5952 } 5953 5954 // Set triviality for the purpose of calls if this is a user-provided 5955 // copy/move constructor or destructor. 5956 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 5957 CSM == CXXDestructor) && M->isUserProvided()) { 5958 M->setTrivialForCall(HasTrivialABI); 5959 Record->setTrivialForCallFlags(M); 5960 } 5961 5962 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5963 M->hasAttr<DLLExportAttr>()) { 5964 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5965 M->isTrivial() && 5966 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5967 CSM == CXXDestructor)) 5968 M->dropAttr<DLLExportAttr>(); 5969 5970 if (M->hasAttr<DLLExportAttr>()) { 5971 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5972 ActOnFinishInlineFunctionDef(M); 5973 } 5974 } 5975 } 5976 } 5977 5978 if (HasMethodWithOverrideControl && 5979 HasOverridingMethodWithoutOverrideControl) { 5980 // At least one method has the 'override' control declared. 5981 // Diagnose all other overridden methods which do not have 'override' specified on them. 5982 for (auto *M : Record->methods()) 5983 DiagnoseAbsenceOfOverrideControl(M); 5984 } 5985 5986 // ms_struct is a request to use the same ABI rules as MSVC. Check 5987 // whether this class uses any C++ features that are implemented 5988 // completely differently in MSVC, and if so, emit a diagnostic. 5989 // That diagnostic defaults to an error, but we allow projects to 5990 // map it down to a warning (or ignore it). It's a fairly common 5991 // practice among users of the ms_struct pragma to mass-annotate 5992 // headers, sweeping up a bunch of types that the project doesn't 5993 // really rely on MSVC-compatible layout for. We must therefore 5994 // support "ms_struct except for C++ stuff" as a secondary ABI. 5995 if (Record->isMsStruct(Context) && 5996 (Record->isPolymorphic() || Record->getNumBases())) { 5997 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5998 } 5999 6000 checkClassLevelDLLAttribute(Record); 6001 6002 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 6003 } 6004 6005 /// Look up the special member function that would be called by a special 6006 /// member function for a subobject of class type. 6007 /// 6008 /// \param Class The class type of the subobject. 6009 /// \param CSM The kind of special member function. 6010 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6011 /// \param ConstRHS True if this is a copy operation with a const object 6012 /// on its RHS, that is, if the argument to the outer special member 6013 /// function is 'const' and this is not a field marked 'mutable'. 6014 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6015 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6016 unsigned FieldQuals, bool ConstRHS) { 6017 unsigned LHSQuals = 0; 6018 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6019 LHSQuals = FieldQuals; 6020 6021 unsigned RHSQuals = FieldQuals; 6022 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6023 RHSQuals = 0; 6024 else if (ConstRHS) 6025 RHSQuals |= Qualifiers::Const; 6026 6027 return S.LookupSpecialMember(Class, CSM, 6028 RHSQuals & Qualifiers::Const, 6029 RHSQuals & Qualifiers::Volatile, 6030 false, 6031 LHSQuals & Qualifiers::Const, 6032 LHSQuals & Qualifiers::Volatile); 6033 } 6034 6035 class Sema::InheritedConstructorInfo { 6036 Sema &S; 6037 SourceLocation UseLoc; 6038 6039 /// A mapping from the base classes through which the constructor was 6040 /// inherited to the using shadow declaration in that base class (or a null 6041 /// pointer if the constructor was declared in that base class). 6042 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6043 InheritedFromBases; 6044 6045 public: 6046 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6047 ConstructorUsingShadowDecl *Shadow) 6048 : S(S), UseLoc(UseLoc) { 6049 bool DiagnosedMultipleConstructedBases = false; 6050 CXXRecordDecl *ConstructedBase = nullptr; 6051 UsingDecl *ConstructedBaseUsing = nullptr; 6052 6053 // Find the set of such base class subobjects and check that there's a 6054 // unique constructed subobject. 6055 for (auto *D : Shadow->redecls()) { 6056 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6057 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6058 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6059 6060 InheritedFromBases.insert( 6061 std::make_pair(DNominatedBase->getCanonicalDecl(), 6062 DShadow->getNominatedBaseClassShadowDecl())); 6063 if (DShadow->constructsVirtualBase()) 6064 InheritedFromBases.insert( 6065 std::make_pair(DConstructedBase->getCanonicalDecl(), 6066 DShadow->getConstructedBaseClassShadowDecl())); 6067 else 6068 assert(DNominatedBase == DConstructedBase); 6069 6070 // [class.inhctor.init]p2: 6071 // If the constructor was inherited from multiple base class subobjects 6072 // of type B, the program is ill-formed. 6073 if (!ConstructedBase) { 6074 ConstructedBase = DConstructedBase; 6075 ConstructedBaseUsing = D->getUsingDecl(); 6076 } else if (ConstructedBase != DConstructedBase && 6077 !Shadow->isInvalidDecl()) { 6078 if (!DiagnosedMultipleConstructedBases) { 6079 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6080 << Shadow->getTargetDecl(); 6081 S.Diag(ConstructedBaseUsing->getLocation(), 6082 diag::note_ambiguous_inherited_constructor_using) 6083 << ConstructedBase; 6084 DiagnosedMultipleConstructedBases = true; 6085 } 6086 S.Diag(D->getUsingDecl()->getLocation(), 6087 diag::note_ambiguous_inherited_constructor_using) 6088 << DConstructedBase; 6089 } 6090 } 6091 6092 if (DiagnosedMultipleConstructedBases) 6093 Shadow->setInvalidDecl(); 6094 } 6095 6096 /// Find the constructor to use for inherited construction of a base class, 6097 /// and whether that base class constructor inherits the constructor from a 6098 /// virtual base class (in which case it won't actually invoke it). 6099 std::pair<CXXConstructorDecl *, bool> 6100 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6101 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6102 if (It == InheritedFromBases.end()) 6103 return std::make_pair(nullptr, false); 6104 6105 // This is an intermediary class. 6106 if (It->second) 6107 return std::make_pair( 6108 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6109 It->second->constructsVirtualBase()); 6110 6111 // This is the base class from which the constructor was inherited. 6112 return std::make_pair(Ctor, false); 6113 } 6114 }; 6115 6116 /// Is the special member function which would be selected to perform the 6117 /// specified operation on the specified class type a constexpr constructor? 6118 static bool 6119 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6120 Sema::CXXSpecialMember CSM, unsigned Quals, 6121 bool ConstRHS, 6122 CXXConstructorDecl *InheritedCtor = nullptr, 6123 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6124 // If we're inheriting a constructor, see if we need to call it for this base 6125 // class. 6126 if (InheritedCtor) { 6127 assert(CSM == Sema::CXXDefaultConstructor); 6128 auto BaseCtor = 6129 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6130 if (BaseCtor) 6131 return BaseCtor->isConstexpr(); 6132 } 6133 6134 if (CSM == Sema::CXXDefaultConstructor) 6135 return ClassDecl->hasConstexprDefaultConstructor(); 6136 6137 Sema::SpecialMemberOverloadResult SMOR = 6138 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6139 if (!SMOR.getMethod()) 6140 // A constructor we wouldn't select can't be "involved in initializing" 6141 // anything. 6142 return true; 6143 return SMOR.getMethod()->isConstexpr(); 6144 } 6145 6146 /// Determine whether the specified special member function would be constexpr 6147 /// if it were implicitly defined. 6148 static bool defaultedSpecialMemberIsConstexpr( 6149 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6150 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6151 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6152 if (!S.getLangOpts().CPlusPlus11) 6153 return false; 6154 6155 // C++11 [dcl.constexpr]p4: 6156 // In the definition of a constexpr constructor [...] 6157 bool Ctor = true; 6158 switch (CSM) { 6159 case Sema::CXXDefaultConstructor: 6160 if (Inherited) 6161 break; 6162 // Since default constructor lookup is essentially trivial (and cannot 6163 // involve, for instance, template instantiation), we compute whether a 6164 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6165 // 6166 // This is important for performance; we need to know whether the default 6167 // constructor is constexpr to determine whether the type is a literal type. 6168 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6169 6170 case Sema::CXXCopyConstructor: 6171 case Sema::CXXMoveConstructor: 6172 // For copy or move constructors, we need to perform overload resolution. 6173 break; 6174 6175 case Sema::CXXCopyAssignment: 6176 case Sema::CXXMoveAssignment: 6177 if (!S.getLangOpts().CPlusPlus14) 6178 return false; 6179 // In C++1y, we need to perform overload resolution. 6180 Ctor = false; 6181 break; 6182 6183 case Sema::CXXDestructor: 6184 case Sema::CXXInvalid: 6185 return false; 6186 } 6187 6188 // -- if the class is a non-empty union, or for each non-empty anonymous 6189 // union member of a non-union class, exactly one non-static data member 6190 // shall be initialized; [DR1359] 6191 // 6192 // If we squint, this is guaranteed, since exactly one non-static data member 6193 // will be initialized (if the constructor isn't deleted), we just don't know 6194 // which one. 6195 if (Ctor && ClassDecl->isUnion()) 6196 return CSM == Sema::CXXDefaultConstructor 6197 ? ClassDecl->hasInClassInitializer() || 6198 !ClassDecl->hasVariantMembers() 6199 : true; 6200 6201 // -- the class shall not have any virtual base classes; 6202 if (Ctor && ClassDecl->getNumVBases()) 6203 return false; 6204 6205 // C++1y [class.copy]p26: 6206 // -- [the class] is a literal type, and 6207 if (!Ctor && !ClassDecl->isLiteral()) 6208 return false; 6209 6210 // -- every constructor involved in initializing [...] base class 6211 // sub-objects shall be a constexpr constructor; 6212 // -- the assignment operator selected to copy/move each direct base 6213 // class is a constexpr function, and 6214 for (const auto &B : ClassDecl->bases()) { 6215 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6216 if (!BaseType) continue; 6217 6218 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6219 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6220 InheritedCtor, Inherited)) 6221 return false; 6222 } 6223 6224 // -- every constructor involved in initializing non-static data members 6225 // [...] shall be a constexpr constructor; 6226 // -- every non-static data member and base class sub-object shall be 6227 // initialized 6228 // -- for each non-static data member of X that is of class type (or array 6229 // thereof), the assignment operator selected to copy/move that member is 6230 // a constexpr function 6231 for (const auto *F : ClassDecl->fields()) { 6232 if (F->isInvalidDecl()) 6233 continue; 6234 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6235 continue; 6236 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6237 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6238 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6239 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6240 BaseType.getCVRQualifiers(), 6241 ConstArg && !F->isMutable())) 6242 return false; 6243 } else if (CSM == Sema::CXXDefaultConstructor) { 6244 return false; 6245 } 6246 } 6247 6248 // All OK, it's constexpr! 6249 return true; 6250 } 6251 6252 static Sema::ImplicitExceptionSpecification 6253 ComputeDefaultedSpecialMemberExceptionSpec( 6254 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6255 Sema::InheritedConstructorInfo *ICI); 6256 6257 static Sema::ImplicitExceptionSpecification 6258 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6259 auto CSM = S.getSpecialMember(MD); 6260 if (CSM != Sema::CXXInvalid) 6261 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6262 6263 auto *CD = cast<CXXConstructorDecl>(MD); 6264 assert(CD->getInheritedConstructor() && 6265 "only special members have implicit exception specs"); 6266 Sema::InheritedConstructorInfo ICI( 6267 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6268 return ComputeDefaultedSpecialMemberExceptionSpec( 6269 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6270 } 6271 6272 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6273 CXXMethodDecl *MD) { 6274 FunctionProtoType::ExtProtoInfo EPI; 6275 6276 // Build an exception specification pointing back at this member. 6277 EPI.ExceptionSpec.Type = EST_Unevaluated; 6278 EPI.ExceptionSpec.SourceDecl = MD; 6279 6280 // Set the calling convention to the default for C++ instance methods. 6281 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6282 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6283 /*IsCXXMethod=*/true)); 6284 return EPI; 6285 } 6286 6287 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6288 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6289 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6290 return; 6291 6292 // Evaluate the exception specification. 6293 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6294 auto ESI = IES.getExceptionSpec(); 6295 6296 // Update the type of the special member to use it. 6297 UpdateExceptionSpec(MD, ESI); 6298 6299 // A user-provided destructor can be defined outside the class. When that 6300 // happens, be sure to update the exception specification on both 6301 // declarations. 6302 const FunctionProtoType *CanonicalFPT = 6303 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6304 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6305 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6306 } 6307 6308 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6309 CXXRecordDecl *RD = MD->getParent(); 6310 CXXSpecialMember CSM = getSpecialMember(MD); 6311 6312 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6313 "not an explicitly-defaulted special member"); 6314 6315 // Whether this was the first-declared instance of the constructor. 6316 // This affects whether we implicitly add an exception spec and constexpr. 6317 bool First = MD == MD->getCanonicalDecl(); 6318 6319 bool HadError = false; 6320 6321 // C++11 [dcl.fct.def.default]p1: 6322 // A function that is explicitly defaulted shall 6323 // -- be a special member function (checked elsewhere), 6324 // -- have the same type (except for ref-qualifiers, and except that a 6325 // copy operation can take a non-const reference) as an implicit 6326 // declaration, and 6327 // -- not have default arguments. 6328 unsigned ExpectedParams = 1; 6329 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6330 ExpectedParams = 0; 6331 if (MD->getNumParams() != ExpectedParams) { 6332 // This also checks for default arguments: a copy or move constructor with a 6333 // default argument is classified as a default constructor, and assignment 6334 // operations and destructors can't have default arguments. 6335 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6336 << CSM << MD->getSourceRange(); 6337 HadError = true; 6338 } else if (MD->isVariadic()) { 6339 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6340 << CSM << MD->getSourceRange(); 6341 HadError = true; 6342 } 6343 6344 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6345 6346 bool CanHaveConstParam = false; 6347 if (CSM == CXXCopyConstructor) 6348 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6349 else if (CSM == CXXCopyAssignment) 6350 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6351 6352 QualType ReturnType = Context.VoidTy; 6353 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6354 // Check for return type matching. 6355 ReturnType = Type->getReturnType(); 6356 QualType ExpectedReturnType = 6357 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6358 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6359 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6360 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6361 HadError = true; 6362 } 6363 6364 // A defaulted special member cannot have cv-qualifiers. 6365 if (Type->getTypeQuals()) { 6366 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6367 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6368 HadError = true; 6369 } 6370 } 6371 6372 // Check for parameter type matching. 6373 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6374 bool HasConstParam = false; 6375 if (ExpectedParams && ArgType->isReferenceType()) { 6376 // Argument must be reference to possibly-const T. 6377 QualType ReferentType = ArgType->getPointeeType(); 6378 HasConstParam = ReferentType.isConstQualified(); 6379 6380 if (ReferentType.isVolatileQualified()) { 6381 Diag(MD->getLocation(), 6382 diag::err_defaulted_special_member_volatile_param) << CSM; 6383 HadError = true; 6384 } 6385 6386 if (HasConstParam && !CanHaveConstParam) { 6387 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6388 Diag(MD->getLocation(), 6389 diag::err_defaulted_special_member_copy_const_param) 6390 << (CSM == CXXCopyAssignment); 6391 // FIXME: Explain why this special member can't be const. 6392 } else { 6393 Diag(MD->getLocation(), 6394 diag::err_defaulted_special_member_move_const_param) 6395 << (CSM == CXXMoveAssignment); 6396 } 6397 HadError = true; 6398 } 6399 } else if (ExpectedParams) { 6400 // A copy assignment operator can take its argument by value, but a 6401 // defaulted one cannot. 6402 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6403 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6404 HadError = true; 6405 } 6406 6407 // C++11 [dcl.fct.def.default]p2: 6408 // An explicitly-defaulted function may be declared constexpr only if it 6409 // would have been implicitly declared as constexpr, 6410 // Do not apply this rule to members of class templates, since core issue 1358 6411 // makes such functions always instantiate to constexpr functions. For 6412 // functions which cannot be constexpr (for non-constructors in C++11 and for 6413 // destructors in C++1y), this is checked elsewhere. 6414 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6415 HasConstParam); 6416 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6417 : isa<CXXConstructorDecl>(MD)) && 6418 MD->isConstexpr() && !Constexpr && 6419 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6420 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6421 // FIXME: Explain why the special member can't be constexpr. 6422 HadError = true; 6423 } 6424 6425 // and may have an explicit exception-specification only if it is compatible 6426 // with the exception-specification on the implicit declaration. 6427 if (Type->hasExceptionSpec()) { 6428 // Delay the check if this is the first declaration of the special member, 6429 // since we may not have parsed some necessary in-class initializers yet. 6430 if (First) { 6431 // If the exception specification needs to be instantiated, do so now, 6432 // before we clobber it with an EST_Unevaluated specification below. 6433 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6434 InstantiateExceptionSpec(MD->getLocStart(), MD); 6435 Type = MD->getType()->getAs<FunctionProtoType>(); 6436 } 6437 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6438 } else 6439 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6440 } 6441 6442 // If a function is explicitly defaulted on its first declaration, 6443 if (First) { 6444 // -- it is implicitly considered to be constexpr if the implicit 6445 // definition would be, 6446 MD->setConstexpr(Constexpr); 6447 6448 // -- it is implicitly considered to have the same exception-specification 6449 // as if it had been implicitly declared, 6450 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6451 EPI.ExceptionSpec.Type = EST_Unevaluated; 6452 EPI.ExceptionSpec.SourceDecl = MD; 6453 MD->setType(Context.getFunctionType(ReturnType, 6454 llvm::makeArrayRef(&ArgType, 6455 ExpectedParams), 6456 EPI)); 6457 } 6458 6459 if (ShouldDeleteSpecialMember(MD, CSM)) { 6460 if (First) { 6461 SetDeclDeleted(MD, MD->getLocation()); 6462 } else { 6463 // C++11 [dcl.fct.def.default]p4: 6464 // [For a] user-provided explicitly-defaulted function [...] if such a 6465 // function is implicitly defined as deleted, the program is ill-formed. 6466 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6467 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6468 HadError = true; 6469 } 6470 } 6471 6472 if (HadError) 6473 MD->setInvalidDecl(); 6474 } 6475 6476 /// Check whether the exception specification provided for an 6477 /// explicitly-defaulted special member matches the exception specification 6478 /// that would have been generated for an implicit special member, per 6479 /// C++11 [dcl.fct.def.default]p2. 6480 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6481 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6482 // If the exception specification was explicitly specified but hadn't been 6483 // parsed when the method was defaulted, grab it now. 6484 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6485 SpecifiedType = 6486 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6487 6488 // Compute the implicit exception specification. 6489 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6490 /*IsCXXMethod=*/true); 6491 FunctionProtoType::ExtProtoInfo EPI(CC); 6492 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6493 EPI.ExceptionSpec = IES.getExceptionSpec(); 6494 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6495 Context.getFunctionType(Context.VoidTy, None, EPI)); 6496 6497 // Ensure that it matches. 6498 CheckEquivalentExceptionSpec( 6499 PDiag(diag::err_incorrect_defaulted_exception_spec) 6500 << getSpecialMember(MD), PDiag(), 6501 ImplicitType, SourceLocation(), 6502 SpecifiedType, MD->getLocation()); 6503 } 6504 6505 void Sema::CheckDelayedMemberExceptionSpecs() { 6506 decltype(DelayedExceptionSpecChecks) Checks; 6507 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6508 6509 std::swap(Checks, DelayedExceptionSpecChecks); 6510 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6511 6512 // Perform any deferred checking of exception specifications for virtual 6513 // destructors. 6514 for (auto &Check : Checks) 6515 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6516 6517 // Check that any explicitly-defaulted methods have exception specifications 6518 // compatible with their implicit exception specifications. 6519 for (auto &Spec : Specs) 6520 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6521 } 6522 6523 namespace { 6524 /// CRTP base class for visiting operations performed by a special member 6525 /// function (or inherited constructor). 6526 template<typename Derived> 6527 struct SpecialMemberVisitor { 6528 Sema &S; 6529 CXXMethodDecl *MD; 6530 Sema::CXXSpecialMember CSM; 6531 Sema::InheritedConstructorInfo *ICI; 6532 6533 // Properties of the special member, computed for convenience. 6534 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6535 6536 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6537 Sema::InheritedConstructorInfo *ICI) 6538 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6539 switch (CSM) { 6540 case Sema::CXXDefaultConstructor: 6541 case Sema::CXXCopyConstructor: 6542 case Sema::CXXMoveConstructor: 6543 IsConstructor = true; 6544 break; 6545 case Sema::CXXCopyAssignment: 6546 case Sema::CXXMoveAssignment: 6547 IsAssignment = true; 6548 break; 6549 case Sema::CXXDestructor: 6550 break; 6551 case Sema::CXXInvalid: 6552 llvm_unreachable("invalid special member kind"); 6553 } 6554 6555 if (MD->getNumParams()) { 6556 if (const ReferenceType *RT = 6557 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6558 ConstArg = RT->getPointeeType().isConstQualified(); 6559 } 6560 } 6561 6562 Derived &getDerived() { return static_cast<Derived&>(*this); } 6563 6564 /// Is this a "move" special member? 6565 bool isMove() const { 6566 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6567 } 6568 6569 /// Look up the corresponding special member in the given class. 6570 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6571 unsigned Quals, bool IsMutable) { 6572 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6573 ConstArg && !IsMutable); 6574 } 6575 6576 /// Look up the constructor for the specified base class to see if it's 6577 /// overridden due to this being an inherited constructor. 6578 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6579 if (!ICI) 6580 return {}; 6581 assert(CSM == Sema::CXXDefaultConstructor); 6582 auto *BaseCtor = 6583 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6584 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6585 return MD; 6586 return {}; 6587 } 6588 6589 /// A base or member subobject. 6590 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6591 6592 /// Get the location to use for a subobject in diagnostics. 6593 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6594 // FIXME: For an indirect virtual base, the direct base leading to 6595 // the indirect virtual base would be a more useful choice. 6596 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6597 return B->getBaseTypeLoc(); 6598 else 6599 return Subobj.get<FieldDecl*>()->getLocation(); 6600 } 6601 6602 enum BasesToVisit { 6603 /// Visit all non-virtual (direct) bases. 6604 VisitNonVirtualBases, 6605 /// Visit all direct bases, virtual or not. 6606 VisitDirectBases, 6607 /// Visit all non-virtual bases, and all virtual bases if the class 6608 /// is not abstract. 6609 VisitPotentiallyConstructedBases, 6610 /// Visit all direct or virtual bases. 6611 VisitAllBases 6612 }; 6613 6614 // Visit the bases and members of the class. 6615 bool visit(BasesToVisit Bases) { 6616 CXXRecordDecl *RD = MD->getParent(); 6617 6618 if (Bases == VisitPotentiallyConstructedBases) 6619 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6620 6621 for (auto &B : RD->bases()) 6622 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6623 getDerived().visitBase(&B)) 6624 return true; 6625 6626 if (Bases == VisitAllBases) 6627 for (auto &B : RD->vbases()) 6628 if (getDerived().visitBase(&B)) 6629 return true; 6630 6631 for (auto *F : RD->fields()) 6632 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6633 getDerived().visitField(F)) 6634 return true; 6635 6636 return false; 6637 } 6638 }; 6639 } 6640 6641 namespace { 6642 struct SpecialMemberDeletionInfo 6643 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6644 bool Diagnose; 6645 6646 SourceLocation Loc; 6647 6648 bool AllFieldsAreConst; 6649 6650 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6651 Sema::CXXSpecialMember CSM, 6652 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6653 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6654 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6655 6656 bool inUnion() const { return MD->getParent()->isUnion(); } 6657 6658 Sema::CXXSpecialMember getEffectiveCSM() { 6659 return ICI ? Sema::CXXInvalid : CSM; 6660 } 6661 6662 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6663 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6664 6665 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6666 bool shouldDeleteForField(FieldDecl *FD); 6667 bool shouldDeleteForAllConstMembers(); 6668 6669 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6670 unsigned Quals); 6671 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6672 Sema::SpecialMemberOverloadResult SMOR, 6673 bool IsDtorCallInCtor); 6674 6675 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6676 }; 6677 } 6678 6679 /// Is the given special member inaccessible when used on the given 6680 /// sub-object. 6681 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6682 CXXMethodDecl *target) { 6683 /// If we're operating on a base class, the object type is the 6684 /// type of this special member. 6685 QualType objectTy; 6686 AccessSpecifier access = target->getAccess(); 6687 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6688 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6689 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6690 6691 // If we're operating on a field, the object type is the type of the field. 6692 } else { 6693 objectTy = S.Context.getTypeDeclType(target->getParent()); 6694 } 6695 6696 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6697 } 6698 6699 /// Check whether we should delete a special member due to the implicit 6700 /// definition containing a call to a special member of a subobject. 6701 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6702 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6703 bool IsDtorCallInCtor) { 6704 CXXMethodDecl *Decl = SMOR.getMethod(); 6705 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6706 6707 int DiagKind = -1; 6708 6709 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6710 DiagKind = !Decl ? 0 : 1; 6711 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6712 DiagKind = 2; 6713 else if (!isAccessible(Subobj, Decl)) 6714 DiagKind = 3; 6715 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6716 !Decl->isTrivial()) { 6717 // A member of a union must have a trivial corresponding special member. 6718 // As a weird special case, a destructor call from a union's constructor 6719 // must be accessible and non-deleted, but need not be trivial. Such a 6720 // destructor is never actually called, but is semantically checked as 6721 // if it were. 6722 DiagKind = 4; 6723 } 6724 6725 if (DiagKind == -1) 6726 return false; 6727 6728 if (Diagnose) { 6729 if (Field) { 6730 S.Diag(Field->getLocation(), 6731 diag::note_deleted_special_member_class_subobject) 6732 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6733 << Field << DiagKind << IsDtorCallInCtor; 6734 } else { 6735 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6736 S.Diag(Base->getLocStart(), 6737 diag::note_deleted_special_member_class_subobject) 6738 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6739 << Base->getType() << DiagKind << IsDtorCallInCtor; 6740 } 6741 6742 if (DiagKind == 1) 6743 S.NoteDeletedFunction(Decl); 6744 // FIXME: Explain inaccessibility if DiagKind == 3. 6745 } 6746 6747 return true; 6748 } 6749 6750 /// Check whether we should delete a special member function due to having a 6751 /// direct or virtual base class or non-static data member of class type M. 6752 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6753 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6754 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6755 bool IsMutable = Field && Field->isMutable(); 6756 6757 // C++11 [class.ctor]p5: 6758 // -- any direct or virtual base class, or non-static data member with no 6759 // brace-or-equal-initializer, has class type M (or array thereof) and 6760 // either M has no default constructor or overload resolution as applied 6761 // to M's default constructor results in an ambiguity or in a function 6762 // that is deleted or inaccessible 6763 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6764 // -- a direct or virtual base class B that cannot be copied/moved because 6765 // overload resolution, as applied to B's corresponding special member, 6766 // results in an ambiguity or a function that is deleted or inaccessible 6767 // from the defaulted special member 6768 // C++11 [class.dtor]p5: 6769 // -- any direct or virtual base class [...] has a type with a destructor 6770 // that is deleted or inaccessible 6771 if (!(CSM == Sema::CXXDefaultConstructor && 6772 Field && Field->hasInClassInitializer()) && 6773 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6774 false)) 6775 return true; 6776 6777 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6778 // -- any direct or virtual base class or non-static data member has a 6779 // type with a destructor that is deleted or inaccessible 6780 if (IsConstructor) { 6781 Sema::SpecialMemberOverloadResult SMOR = 6782 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6783 false, false, false, false, false); 6784 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6785 return true; 6786 } 6787 6788 return false; 6789 } 6790 6791 /// Check whether we should delete a special member function due to the class 6792 /// having a particular direct or virtual base class. 6793 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6794 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6795 // If program is correct, BaseClass cannot be null, but if it is, the error 6796 // must be reported elsewhere. 6797 if (!BaseClass) 6798 return false; 6799 // If we have an inheriting constructor, check whether we're calling an 6800 // inherited constructor instead of a default constructor. 6801 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6802 if (auto *BaseCtor = SMOR.getMethod()) { 6803 // Note that we do not check access along this path; other than that, 6804 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6805 // FIXME: Check that the base has a usable destructor! Sink this into 6806 // shouldDeleteForClassSubobject. 6807 if (BaseCtor->isDeleted() && Diagnose) { 6808 S.Diag(Base->getLocStart(), 6809 diag::note_deleted_special_member_class_subobject) 6810 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6811 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6812 S.NoteDeletedFunction(BaseCtor); 6813 } 6814 return BaseCtor->isDeleted(); 6815 } 6816 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6817 } 6818 6819 /// Check whether we should delete a special member function due to the class 6820 /// having a particular non-static data member. 6821 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6822 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6823 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6824 6825 if (CSM == Sema::CXXDefaultConstructor) { 6826 // For a default constructor, all references must be initialized in-class 6827 // and, if a union, it must have a non-const member. 6828 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6829 if (Diagnose) 6830 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6831 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6832 return true; 6833 } 6834 // C++11 [class.ctor]p5: any non-variant non-static data member of 6835 // const-qualified type (or array thereof) with no 6836 // brace-or-equal-initializer does not have a user-provided default 6837 // constructor. 6838 if (!inUnion() && FieldType.isConstQualified() && 6839 !FD->hasInClassInitializer() && 6840 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6841 if (Diagnose) 6842 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6843 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6844 return true; 6845 } 6846 6847 if (inUnion() && !FieldType.isConstQualified()) 6848 AllFieldsAreConst = false; 6849 } else if (CSM == Sema::CXXCopyConstructor) { 6850 // For a copy constructor, data members must not be of rvalue reference 6851 // type. 6852 if (FieldType->isRValueReferenceType()) { 6853 if (Diagnose) 6854 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6855 << MD->getParent() << FD << FieldType; 6856 return true; 6857 } 6858 } else if (IsAssignment) { 6859 // For an assignment operator, data members must not be of reference type. 6860 if (FieldType->isReferenceType()) { 6861 if (Diagnose) 6862 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6863 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6864 return true; 6865 } 6866 if (!FieldRecord && FieldType.isConstQualified()) { 6867 // C++11 [class.copy]p23: 6868 // -- a non-static data member of const non-class type (or array thereof) 6869 if (Diagnose) 6870 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6871 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6872 return true; 6873 } 6874 } 6875 6876 if (FieldRecord) { 6877 // Some additional restrictions exist on the variant members. 6878 if (!inUnion() && FieldRecord->isUnion() && 6879 FieldRecord->isAnonymousStructOrUnion()) { 6880 bool AllVariantFieldsAreConst = true; 6881 6882 // FIXME: Handle anonymous unions declared within anonymous unions. 6883 for (auto *UI : FieldRecord->fields()) { 6884 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6885 6886 if (!UnionFieldType.isConstQualified()) 6887 AllVariantFieldsAreConst = false; 6888 6889 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6890 if (UnionFieldRecord && 6891 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6892 UnionFieldType.getCVRQualifiers())) 6893 return true; 6894 } 6895 6896 // At least one member in each anonymous union must be non-const 6897 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6898 !FieldRecord->field_empty()) { 6899 if (Diagnose) 6900 S.Diag(FieldRecord->getLocation(), 6901 diag::note_deleted_default_ctor_all_const) 6902 << !!ICI << MD->getParent() << /*anonymous union*/1; 6903 return true; 6904 } 6905 6906 // Don't check the implicit member of the anonymous union type. 6907 // This is technically non-conformant, but sanity demands it. 6908 return false; 6909 } 6910 6911 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6912 FieldType.getCVRQualifiers())) 6913 return true; 6914 } 6915 6916 return false; 6917 } 6918 6919 /// C++11 [class.ctor] p5: 6920 /// A defaulted default constructor for a class X is defined as deleted if 6921 /// X is a union and all of its variant members are of const-qualified type. 6922 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6923 // This is a silly definition, because it gives an empty union a deleted 6924 // default constructor. Don't do that. 6925 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6926 bool AnyFields = false; 6927 for (auto *F : MD->getParent()->fields()) 6928 if ((AnyFields = !F->isUnnamedBitfield())) 6929 break; 6930 if (!AnyFields) 6931 return false; 6932 if (Diagnose) 6933 S.Diag(MD->getParent()->getLocation(), 6934 diag::note_deleted_default_ctor_all_const) 6935 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6936 return true; 6937 } 6938 return false; 6939 } 6940 6941 /// Determine whether a defaulted special member function should be defined as 6942 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6943 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6944 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6945 InheritedConstructorInfo *ICI, 6946 bool Diagnose) { 6947 if (MD->isInvalidDecl()) 6948 return false; 6949 CXXRecordDecl *RD = MD->getParent(); 6950 assert(!RD->isDependentType() && "do deletion after instantiation"); 6951 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6952 return false; 6953 6954 // C++11 [expr.lambda.prim]p19: 6955 // The closure type associated with a lambda-expression has a 6956 // deleted (8.4.3) default constructor and a deleted copy 6957 // assignment operator. 6958 if (RD->isLambda() && 6959 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6960 if (Diagnose) 6961 Diag(RD->getLocation(), diag::note_lambda_decl); 6962 return true; 6963 } 6964 6965 // For an anonymous struct or union, the copy and assignment special members 6966 // will never be used, so skip the check. For an anonymous union declared at 6967 // namespace scope, the constructor and destructor are used. 6968 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6969 RD->isAnonymousStructOrUnion()) 6970 return false; 6971 6972 // C++11 [class.copy]p7, p18: 6973 // If the class definition declares a move constructor or move assignment 6974 // operator, an implicitly declared copy constructor or copy assignment 6975 // operator is defined as deleted. 6976 if (MD->isImplicit() && 6977 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6978 CXXMethodDecl *UserDeclaredMove = nullptr; 6979 6980 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6981 // deletion of the corresponding copy operation, not both copy operations. 6982 // MSVC 2015 has adopted the standards conforming behavior. 6983 bool DeletesOnlyMatchingCopy = 6984 getLangOpts().MSVCCompat && 6985 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6986 6987 if (RD->hasUserDeclaredMoveConstructor() && 6988 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6989 if (!Diagnose) return true; 6990 6991 // Find any user-declared move constructor. 6992 for (auto *I : RD->ctors()) { 6993 if (I->isMoveConstructor()) { 6994 UserDeclaredMove = I; 6995 break; 6996 } 6997 } 6998 assert(UserDeclaredMove); 6999 } else if (RD->hasUserDeclaredMoveAssignment() && 7000 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7001 if (!Diagnose) return true; 7002 7003 // Find any user-declared move assignment operator. 7004 for (auto *I : RD->methods()) { 7005 if (I->isMoveAssignmentOperator()) { 7006 UserDeclaredMove = I; 7007 break; 7008 } 7009 } 7010 assert(UserDeclaredMove); 7011 } 7012 7013 if (UserDeclaredMove) { 7014 Diag(UserDeclaredMove->getLocation(), 7015 diag::note_deleted_copy_user_declared_move) 7016 << (CSM == CXXCopyAssignment) << RD 7017 << UserDeclaredMove->isMoveAssignmentOperator(); 7018 return true; 7019 } 7020 } 7021 7022 // Do access control from the special member function 7023 ContextRAII MethodContext(*this, MD); 7024 7025 // C++11 [class.dtor]p5: 7026 // -- for a virtual destructor, lookup of the non-array deallocation function 7027 // results in an ambiguity or in a function that is deleted or inaccessible 7028 if (CSM == CXXDestructor && MD->isVirtual()) { 7029 FunctionDecl *OperatorDelete = nullptr; 7030 DeclarationName Name = 7031 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7032 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7033 OperatorDelete, /*Diagnose*/false)) { 7034 if (Diagnose) 7035 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7036 return true; 7037 } 7038 } 7039 7040 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7041 7042 // Per DR1611, do not consider virtual bases of constructors of abstract 7043 // classes, since we are not going to construct them. 7044 // Per DR1658, do not consider virtual bases of destructors of abstract 7045 // classes either. 7046 // Per DR2180, for assignment operators we only assign (and thus only 7047 // consider) direct bases. 7048 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7049 : SMI.VisitPotentiallyConstructedBases)) 7050 return true; 7051 7052 if (SMI.shouldDeleteForAllConstMembers()) 7053 return true; 7054 7055 if (getLangOpts().CUDA) { 7056 // We should delete the special member in CUDA mode if target inference 7057 // failed. 7058 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7059 Diagnose); 7060 } 7061 7062 return false; 7063 } 7064 7065 /// Perform lookup for a special member of the specified kind, and determine 7066 /// whether it is trivial. If the triviality can be determined without the 7067 /// lookup, skip it. This is intended for use when determining whether a 7068 /// special member of a containing object is trivial, and thus does not ever 7069 /// perform overload resolution for default constructors. 7070 /// 7071 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7072 /// member that was most likely to be intended to be trivial, if any. 7073 /// 7074 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7075 /// determine whether the special member is trivial. 7076 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7077 Sema::CXXSpecialMember CSM, unsigned Quals, 7078 bool ConstRHS, 7079 Sema::TrivialABIHandling TAH, 7080 CXXMethodDecl **Selected) { 7081 if (Selected) 7082 *Selected = nullptr; 7083 7084 switch (CSM) { 7085 case Sema::CXXInvalid: 7086 llvm_unreachable("not a special member"); 7087 7088 case Sema::CXXDefaultConstructor: 7089 // C++11 [class.ctor]p5: 7090 // A default constructor is trivial if: 7091 // - all the [direct subobjects] have trivial default constructors 7092 // 7093 // Note, no overload resolution is performed in this case. 7094 if (RD->hasTrivialDefaultConstructor()) 7095 return true; 7096 7097 if (Selected) { 7098 // If there's a default constructor which could have been trivial, dig it 7099 // out. Otherwise, if there's any user-provided default constructor, point 7100 // to that as an example of why there's not a trivial one. 7101 CXXConstructorDecl *DefCtor = nullptr; 7102 if (RD->needsImplicitDefaultConstructor()) 7103 S.DeclareImplicitDefaultConstructor(RD); 7104 for (auto *CI : RD->ctors()) { 7105 if (!CI->isDefaultConstructor()) 7106 continue; 7107 DefCtor = CI; 7108 if (!DefCtor->isUserProvided()) 7109 break; 7110 } 7111 7112 *Selected = DefCtor; 7113 } 7114 7115 return false; 7116 7117 case Sema::CXXDestructor: 7118 // C++11 [class.dtor]p5: 7119 // A destructor is trivial if: 7120 // - all the direct [subobjects] have trivial destructors 7121 if (RD->hasTrivialDestructor() || 7122 (TAH == Sema::TAH_ConsiderTrivialABI && 7123 RD->hasTrivialDestructorForCall())) 7124 return true; 7125 7126 if (Selected) { 7127 if (RD->needsImplicitDestructor()) 7128 S.DeclareImplicitDestructor(RD); 7129 *Selected = RD->getDestructor(); 7130 } 7131 7132 return false; 7133 7134 case Sema::CXXCopyConstructor: 7135 // C++11 [class.copy]p12: 7136 // A copy constructor is trivial if: 7137 // - the constructor selected to copy each direct [subobject] is trivial 7138 if (RD->hasTrivialCopyConstructor() || 7139 (TAH == Sema::TAH_ConsiderTrivialABI && 7140 RD->hasTrivialCopyConstructorForCall())) { 7141 if (Quals == Qualifiers::Const) 7142 // We must either select the trivial copy constructor or reach an 7143 // ambiguity; no need to actually perform overload resolution. 7144 return true; 7145 } else if (!Selected) { 7146 return false; 7147 } 7148 // In C++98, we are not supposed to perform overload resolution here, but we 7149 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7150 // cases like B as having a non-trivial copy constructor: 7151 // struct A { template<typename T> A(T&); }; 7152 // struct B { mutable A a; }; 7153 goto NeedOverloadResolution; 7154 7155 case Sema::CXXCopyAssignment: 7156 // C++11 [class.copy]p25: 7157 // A copy assignment operator is trivial if: 7158 // - the assignment operator selected to copy each direct [subobject] is 7159 // trivial 7160 if (RD->hasTrivialCopyAssignment()) { 7161 if (Quals == Qualifiers::Const) 7162 return true; 7163 } else if (!Selected) { 7164 return false; 7165 } 7166 // In C++98, we are not supposed to perform overload resolution here, but we 7167 // treat that as a language defect. 7168 goto NeedOverloadResolution; 7169 7170 case Sema::CXXMoveConstructor: 7171 case Sema::CXXMoveAssignment: 7172 NeedOverloadResolution: 7173 Sema::SpecialMemberOverloadResult SMOR = 7174 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7175 7176 // The standard doesn't describe how to behave if the lookup is ambiguous. 7177 // We treat it as not making the member non-trivial, just like the standard 7178 // mandates for the default constructor. This should rarely matter, because 7179 // the member will also be deleted. 7180 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7181 return true; 7182 7183 if (!SMOR.getMethod()) { 7184 assert(SMOR.getKind() == 7185 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7186 return false; 7187 } 7188 7189 // We deliberately don't check if we found a deleted special member. We're 7190 // not supposed to! 7191 if (Selected) 7192 *Selected = SMOR.getMethod(); 7193 7194 if (TAH == Sema::TAH_ConsiderTrivialABI && 7195 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7196 return SMOR.getMethod()->isTrivialForCall(); 7197 return SMOR.getMethod()->isTrivial(); 7198 } 7199 7200 llvm_unreachable("unknown special method kind"); 7201 } 7202 7203 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7204 for (auto *CI : RD->ctors()) 7205 if (!CI->isImplicit()) 7206 return CI; 7207 7208 // Look for constructor templates. 7209 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7210 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7211 if (CXXConstructorDecl *CD = 7212 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7213 return CD; 7214 } 7215 7216 return nullptr; 7217 } 7218 7219 /// The kind of subobject we are checking for triviality. The values of this 7220 /// enumeration are used in diagnostics. 7221 enum TrivialSubobjectKind { 7222 /// The subobject is a base class. 7223 TSK_BaseClass, 7224 /// The subobject is a non-static data member. 7225 TSK_Field, 7226 /// The object is actually the complete object. 7227 TSK_CompleteObject 7228 }; 7229 7230 /// Check whether the special member selected for a given type would be trivial. 7231 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7232 QualType SubType, bool ConstRHS, 7233 Sema::CXXSpecialMember CSM, 7234 TrivialSubobjectKind Kind, 7235 Sema::TrivialABIHandling TAH, bool Diagnose) { 7236 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7237 if (!SubRD) 7238 return true; 7239 7240 CXXMethodDecl *Selected; 7241 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7242 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7243 return true; 7244 7245 if (Diagnose) { 7246 if (ConstRHS) 7247 SubType.addConst(); 7248 7249 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7250 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7251 << Kind << SubType.getUnqualifiedType(); 7252 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7253 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7254 } else if (!Selected) 7255 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7256 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7257 else if (Selected->isUserProvided()) { 7258 if (Kind == TSK_CompleteObject) 7259 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7260 << Kind << SubType.getUnqualifiedType() << CSM; 7261 else { 7262 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7263 << Kind << SubType.getUnqualifiedType() << CSM; 7264 S.Diag(Selected->getLocation(), diag::note_declared_at); 7265 } 7266 } else { 7267 if (Kind != TSK_CompleteObject) 7268 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7269 << Kind << SubType.getUnqualifiedType() << CSM; 7270 7271 // Explain why the defaulted or deleted special member isn't trivial. 7272 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7273 Diagnose); 7274 } 7275 } 7276 7277 return false; 7278 } 7279 7280 /// Check whether the members of a class type allow a special member to be 7281 /// trivial. 7282 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7283 Sema::CXXSpecialMember CSM, 7284 bool ConstArg, 7285 Sema::TrivialABIHandling TAH, 7286 bool Diagnose) { 7287 for (const auto *FI : RD->fields()) { 7288 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7289 continue; 7290 7291 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7292 7293 // Pretend anonymous struct or union members are members of this class. 7294 if (FI->isAnonymousStructOrUnion()) { 7295 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7296 CSM, ConstArg, TAH, Diagnose)) 7297 return false; 7298 continue; 7299 } 7300 7301 // C++11 [class.ctor]p5: 7302 // A default constructor is trivial if [...] 7303 // -- no non-static data member of its class has a 7304 // brace-or-equal-initializer 7305 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7306 if (Diagnose) 7307 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7308 return false; 7309 } 7310 7311 // Objective C ARC 4.3.5: 7312 // [...] nontrivally ownership-qualified types are [...] not trivially 7313 // default constructible, copy constructible, move constructible, copy 7314 // assignable, move assignable, or destructible [...] 7315 if (FieldType.hasNonTrivialObjCLifetime()) { 7316 if (Diagnose) 7317 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7318 << RD << FieldType.getObjCLifetime(); 7319 return false; 7320 } 7321 7322 bool ConstRHS = ConstArg && !FI->isMutable(); 7323 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7324 CSM, TSK_Field, TAH, Diagnose)) 7325 return false; 7326 } 7327 7328 return true; 7329 } 7330 7331 /// Diagnose why the specified class does not have a trivial special member of 7332 /// the given kind. 7333 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7334 QualType Ty = Context.getRecordType(RD); 7335 7336 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7337 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7338 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7339 /*Diagnose*/true); 7340 } 7341 7342 /// Determine whether a defaulted or deleted special member function is trivial, 7343 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7344 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7345 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7346 TrivialABIHandling TAH, bool Diagnose) { 7347 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7348 7349 CXXRecordDecl *RD = MD->getParent(); 7350 7351 bool ConstArg = false; 7352 7353 // C++11 [class.copy]p12, p25: [DR1593] 7354 // A [special member] is trivial if [...] its parameter-type-list is 7355 // equivalent to the parameter-type-list of an implicit declaration [...] 7356 switch (CSM) { 7357 case CXXDefaultConstructor: 7358 case CXXDestructor: 7359 // Trivial default constructors and destructors cannot have parameters. 7360 break; 7361 7362 case CXXCopyConstructor: 7363 case CXXCopyAssignment: { 7364 // Trivial copy operations always have const, non-volatile parameter types. 7365 ConstArg = true; 7366 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7367 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7368 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7369 if (Diagnose) 7370 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7371 << Param0->getSourceRange() << Param0->getType() 7372 << Context.getLValueReferenceType( 7373 Context.getRecordType(RD).withConst()); 7374 return false; 7375 } 7376 break; 7377 } 7378 7379 case CXXMoveConstructor: 7380 case CXXMoveAssignment: { 7381 // Trivial move operations always have non-cv-qualified parameters. 7382 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7383 const RValueReferenceType *RT = 7384 Param0->getType()->getAs<RValueReferenceType>(); 7385 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7386 if (Diagnose) 7387 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7388 << Param0->getSourceRange() << Param0->getType() 7389 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7390 return false; 7391 } 7392 break; 7393 } 7394 7395 case CXXInvalid: 7396 llvm_unreachable("not a special member"); 7397 } 7398 7399 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7400 if (Diagnose) 7401 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7402 diag::note_nontrivial_default_arg) 7403 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7404 return false; 7405 } 7406 if (MD->isVariadic()) { 7407 if (Diagnose) 7408 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7409 return false; 7410 } 7411 7412 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7413 // A copy/move [constructor or assignment operator] is trivial if 7414 // -- the [member] selected to copy/move each direct base class subobject 7415 // is trivial 7416 // 7417 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7418 // A [default constructor or destructor] is trivial if 7419 // -- all the direct base classes have trivial [default constructors or 7420 // destructors] 7421 for (const auto &BI : RD->bases()) 7422 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7423 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7424 return false; 7425 7426 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7427 // A copy/move [constructor or assignment operator] for a class X is 7428 // trivial if 7429 // -- for each non-static data member of X that is of class type (or array 7430 // thereof), the constructor selected to copy/move that member is 7431 // trivial 7432 // 7433 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7434 // A [default constructor or destructor] is trivial if 7435 // -- for all of the non-static data members of its class that are of class 7436 // type (or array thereof), each such class has a trivial [default 7437 // constructor or destructor] 7438 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7439 return false; 7440 7441 // C++11 [class.dtor]p5: 7442 // A destructor is trivial if [...] 7443 // -- the destructor is not virtual 7444 if (CSM == CXXDestructor && MD->isVirtual()) { 7445 if (Diagnose) 7446 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7447 return false; 7448 } 7449 7450 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7451 // A [special member] for class X is trivial if [...] 7452 // -- class X has no virtual functions and no virtual base classes 7453 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7454 if (!Diagnose) 7455 return false; 7456 7457 if (RD->getNumVBases()) { 7458 // Check for virtual bases. We already know that the corresponding 7459 // member in all bases is trivial, so vbases must all be direct. 7460 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7461 assert(BS.isVirtual()); 7462 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7463 return false; 7464 } 7465 7466 // Must have a virtual method. 7467 for (const auto *MI : RD->methods()) { 7468 if (MI->isVirtual()) { 7469 SourceLocation MLoc = MI->getLocStart(); 7470 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7471 return false; 7472 } 7473 } 7474 7475 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7476 } 7477 7478 // Looks like it's trivial! 7479 return true; 7480 } 7481 7482 namespace { 7483 struct FindHiddenVirtualMethod { 7484 Sema *S; 7485 CXXMethodDecl *Method; 7486 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7487 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7488 7489 private: 7490 /// Check whether any most overriden method from MD in Methods 7491 static bool CheckMostOverridenMethods( 7492 const CXXMethodDecl *MD, 7493 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7494 if (MD->size_overridden_methods() == 0) 7495 return Methods.count(MD->getCanonicalDecl()); 7496 for (const CXXMethodDecl *O : MD->overridden_methods()) 7497 if (CheckMostOverridenMethods(O, Methods)) 7498 return true; 7499 return false; 7500 } 7501 7502 public: 7503 /// Member lookup function that determines whether a given C++ 7504 /// method overloads virtual methods in a base class without overriding any, 7505 /// to be used with CXXRecordDecl::lookupInBases(). 7506 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7507 RecordDecl *BaseRecord = 7508 Specifier->getType()->getAs<RecordType>()->getDecl(); 7509 7510 DeclarationName Name = Method->getDeclName(); 7511 assert(Name.getNameKind() == DeclarationName::Identifier); 7512 7513 bool foundSameNameMethod = false; 7514 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7515 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7516 Path.Decls = Path.Decls.slice(1)) { 7517 NamedDecl *D = Path.Decls.front(); 7518 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7519 MD = MD->getCanonicalDecl(); 7520 foundSameNameMethod = true; 7521 // Interested only in hidden virtual methods. 7522 if (!MD->isVirtual()) 7523 continue; 7524 // If the method we are checking overrides a method from its base 7525 // don't warn about the other overloaded methods. Clang deviates from 7526 // GCC by only diagnosing overloads of inherited virtual functions that 7527 // do not override any other virtual functions in the base. GCC's 7528 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7529 // function from a base class. These cases may be better served by a 7530 // warning (not specific to virtual functions) on call sites when the 7531 // call would select a different function from the base class, were it 7532 // visible. 7533 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7534 if (!S->IsOverload(Method, MD, false)) 7535 return true; 7536 // Collect the overload only if its hidden. 7537 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7538 overloadedMethods.push_back(MD); 7539 } 7540 } 7541 7542 if (foundSameNameMethod) 7543 OverloadedMethods.append(overloadedMethods.begin(), 7544 overloadedMethods.end()); 7545 return foundSameNameMethod; 7546 } 7547 }; 7548 } // end anonymous namespace 7549 7550 /// \brief Add the most overriden methods from MD to Methods 7551 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7552 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7553 if (MD->size_overridden_methods() == 0) 7554 Methods.insert(MD->getCanonicalDecl()); 7555 else 7556 for (const CXXMethodDecl *O : MD->overridden_methods()) 7557 AddMostOverridenMethods(O, Methods); 7558 } 7559 7560 /// \brief Check if a method overloads virtual methods in a base class without 7561 /// overriding any. 7562 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7563 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7564 if (!MD->getDeclName().isIdentifier()) 7565 return; 7566 7567 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7568 /*bool RecordPaths=*/false, 7569 /*bool DetectVirtual=*/false); 7570 FindHiddenVirtualMethod FHVM; 7571 FHVM.Method = MD; 7572 FHVM.S = this; 7573 7574 // Keep the base methods that were overriden or introduced in the subclass 7575 // by 'using' in a set. A base method not in this set is hidden. 7576 CXXRecordDecl *DC = MD->getParent(); 7577 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7578 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7579 NamedDecl *ND = *I; 7580 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7581 ND = shad->getTargetDecl(); 7582 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7583 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7584 } 7585 7586 if (DC->lookupInBases(FHVM, Paths)) 7587 OverloadedMethods = FHVM.OverloadedMethods; 7588 } 7589 7590 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7591 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7592 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7593 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7594 PartialDiagnostic PD = PDiag( 7595 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7596 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7597 Diag(overloadedMD->getLocation(), PD); 7598 } 7599 } 7600 7601 /// \brief Diagnose methods which overload virtual methods in a base class 7602 /// without overriding any. 7603 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7604 if (MD->isInvalidDecl()) 7605 return; 7606 7607 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7608 return; 7609 7610 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7611 FindHiddenVirtualMethods(MD, OverloadedMethods); 7612 if (!OverloadedMethods.empty()) { 7613 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7614 << MD << (OverloadedMethods.size() > 1); 7615 7616 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7617 } 7618 } 7619 7620 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7621 auto PrintDiagAndRemoveAttr = [&]() { 7622 // No diagnostics if this is a template instantiation. 7623 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7624 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7625 diag::ext_cannot_use_trivial_abi) << &RD; 7626 RD.dropAttr<TrivialABIAttr>(); 7627 }; 7628 7629 // Ill-formed if the struct has virtual functions. 7630 if (RD.isPolymorphic()) { 7631 PrintDiagAndRemoveAttr(); 7632 return; 7633 } 7634 7635 for (const auto &B : RD.bases()) { 7636 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7637 // virtual base. 7638 if ((!B.getType()->isDependentType() && 7639 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7640 B.isVirtual()) { 7641 PrintDiagAndRemoveAttr(); 7642 return; 7643 } 7644 } 7645 7646 for (const auto *FD : RD.fields()) { 7647 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7648 // non-trivial for the purpose of calls. 7649 QualType FT = FD->getType(); 7650 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7651 PrintDiagAndRemoveAttr(); 7652 return; 7653 } 7654 7655 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7656 if (!RT->isDependentType() && 7657 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7658 PrintDiagAndRemoveAttr(); 7659 return; 7660 } 7661 } 7662 } 7663 7664 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7665 Decl *TagDecl, 7666 SourceLocation LBrac, 7667 SourceLocation RBrac, 7668 AttributeList *AttrList) { 7669 if (!TagDecl) 7670 return; 7671 7672 AdjustDeclIfTemplate(TagDecl); 7673 7674 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7675 if (l->getKind() != AttributeList::AT_Visibility) 7676 continue; 7677 l->setInvalid(); 7678 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7679 l->getName(); 7680 } 7681 7682 // See if trivial_abi has to be dropped. 7683 auto *RD = dyn_cast<CXXRecordDecl>(TagDecl); 7684 if (RD && RD->hasAttr<TrivialABIAttr>()) 7685 checkIllFormedTrivialABIStruct(*RD); 7686 7687 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7688 // strict aliasing violation! 7689 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7690 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7691 7692 CheckCompletedCXXClass(RD); 7693 } 7694 7695 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7696 /// special functions, such as the default constructor, copy 7697 /// constructor, or destructor, to the given C++ class (C++ 7698 /// [special]p1). This routine can only be executed just before the 7699 /// definition of the class is complete. 7700 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7701 if (ClassDecl->needsImplicitDefaultConstructor()) { 7702 ++ASTContext::NumImplicitDefaultConstructors; 7703 7704 if (ClassDecl->hasInheritedConstructor()) 7705 DeclareImplicitDefaultConstructor(ClassDecl); 7706 } 7707 7708 if (ClassDecl->needsImplicitCopyConstructor()) { 7709 ++ASTContext::NumImplicitCopyConstructors; 7710 7711 // If the properties or semantics of the copy constructor couldn't be 7712 // determined while the class was being declared, force a declaration 7713 // of it now. 7714 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7715 ClassDecl->hasInheritedConstructor()) 7716 DeclareImplicitCopyConstructor(ClassDecl); 7717 // For the MS ABI we need to know whether the copy ctor is deleted. A 7718 // prerequisite for deleting the implicit copy ctor is that the class has a 7719 // move ctor or move assignment that is either user-declared or whose 7720 // semantics are inherited from a subobject. FIXME: We should provide a more 7721 // direct way for CodeGen to ask whether the constructor was deleted. 7722 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7723 (ClassDecl->hasUserDeclaredMoveConstructor() || 7724 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7725 ClassDecl->hasUserDeclaredMoveAssignment() || 7726 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7727 DeclareImplicitCopyConstructor(ClassDecl); 7728 } 7729 7730 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7731 ++ASTContext::NumImplicitMoveConstructors; 7732 7733 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7734 ClassDecl->hasInheritedConstructor()) 7735 DeclareImplicitMoveConstructor(ClassDecl); 7736 } 7737 7738 if (ClassDecl->needsImplicitCopyAssignment()) { 7739 ++ASTContext::NumImplicitCopyAssignmentOperators; 7740 7741 // If we have a dynamic class, then the copy assignment operator may be 7742 // virtual, so we have to declare it immediately. This ensures that, e.g., 7743 // it shows up in the right place in the vtable and that we diagnose 7744 // problems with the implicit exception specification. 7745 if (ClassDecl->isDynamicClass() || 7746 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7747 ClassDecl->hasInheritedAssignment()) 7748 DeclareImplicitCopyAssignment(ClassDecl); 7749 } 7750 7751 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7752 ++ASTContext::NumImplicitMoveAssignmentOperators; 7753 7754 // Likewise for the move assignment operator. 7755 if (ClassDecl->isDynamicClass() || 7756 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7757 ClassDecl->hasInheritedAssignment()) 7758 DeclareImplicitMoveAssignment(ClassDecl); 7759 } 7760 7761 if (ClassDecl->needsImplicitDestructor()) { 7762 ++ASTContext::NumImplicitDestructors; 7763 7764 // If we have a dynamic class, then the destructor may be virtual, so we 7765 // have to declare the destructor immediately. This ensures that, e.g., it 7766 // shows up in the right place in the vtable and that we diagnose problems 7767 // with the implicit exception specification. 7768 if (ClassDecl->isDynamicClass() || 7769 ClassDecl->needsOverloadResolutionForDestructor()) 7770 DeclareImplicitDestructor(ClassDecl); 7771 } 7772 } 7773 7774 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7775 if (!D) 7776 return 0; 7777 7778 // The order of template parameters is not important here. All names 7779 // get added to the same scope. 7780 SmallVector<TemplateParameterList *, 4> ParameterLists; 7781 7782 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7783 D = TD->getTemplatedDecl(); 7784 7785 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7786 ParameterLists.push_back(PSD->getTemplateParameters()); 7787 7788 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7789 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7790 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7791 7792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7793 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7794 ParameterLists.push_back(FTD->getTemplateParameters()); 7795 } 7796 } 7797 7798 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7799 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7800 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7801 7802 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7803 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7804 ParameterLists.push_back(CTD->getTemplateParameters()); 7805 } 7806 } 7807 7808 unsigned Count = 0; 7809 for (TemplateParameterList *Params : ParameterLists) { 7810 if (Params->size() > 0) 7811 // Ignore explicit specializations; they don't contribute to the template 7812 // depth. 7813 ++Count; 7814 for (NamedDecl *Param : *Params) { 7815 if (Param->getDeclName()) { 7816 S->AddDecl(Param); 7817 IdResolver.AddDecl(Param); 7818 } 7819 } 7820 } 7821 7822 return Count; 7823 } 7824 7825 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7826 if (!RecordD) return; 7827 AdjustDeclIfTemplate(RecordD); 7828 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7829 PushDeclContext(S, Record); 7830 } 7831 7832 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7833 if (!RecordD) return; 7834 PopDeclContext(); 7835 } 7836 7837 /// This is used to implement the constant expression evaluation part of the 7838 /// attribute enable_if extension. There is nothing in standard C++ which would 7839 /// require reentering parameters. 7840 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7841 if (!Param) 7842 return; 7843 7844 S->AddDecl(Param); 7845 if (Param->getDeclName()) 7846 IdResolver.AddDecl(Param); 7847 } 7848 7849 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7850 /// parsing a top-level (non-nested) C++ class, and we are now 7851 /// parsing those parts of the given Method declaration that could 7852 /// not be parsed earlier (C++ [class.mem]p2), such as default 7853 /// arguments. This action should enter the scope of the given 7854 /// Method declaration as if we had just parsed the qualified method 7855 /// name. However, it should not bring the parameters into scope; 7856 /// that will be performed by ActOnDelayedCXXMethodParameter. 7857 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7858 } 7859 7860 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7861 /// C++ method declaration. We're (re-)introducing the given 7862 /// function parameter into scope for use in parsing later parts of 7863 /// the method declaration. For example, we could see an 7864 /// ActOnParamDefaultArgument event for this parameter. 7865 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7866 if (!ParamD) 7867 return; 7868 7869 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7870 7871 // If this parameter has an unparsed default argument, clear it out 7872 // to make way for the parsed default argument. 7873 if (Param->hasUnparsedDefaultArg()) 7874 Param->setDefaultArg(nullptr); 7875 7876 S->AddDecl(Param); 7877 if (Param->getDeclName()) 7878 IdResolver.AddDecl(Param); 7879 } 7880 7881 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7882 /// processing the delayed method declaration for Method. The method 7883 /// declaration is now considered finished. There may be a separate 7884 /// ActOnStartOfFunctionDef action later (not necessarily 7885 /// immediately!) for this method, if it was also defined inside the 7886 /// class body. 7887 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7888 if (!MethodD) 7889 return; 7890 7891 AdjustDeclIfTemplate(MethodD); 7892 7893 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7894 7895 // Now that we have our default arguments, check the constructor 7896 // again. It could produce additional diagnostics or affect whether 7897 // the class has implicitly-declared destructors, among other 7898 // things. 7899 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7900 CheckConstructor(Constructor); 7901 7902 // Check the default arguments, which we may have added. 7903 if (!Method->isInvalidDecl()) 7904 CheckCXXDefaultArguments(Method); 7905 } 7906 7907 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7908 /// the well-formedness of the constructor declarator @p D with type @p 7909 /// R. If there are any errors in the declarator, this routine will 7910 /// emit diagnostics and set the invalid bit to true. In any case, the type 7911 /// will be updated to reflect a well-formed type for the constructor and 7912 /// returned. 7913 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7914 StorageClass &SC) { 7915 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7916 7917 // C++ [class.ctor]p3: 7918 // A constructor shall not be virtual (10.3) or static (9.4). A 7919 // constructor can be invoked for a const, volatile or const 7920 // volatile object. A constructor shall not be declared const, 7921 // volatile, or const volatile (9.3.2). 7922 if (isVirtual) { 7923 if (!D.isInvalidType()) 7924 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7925 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7926 << SourceRange(D.getIdentifierLoc()); 7927 D.setInvalidType(); 7928 } 7929 if (SC == SC_Static) { 7930 if (!D.isInvalidType()) 7931 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7932 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7933 << SourceRange(D.getIdentifierLoc()); 7934 D.setInvalidType(); 7935 SC = SC_None; 7936 } 7937 7938 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7939 diagnoseIgnoredQualifiers( 7940 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7941 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7942 D.getDeclSpec().getRestrictSpecLoc(), 7943 D.getDeclSpec().getAtomicSpecLoc()); 7944 D.setInvalidType(); 7945 } 7946 7947 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7948 if (FTI.TypeQuals != 0) { 7949 if (FTI.TypeQuals & Qualifiers::Const) 7950 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7951 << "const" << SourceRange(D.getIdentifierLoc()); 7952 if (FTI.TypeQuals & Qualifiers::Volatile) 7953 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7954 << "volatile" << SourceRange(D.getIdentifierLoc()); 7955 if (FTI.TypeQuals & Qualifiers::Restrict) 7956 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7957 << "restrict" << SourceRange(D.getIdentifierLoc()); 7958 D.setInvalidType(); 7959 } 7960 7961 // C++0x [class.ctor]p4: 7962 // A constructor shall not be declared with a ref-qualifier. 7963 if (FTI.hasRefQualifier()) { 7964 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7965 << FTI.RefQualifierIsLValueRef 7966 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7967 D.setInvalidType(); 7968 } 7969 7970 // Rebuild the function type "R" without any type qualifiers (in 7971 // case any of the errors above fired) and with "void" as the 7972 // return type, since constructors don't have return types. 7973 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7974 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7975 return R; 7976 7977 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7978 EPI.TypeQuals = 0; 7979 EPI.RefQualifier = RQ_None; 7980 7981 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7982 } 7983 7984 /// CheckConstructor - Checks a fully-formed constructor for 7985 /// well-formedness, issuing any diagnostics required. Returns true if 7986 /// the constructor declarator is invalid. 7987 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7988 CXXRecordDecl *ClassDecl 7989 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7990 if (!ClassDecl) 7991 return Constructor->setInvalidDecl(); 7992 7993 // C++ [class.copy]p3: 7994 // A declaration of a constructor for a class X is ill-formed if 7995 // its first parameter is of type (optionally cv-qualified) X and 7996 // either there are no other parameters or else all other 7997 // parameters have default arguments. 7998 if (!Constructor->isInvalidDecl() && 7999 ((Constructor->getNumParams() == 1) || 8000 (Constructor->getNumParams() > 1 && 8001 Constructor->getParamDecl(1)->hasDefaultArg())) && 8002 Constructor->getTemplateSpecializationKind() 8003 != TSK_ImplicitInstantiation) { 8004 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8005 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8006 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8007 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8008 const char *ConstRef 8009 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8010 : " const &"; 8011 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8012 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8013 8014 // FIXME: Rather that making the constructor invalid, we should endeavor 8015 // to fix the type. 8016 Constructor->setInvalidDecl(); 8017 } 8018 } 8019 } 8020 8021 /// CheckDestructor - Checks a fully-formed destructor definition for 8022 /// well-formedness, issuing any diagnostics required. Returns true 8023 /// on error. 8024 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8025 CXXRecordDecl *RD = Destructor->getParent(); 8026 8027 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8028 SourceLocation Loc; 8029 8030 if (!Destructor->isImplicit()) 8031 Loc = Destructor->getLocation(); 8032 else 8033 Loc = RD->getLocation(); 8034 8035 // If we have a virtual destructor, look up the deallocation function 8036 if (FunctionDecl *OperatorDelete = 8037 FindDeallocationFunctionForDestructor(Loc, RD)) { 8038 Expr *ThisArg = nullptr; 8039 8040 // If the notional 'delete this' expression requires a non-trivial 8041 // conversion from 'this' to the type of a destroying operator delete's 8042 // first parameter, perform that conversion now. 8043 if (OperatorDelete->isDestroyingOperatorDelete()) { 8044 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8045 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8046 // C++ [class.dtor]p13: 8047 // ... as if for the expression 'delete this' appearing in a 8048 // non-virtual destructor of the destructor's class. 8049 ContextRAII SwitchContext(*this, Destructor); 8050 ExprResult This = 8051 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8052 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8053 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8054 if (This.isInvalid()) { 8055 // FIXME: Register this as a context note so that it comes out 8056 // in the right order. 8057 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8058 return true; 8059 } 8060 ThisArg = This.get(); 8061 } 8062 } 8063 8064 MarkFunctionReferenced(Loc, OperatorDelete); 8065 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8066 } 8067 } 8068 8069 return false; 8070 } 8071 8072 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8073 /// the well-formednes of the destructor declarator @p D with type @p 8074 /// R. If there are any errors in the declarator, this routine will 8075 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8076 /// will be updated to reflect a well-formed type for the destructor and 8077 /// returned. 8078 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8079 StorageClass& SC) { 8080 // C++ [class.dtor]p1: 8081 // [...] A typedef-name that names a class is a class-name 8082 // (7.1.3); however, a typedef-name that names a class shall not 8083 // be used as the identifier in the declarator for a destructor 8084 // declaration. 8085 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8086 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8087 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8088 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8089 else if (const TemplateSpecializationType *TST = 8090 DeclaratorType->getAs<TemplateSpecializationType>()) 8091 if (TST->isTypeAlias()) 8092 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8093 << DeclaratorType << 1; 8094 8095 // C++ [class.dtor]p2: 8096 // A destructor is used to destroy objects of its class type. A 8097 // destructor takes no parameters, and no return type can be 8098 // specified for it (not even void). The address of a destructor 8099 // shall not be taken. A destructor shall not be static. A 8100 // destructor can be invoked for a const, volatile or const 8101 // volatile object. A destructor shall not be declared const, 8102 // volatile or const volatile (9.3.2). 8103 if (SC == SC_Static) { 8104 if (!D.isInvalidType()) 8105 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8106 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8107 << SourceRange(D.getIdentifierLoc()) 8108 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8109 8110 SC = SC_None; 8111 } 8112 if (!D.isInvalidType()) { 8113 // Destructors don't have return types, but the parser will 8114 // happily parse something like: 8115 // 8116 // class X { 8117 // float ~X(); 8118 // }; 8119 // 8120 // The return type will be eliminated later. 8121 if (D.getDeclSpec().hasTypeSpecifier()) 8122 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8123 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8124 << SourceRange(D.getIdentifierLoc()); 8125 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8126 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8127 SourceLocation(), 8128 D.getDeclSpec().getConstSpecLoc(), 8129 D.getDeclSpec().getVolatileSpecLoc(), 8130 D.getDeclSpec().getRestrictSpecLoc(), 8131 D.getDeclSpec().getAtomicSpecLoc()); 8132 D.setInvalidType(); 8133 } 8134 } 8135 8136 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8137 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8138 if (FTI.TypeQuals & Qualifiers::Const) 8139 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8140 << "const" << SourceRange(D.getIdentifierLoc()); 8141 if (FTI.TypeQuals & Qualifiers::Volatile) 8142 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8143 << "volatile" << SourceRange(D.getIdentifierLoc()); 8144 if (FTI.TypeQuals & Qualifiers::Restrict) 8145 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8146 << "restrict" << SourceRange(D.getIdentifierLoc()); 8147 D.setInvalidType(); 8148 } 8149 8150 // C++0x [class.dtor]p2: 8151 // A destructor shall not be declared with a ref-qualifier. 8152 if (FTI.hasRefQualifier()) { 8153 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8154 << FTI.RefQualifierIsLValueRef 8155 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8156 D.setInvalidType(); 8157 } 8158 8159 // Make sure we don't have any parameters. 8160 if (FTIHasNonVoidParameters(FTI)) { 8161 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8162 8163 // Delete the parameters. 8164 FTI.freeParams(); 8165 D.setInvalidType(); 8166 } 8167 8168 // Make sure the destructor isn't variadic. 8169 if (FTI.isVariadic) { 8170 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8171 D.setInvalidType(); 8172 } 8173 8174 // Rebuild the function type "R" without any type qualifiers or 8175 // parameters (in case any of the errors above fired) and with 8176 // "void" as the return type, since destructors don't have return 8177 // types. 8178 if (!D.isInvalidType()) 8179 return R; 8180 8181 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8182 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8183 EPI.Variadic = false; 8184 EPI.TypeQuals = 0; 8185 EPI.RefQualifier = RQ_None; 8186 return Context.getFunctionType(Context.VoidTy, None, EPI); 8187 } 8188 8189 static void extendLeft(SourceRange &R, SourceRange Before) { 8190 if (Before.isInvalid()) 8191 return; 8192 R.setBegin(Before.getBegin()); 8193 if (R.getEnd().isInvalid()) 8194 R.setEnd(Before.getEnd()); 8195 } 8196 8197 static void extendRight(SourceRange &R, SourceRange After) { 8198 if (After.isInvalid()) 8199 return; 8200 if (R.getBegin().isInvalid()) 8201 R.setBegin(After.getBegin()); 8202 R.setEnd(After.getEnd()); 8203 } 8204 8205 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8206 /// well-formednes of the conversion function declarator @p D with 8207 /// type @p R. If there are any errors in the declarator, this routine 8208 /// will emit diagnostics and return true. Otherwise, it will return 8209 /// false. Either way, the type @p R will be updated to reflect a 8210 /// well-formed type for the conversion operator. 8211 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8212 StorageClass& SC) { 8213 // C++ [class.conv.fct]p1: 8214 // Neither parameter types nor return type can be specified. The 8215 // type of a conversion function (8.3.5) is "function taking no 8216 // parameter returning conversion-type-id." 8217 if (SC == SC_Static) { 8218 if (!D.isInvalidType()) 8219 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8220 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8221 << D.getName().getSourceRange(); 8222 D.setInvalidType(); 8223 SC = SC_None; 8224 } 8225 8226 TypeSourceInfo *ConvTSI = nullptr; 8227 QualType ConvType = 8228 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8229 8230 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8231 // Conversion functions don't have return types, but the parser will 8232 // happily parse something like: 8233 // 8234 // class X { 8235 // float operator bool(); 8236 // }; 8237 // 8238 // The return type will be changed later anyway. 8239 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8240 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8241 << SourceRange(D.getIdentifierLoc()); 8242 D.setInvalidType(); 8243 } 8244 8245 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8246 8247 // Make sure we don't have any parameters. 8248 if (Proto->getNumParams() > 0) { 8249 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8250 8251 // Delete the parameters. 8252 D.getFunctionTypeInfo().freeParams(); 8253 D.setInvalidType(); 8254 } else if (Proto->isVariadic()) { 8255 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8256 D.setInvalidType(); 8257 } 8258 8259 // Diagnose "&operator bool()" and other such nonsense. This 8260 // is actually a gcc extension which we don't support. 8261 if (Proto->getReturnType() != ConvType) { 8262 bool NeedsTypedef = false; 8263 SourceRange Before, After; 8264 8265 // Walk the chunks and extract information on them for our diagnostic. 8266 bool PastFunctionChunk = false; 8267 for (auto &Chunk : D.type_objects()) { 8268 switch (Chunk.Kind) { 8269 case DeclaratorChunk::Function: 8270 if (!PastFunctionChunk) { 8271 if (Chunk.Fun.HasTrailingReturnType) { 8272 TypeSourceInfo *TRT = nullptr; 8273 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8274 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8275 } 8276 PastFunctionChunk = true; 8277 break; 8278 } 8279 LLVM_FALLTHROUGH; 8280 case DeclaratorChunk::Array: 8281 NeedsTypedef = true; 8282 extendRight(After, Chunk.getSourceRange()); 8283 break; 8284 8285 case DeclaratorChunk::Pointer: 8286 case DeclaratorChunk::BlockPointer: 8287 case DeclaratorChunk::Reference: 8288 case DeclaratorChunk::MemberPointer: 8289 case DeclaratorChunk::Pipe: 8290 extendLeft(Before, Chunk.getSourceRange()); 8291 break; 8292 8293 case DeclaratorChunk::Paren: 8294 extendLeft(Before, Chunk.Loc); 8295 extendRight(After, Chunk.EndLoc); 8296 break; 8297 } 8298 } 8299 8300 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8301 After.isValid() ? After.getBegin() : 8302 D.getIdentifierLoc(); 8303 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8304 DB << Before << After; 8305 8306 if (!NeedsTypedef) { 8307 DB << /*don't need a typedef*/0; 8308 8309 // If we can provide a correct fix-it hint, do so. 8310 if (After.isInvalid() && ConvTSI) { 8311 SourceLocation InsertLoc = 8312 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8313 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8314 << FixItHint::CreateInsertionFromRange( 8315 InsertLoc, CharSourceRange::getTokenRange(Before)) 8316 << FixItHint::CreateRemoval(Before); 8317 } 8318 } else if (!Proto->getReturnType()->isDependentType()) { 8319 DB << /*typedef*/1 << Proto->getReturnType(); 8320 } else if (getLangOpts().CPlusPlus11) { 8321 DB << /*alias template*/2 << Proto->getReturnType(); 8322 } else { 8323 DB << /*might not be fixable*/3; 8324 } 8325 8326 // Recover by incorporating the other type chunks into the result type. 8327 // Note, this does *not* change the name of the function. This is compatible 8328 // with the GCC extension: 8329 // struct S { &operator int(); } s; 8330 // int &r = s.operator int(); // ok in GCC 8331 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8332 ConvType = Proto->getReturnType(); 8333 } 8334 8335 // C++ [class.conv.fct]p4: 8336 // The conversion-type-id shall not represent a function type nor 8337 // an array type. 8338 if (ConvType->isArrayType()) { 8339 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8340 ConvType = Context.getPointerType(ConvType); 8341 D.setInvalidType(); 8342 } else if (ConvType->isFunctionType()) { 8343 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8344 ConvType = Context.getPointerType(ConvType); 8345 D.setInvalidType(); 8346 } 8347 8348 // Rebuild the function type "R" without any parameters (in case any 8349 // of the errors above fired) and with the conversion type as the 8350 // return type. 8351 if (D.isInvalidType()) 8352 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8353 8354 // C++0x explicit conversion operators. 8355 if (D.getDeclSpec().isExplicitSpecified()) 8356 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8357 getLangOpts().CPlusPlus11 ? 8358 diag::warn_cxx98_compat_explicit_conversion_functions : 8359 diag::ext_explicit_conversion_functions) 8360 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8361 } 8362 8363 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8364 /// the declaration of the given C++ conversion function. This routine 8365 /// is responsible for recording the conversion function in the C++ 8366 /// class, if possible. 8367 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8368 assert(Conversion && "Expected to receive a conversion function declaration"); 8369 8370 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8371 8372 // Make sure we aren't redeclaring the conversion function. 8373 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8374 8375 // C++ [class.conv.fct]p1: 8376 // [...] A conversion function is never used to convert a 8377 // (possibly cv-qualified) object to the (possibly cv-qualified) 8378 // same object type (or a reference to it), to a (possibly 8379 // cv-qualified) base class of that type (or a reference to it), 8380 // or to (possibly cv-qualified) void. 8381 // FIXME: Suppress this warning if the conversion function ends up being a 8382 // virtual function that overrides a virtual function in a base class. 8383 QualType ClassType 8384 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8385 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8386 ConvType = ConvTypeRef->getPointeeType(); 8387 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8388 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8389 /* Suppress diagnostics for instantiations. */; 8390 else if (ConvType->isRecordType()) { 8391 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8392 if (ConvType == ClassType) 8393 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8394 << ClassType; 8395 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8396 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8397 << ClassType << ConvType; 8398 } else if (ConvType->isVoidType()) { 8399 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8400 << ClassType << ConvType; 8401 } 8402 8403 if (FunctionTemplateDecl *ConversionTemplate 8404 = Conversion->getDescribedFunctionTemplate()) 8405 return ConversionTemplate; 8406 8407 return Conversion; 8408 } 8409 8410 namespace { 8411 /// Utility class to accumulate and print a diagnostic listing the invalid 8412 /// specifier(s) on a declaration. 8413 struct BadSpecifierDiagnoser { 8414 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8415 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8416 ~BadSpecifierDiagnoser() { 8417 Diagnostic << Specifiers; 8418 } 8419 8420 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8421 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8422 } 8423 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8424 return check(SpecLoc, 8425 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8426 } 8427 void check(SourceLocation SpecLoc, const char *Spec) { 8428 if (SpecLoc.isInvalid()) return; 8429 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8430 if (!Specifiers.empty()) Specifiers += " "; 8431 Specifiers += Spec; 8432 } 8433 8434 Sema &S; 8435 Sema::SemaDiagnosticBuilder Diagnostic; 8436 std::string Specifiers; 8437 }; 8438 } 8439 8440 /// Check the validity of a declarator that we parsed for a deduction-guide. 8441 /// These aren't actually declarators in the grammar, so we need to check that 8442 /// the user didn't specify any pieces that are not part of the deduction-guide 8443 /// grammar. 8444 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8445 StorageClass &SC) { 8446 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8447 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8448 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8449 8450 // C++ [temp.deduct.guide]p3: 8451 // A deduction-gide shall be declared in the same scope as the 8452 // corresponding class template. 8453 if (!CurContext->getRedeclContext()->Equals( 8454 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8455 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8456 << GuidedTemplateDecl; 8457 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8458 } 8459 8460 auto &DS = D.getMutableDeclSpec(); 8461 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8462 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8463 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8464 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8465 BadSpecifierDiagnoser Diagnoser( 8466 *this, D.getIdentifierLoc(), 8467 diag::err_deduction_guide_invalid_specifier); 8468 8469 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8470 DS.ClearStorageClassSpecs(); 8471 SC = SC_None; 8472 8473 // 'explicit' is permitted. 8474 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8475 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8476 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8477 DS.ClearConstexprSpec(); 8478 8479 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8480 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8481 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8482 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8483 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8484 DS.ClearTypeQualifiers(); 8485 8486 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8487 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8488 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8489 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8490 DS.ClearTypeSpecType(); 8491 } 8492 8493 if (D.isInvalidType()) 8494 return; 8495 8496 // Check the declarator is simple enough. 8497 bool FoundFunction = false; 8498 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8499 if (Chunk.Kind == DeclaratorChunk::Paren) 8500 continue; 8501 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8502 Diag(D.getDeclSpec().getLocStart(), 8503 diag::err_deduction_guide_with_complex_decl) 8504 << D.getSourceRange(); 8505 break; 8506 } 8507 if (!Chunk.Fun.hasTrailingReturnType()) { 8508 Diag(D.getName().getLocStart(), 8509 diag::err_deduction_guide_no_trailing_return_type); 8510 break; 8511 } 8512 8513 // Check that the return type is written as a specialization of 8514 // the template specified as the deduction-guide's name. 8515 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8516 TypeSourceInfo *TSI = nullptr; 8517 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8518 assert(TSI && "deduction guide has valid type but invalid return type?"); 8519 bool AcceptableReturnType = false; 8520 bool MightInstantiateToSpecialization = false; 8521 if (auto RetTST = 8522 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8523 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8524 bool TemplateMatches = 8525 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8526 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8527 AcceptableReturnType = true; 8528 else { 8529 // This could still instantiate to the right type, unless we know it 8530 // names the wrong class template. 8531 auto *TD = SpecifiedName.getAsTemplateDecl(); 8532 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8533 !TemplateMatches); 8534 } 8535 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8536 MightInstantiateToSpecialization = true; 8537 } 8538 8539 if (!AcceptableReturnType) { 8540 Diag(TSI->getTypeLoc().getLocStart(), 8541 diag::err_deduction_guide_bad_trailing_return_type) 8542 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8543 << TSI->getTypeLoc().getSourceRange(); 8544 } 8545 8546 // Keep going to check that we don't have any inner declarator pieces (we 8547 // could still have a function returning a pointer to a function). 8548 FoundFunction = true; 8549 } 8550 8551 if (D.isFunctionDefinition()) 8552 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8553 } 8554 8555 //===----------------------------------------------------------------------===// 8556 // Namespace Handling 8557 //===----------------------------------------------------------------------===// 8558 8559 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8560 /// reopened. 8561 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8562 SourceLocation Loc, 8563 IdentifierInfo *II, bool *IsInline, 8564 NamespaceDecl *PrevNS) { 8565 assert(*IsInline != PrevNS->isInline()); 8566 8567 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8568 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8569 // inline namespaces, with the intention of bringing names into namespace std. 8570 // 8571 // We support this just well enough to get that case working; this is not 8572 // sufficient to support reopening namespaces as inline in general. 8573 if (*IsInline && II && II->getName().startswith("__atomic") && 8574 S.getSourceManager().isInSystemHeader(Loc)) { 8575 // Mark all prior declarations of the namespace as inline. 8576 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8577 NS = NS->getPreviousDecl()) 8578 NS->setInline(*IsInline); 8579 // Patch up the lookup table for the containing namespace. This isn't really 8580 // correct, but it's good enough for this particular case. 8581 for (auto *I : PrevNS->decls()) 8582 if (auto *ND = dyn_cast<NamedDecl>(I)) 8583 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8584 return; 8585 } 8586 8587 if (PrevNS->isInline()) 8588 // The user probably just forgot the 'inline', so suggest that it 8589 // be added back. 8590 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8591 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8592 else 8593 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8594 8595 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8596 *IsInline = PrevNS->isInline(); 8597 } 8598 8599 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8600 /// definition. 8601 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8602 SourceLocation InlineLoc, 8603 SourceLocation NamespaceLoc, 8604 SourceLocation IdentLoc, 8605 IdentifierInfo *II, 8606 SourceLocation LBrace, 8607 AttributeList *AttrList, 8608 UsingDirectiveDecl *&UD) { 8609 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8610 // For anonymous namespace, take the location of the left brace. 8611 SourceLocation Loc = II ? IdentLoc : LBrace; 8612 bool IsInline = InlineLoc.isValid(); 8613 bool IsInvalid = false; 8614 bool IsStd = false; 8615 bool AddToKnown = false; 8616 Scope *DeclRegionScope = NamespcScope->getParent(); 8617 8618 NamespaceDecl *PrevNS = nullptr; 8619 if (II) { 8620 // C++ [namespace.def]p2: 8621 // The identifier in an original-namespace-definition shall not 8622 // have been previously defined in the declarative region in 8623 // which the original-namespace-definition appears. The 8624 // identifier in an original-namespace-definition is the name of 8625 // the namespace. Subsequently in that declarative region, it is 8626 // treated as an original-namespace-name. 8627 // 8628 // Since namespace names are unique in their scope, and we don't 8629 // look through using directives, just look for any ordinary names 8630 // as if by qualified name lookup. 8631 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8632 ForExternalRedeclaration); 8633 LookupQualifiedName(R, CurContext->getRedeclContext()); 8634 NamedDecl *PrevDecl = 8635 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8636 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8637 8638 if (PrevNS) { 8639 // This is an extended namespace definition. 8640 if (IsInline != PrevNS->isInline()) 8641 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8642 &IsInline, PrevNS); 8643 } else if (PrevDecl) { 8644 // This is an invalid name redefinition. 8645 Diag(Loc, diag::err_redefinition_different_kind) 8646 << II; 8647 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8648 IsInvalid = true; 8649 // Continue on to push Namespc as current DeclContext and return it. 8650 } else if (II->isStr("std") && 8651 CurContext->getRedeclContext()->isTranslationUnit()) { 8652 // This is the first "real" definition of the namespace "std", so update 8653 // our cache of the "std" namespace to point at this definition. 8654 PrevNS = getStdNamespace(); 8655 IsStd = true; 8656 AddToKnown = !IsInline; 8657 } else { 8658 // We've seen this namespace for the first time. 8659 AddToKnown = !IsInline; 8660 } 8661 } else { 8662 // Anonymous namespaces. 8663 8664 // Determine whether the parent already has an anonymous namespace. 8665 DeclContext *Parent = CurContext->getRedeclContext(); 8666 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8667 PrevNS = TU->getAnonymousNamespace(); 8668 } else { 8669 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8670 PrevNS = ND->getAnonymousNamespace(); 8671 } 8672 8673 if (PrevNS && IsInline != PrevNS->isInline()) 8674 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8675 &IsInline, PrevNS); 8676 } 8677 8678 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8679 StartLoc, Loc, II, PrevNS); 8680 if (IsInvalid) 8681 Namespc->setInvalidDecl(); 8682 8683 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8684 AddPragmaAttributes(DeclRegionScope, Namespc); 8685 8686 // FIXME: Should we be merging attributes? 8687 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8688 PushNamespaceVisibilityAttr(Attr, Loc); 8689 8690 if (IsStd) 8691 StdNamespace = Namespc; 8692 if (AddToKnown) 8693 KnownNamespaces[Namespc] = false; 8694 8695 if (II) { 8696 PushOnScopeChains(Namespc, DeclRegionScope); 8697 } else { 8698 // Link the anonymous namespace into its parent. 8699 DeclContext *Parent = CurContext->getRedeclContext(); 8700 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8701 TU->setAnonymousNamespace(Namespc); 8702 } else { 8703 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8704 } 8705 8706 CurContext->addDecl(Namespc); 8707 8708 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8709 // behaves as if it were replaced by 8710 // namespace unique { /* empty body */ } 8711 // using namespace unique; 8712 // namespace unique { namespace-body } 8713 // where all occurrences of 'unique' in a translation unit are 8714 // replaced by the same identifier and this identifier differs 8715 // from all other identifiers in the entire program. 8716 8717 // We just create the namespace with an empty name and then add an 8718 // implicit using declaration, just like the standard suggests. 8719 // 8720 // CodeGen enforces the "universally unique" aspect by giving all 8721 // declarations semantically contained within an anonymous 8722 // namespace internal linkage. 8723 8724 if (!PrevNS) { 8725 UD = UsingDirectiveDecl::Create(Context, Parent, 8726 /* 'using' */ LBrace, 8727 /* 'namespace' */ SourceLocation(), 8728 /* qualifier */ NestedNameSpecifierLoc(), 8729 /* identifier */ SourceLocation(), 8730 Namespc, 8731 /* Ancestor */ Parent); 8732 UD->setImplicit(); 8733 Parent->addDecl(UD); 8734 } 8735 } 8736 8737 ActOnDocumentableDecl(Namespc); 8738 8739 // Although we could have an invalid decl (i.e. the namespace name is a 8740 // redefinition), push it as current DeclContext and try to continue parsing. 8741 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8742 // for the namespace has the declarations that showed up in that particular 8743 // namespace definition. 8744 PushDeclContext(NamespcScope, Namespc); 8745 return Namespc; 8746 } 8747 8748 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8749 /// is a namespace alias, returns the namespace it points to. 8750 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8751 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8752 return AD->getNamespace(); 8753 return dyn_cast_or_null<NamespaceDecl>(D); 8754 } 8755 8756 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8757 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8758 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8759 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8760 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8761 Namespc->setRBraceLoc(RBrace); 8762 PopDeclContext(); 8763 if (Namespc->hasAttr<VisibilityAttr>()) 8764 PopPragmaVisibility(true, RBrace); 8765 } 8766 8767 CXXRecordDecl *Sema::getStdBadAlloc() const { 8768 return cast_or_null<CXXRecordDecl>( 8769 StdBadAlloc.get(Context.getExternalSource())); 8770 } 8771 8772 EnumDecl *Sema::getStdAlignValT() const { 8773 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8774 } 8775 8776 NamespaceDecl *Sema::getStdNamespace() const { 8777 return cast_or_null<NamespaceDecl>( 8778 StdNamespace.get(Context.getExternalSource())); 8779 } 8780 8781 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8782 if (!StdExperimentalNamespaceCache) { 8783 if (auto Std = getStdNamespace()) { 8784 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8785 SourceLocation(), LookupNamespaceName); 8786 if (!LookupQualifiedName(Result, Std) || 8787 !(StdExperimentalNamespaceCache = 8788 Result.getAsSingle<NamespaceDecl>())) 8789 Result.suppressDiagnostics(); 8790 } 8791 } 8792 return StdExperimentalNamespaceCache; 8793 } 8794 8795 /// \brief Retrieve the special "std" namespace, which may require us to 8796 /// implicitly define the namespace. 8797 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8798 if (!StdNamespace) { 8799 // The "std" namespace has not yet been defined, so build one implicitly. 8800 StdNamespace = NamespaceDecl::Create(Context, 8801 Context.getTranslationUnitDecl(), 8802 /*Inline=*/false, 8803 SourceLocation(), SourceLocation(), 8804 &PP.getIdentifierTable().get("std"), 8805 /*PrevDecl=*/nullptr); 8806 getStdNamespace()->setImplicit(true); 8807 } 8808 8809 return getStdNamespace(); 8810 } 8811 8812 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8813 assert(getLangOpts().CPlusPlus && 8814 "Looking for std::initializer_list outside of C++."); 8815 8816 // We're looking for implicit instantiations of 8817 // template <typename E> class std::initializer_list. 8818 8819 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8820 return false; 8821 8822 ClassTemplateDecl *Template = nullptr; 8823 const TemplateArgument *Arguments = nullptr; 8824 8825 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8826 8827 ClassTemplateSpecializationDecl *Specialization = 8828 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8829 if (!Specialization) 8830 return false; 8831 8832 Template = Specialization->getSpecializedTemplate(); 8833 Arguments = Specialization->getTemplateArgs().data(); 8834 } else if (const TemplateSpecializationType *TST = 8835 Ty->getAs<TemplateSpecializationType>()) { 8836 Template = dyn_cast_or_null<ClassTemplateDecl>( 8837 TST->getTemplateName().getAsTemplateDecl()); 8838 Arguments = TST->getArgs(); 8839 } 8840 if (!Template) 8841 return false; 8842 8843 if (!StdInitializerList) { 8844 // Haven't recognized std::initializer_list yet, maybe this is it. 8845 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8846 if (TemplateClass->getIdentifier() != 8847 &PP.getIdentifierTable().get("initializer_list") || 8848 !getStdNamespace()->InEnclosingNamespaceSetOf( 8849 TemplateClass->getDeclContext())) 8850 return false; 8851 // This is a template called std::initializer_list, but is it the right 8852 // template? 8853 TemplateParameterList *Params = Template->getTemplateParameters(); 8854 if (Params->getMinRequiredArguments() != 1) 8855 return false; 8856 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8857 return false; 8858 8859 // It's the right template. 8860 StdInitializerList = Template; 8861 } 8862 8863 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8864 return false; 8865 8866 // This is an instance of std::initializer_list. Find the argument type. 8867 if (Element) 8868 *Element = Arguments[0].getAsType(); 8869 return true; 8870 } 8871 8872 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8873 NamespaceDecl *Std = S.getStdNamespace(); 8874 if (!Std) { 8875 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8876 return nullptr; 8877 } 8878 8879 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8880 Loc, Sema::LookupOrdinaryName); 8881 if (!S.LookupQualifiedName(Result, Std)) { 8882 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8883 return nullptr; 8884 } 8885 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8886 if (!Template) { 8887 Result.suppressDiagnostics(); 8888 // We found something weird. Complain about the first thing we found. 8889 NamedDecl *Found = *Result.begin(); 8890 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8891 return nullptr; 8892 } 8893 8894 // We found some template called std::initializer_list. Now verify that it's 8895 // correct. 8896 TemplateParameterList *Params = Template->getTemplateParameters(); 8897 if (Params->getMinRequiredArguments() != 1 || 8898 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8899 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8900 return nullptr; 8901 } 8902 8903 return Template; 8904 } 8905 8906 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8907 if (!StdInitializerList) { 8908 StdInitializerList = LookupStdInitializerList(*this, Loc); 8909 if (!StdInitializerList) 8910 return QualType(); 8911 } 8912 8913 TemplateArgumentListInfo Args(Loc, Loc); 8914 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8915 Context.getTrivialTypeSourceInfo(Element, 8916 Loc))); 8917 return Context.getCanonicalType( 8918 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8919 } 8920 8921 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8922 // C++ [dcl.init.list]p2: 8923 // A constructor is an initializer-list constructor if its first parameter 8924 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8925 // std::initializer_list<E> for some type E, and either there are no other 8926 // parameters or else all other parameters have default arguments. 8927 if (Ctor->getNumParams() < 1 || 8928 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8929 return false; 8930 8931 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8932 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8933 ArgType = RT->getPointeeType().getUnqualifiedType(); 8934 8935 return isStdInitializerList(ArgType, nullptr); 8936 } 8937 8938 /// \brief Determine whether a using statement is in a context where it will be 8939 /// apply in all contexts. 8940 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8941 switch (CurContext->getDeclKind()) { 8942 case Decl::TranslationUnit: 8943 return true; 8944 case Decl::LinkageSpec: 8945 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8946 default: 8947 return false; 8948 } 8949 } 8950 8951 namespace { 8952 8953 // Callback to only accept typo corrections that are namespaces. 8954 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8955 public: 8956 bool ValidateCandidate(const TypoCorrection &candidate) override { 8957 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8958 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8959 return false; 8960 } 8961 }; 8962 8963 } 8964 8965 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8966 CXXScopeSpec &SS, 8967 SourceLocation IdentLoc, 8968 IdentifierInfo *Ident) { 8969 R.clear(); 8970 if (TypoCorrection Corrected = 8971 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8972 llvm::make_unique<NamespaceValidatorCCC>(), 8973 Sema::CTK_ErrorRecovery)) { 8974 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8975 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8976 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8977 Ident->getName().equals(CorrectedStr); 8978 S.diagnoseTypo(Corrected, 8979 S.PDiag(diag::err_using_directive_member_suggest) 8980 << Ident << DC << DroppedSpecifier << SS.getRange(), 8981 S.PDiag(diag::note_namespace_defined_here)); 8982 } else { 8983 S.diagnoseTypo(Corrected, 8984 S.PDiag(diag::err_using_directive_suggest) << Ident, 8985 S.PDiag(diag::note_namespace_defined_here)); 8986 } 8987 R.addDecl(Corrected.getFoundDecl()); 8988 return true; 8989 } 8990 return false; 8991 } 8992 8993 Decl *Sema::ActOnUsingDirective(Scope *S, 8994 SourceLocation UsingLoc, 8995 SourceLocation NamespcLoc, 8996 CXXScopeSpec &SS, 8997 SourceLocation IdentLoc, 8998 IdentifierInfo *NamespcName, 8999 AttributeList *AttrList) { 9000 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9001 assert(NamespcName && "Invalid NamespcName."); 9002 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9003 9004 // This can only happen along a recovery path. 9005 while (S->isTemplateParamScope()) 9006 S = S->getParent(); 9007 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9008 9009 UsingDirectiveDecl *UDir = nullptr; 9010 NestedNameSpecifier *Qualifier = nullptr; 9011 if (SS.isSet()) 9012 Qualifier = SS.getScopeRep(); 9013 9014 // Lookup namespace name. 9015 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9016 LookupParsedName(R, S, &SS); 9017 if (R.isAmbiguous()) 9018 return nullptr; 9019 9020 if (R.empty()) { 9021 R.clear(); 9022 // Allow "using namespace std;" or "using namespace ::std;" even if 9023 // "std" hasn't been defined yet, for GCC compatibility. 9024 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9025 NamespcName->isStr("std")) { 9026 Diag(IdentLoc, diag::ext_using_undefined_std); 9027 R.addDecl(getOrCreateStdNamespace()); 9028 R.resolveKind(); 9029 } 9030 // Otherwise, attempt typo correction. 9031 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9032 } 9033 9034 if (!R.empty()) { 9035 NamedDecl *Named = R.getRepresentativeDecl(); 9036 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9037 assert(NS && "expected namespace decl"); 9038 9039 // The use of a nested name specifier may trigger deprecation warnings. 9040 DiagnoseUseOfDecl(Named, IdentLoc); 9041 9042 // C++ [namespace.udir]p1: 9043 // A using-directive specifies that the names in the nominated 9044 // namespace can be used in the scope in which the 9045 // using-directive appears after the using-directive. During 9046 // unqualified name lookup (3.4.1), the names appear as if they 9047 // were declared in the nearest enclosing namespace which 9048 // contains both the using-directive and the nominated 9049 // namespace. [Note: in this context, "contains" means "contains 9050 // directly or indirectly". ] 9051 9052 // Find enclosing context containing both using-directive and 9053 // nominated namespace. 9054 DeclContext *CommonAncestor = NS; 9055 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9056 CommonAncestor = CommonAncestor->getParent(); 9057 9058 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9059 SS.getWithLocInContext(Context), 9060 IdentLoc, Named, CommonAncestor); 9061 9062 if (IsUsingDirectiveInToplevelContext(CurContext) && 9063 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9064 Diag(IdentLoc, diag::warn_using_directive_in_header); 9065 } 9066 9067 PushUsingDirective(S, UDir); 9068 } else { 9069 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9070 } 9071 9072 if (UDir) 9073 ProcessDeclAttributeList(S, UDir, AttrList); 9074 9075 return UDir; 9076 } 9077 9078 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9079 // If the scope has an associated entity and the using directive is at 9080 // namespace or translation unit scope, add the UsingDirectiveDecl into 9081 // its lookup structure so qualified name lookup can find it. 9082 DeclContext *Ctx = S->getEntity(); 9083 if (Ctx && !Ctx->isFunctionOrMethod()) 9084 Ctx->addDecl(UDir); 9085 else 9086 // Otherwise, it is at block scope. The using-directives will affect lookup 9087 // only to the end of the scope. 9088 S->PushUsingDirective(UDir); 9089 } 9090 9091 9092 Decl *Sema::ActOnUsingDeclaration(Scope *S, 9093 AccessSpecifier AS, 9094 SourceLocation UsingLoc, 9095 SourceLocation TypenameLoc, 9096 CXXScopeSpec &SS, 9097 UnqualifiedId &Name, 9098 SourceLocation EllipsisLoc, 9099 AttributeList *AttrList) { 9100 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9101 9102 if (SS.isEmpty()) { 9103 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 9104 return nullptr; 9105 } 9106 9107 switch (Name.getKind()) { 9108 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9109 case UnqualifiedIdKind::IK_Identifier: 9110 case UnqualifiedIdKind::IK_OperatorFunctionId: 9111 case UnqualifiedIdKind::IK_LiteralOperatorId: 9112 case UnqualifiedIdKind::IK_ConversionFunctionId: 9113 break; 9114 9115 case UnqualifiedIdKind::IK_ConstructorName: 9116 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9117 // C++11 inheriting constructors. 9118 Diag(Name.getLocStart(), 9119 getLangOpts().CPlusPlus11 ? 9120 diag::warn_cxx98_compat_using_decl_constructor : 9121 diag::err_using_decl_constructor) 9122 << SS.getRange(); 9123 9124 if (getLangOpts().CPlusPlus11) break; 9125 9126 return nullptr; 9127 9128 case UnqualifiedIdKind::IK_DestructorName: 9129 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9130 << SS.getRange(); 9131 return nullptr; 9132 9133 case UnqualifiedIdKind::IK_TemplateId: 9134 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9135 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9136 return nullptr; 9137 9138 case UnqualifiedIdKind::IK_DeductionGuideName: 9139 llvm_unreachable("cannot parse qualified deduction guide name"); 9140 } 9141 9142 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9143 DeclarationName TargetName = TargetNameInfo.getName(); 9144 if (!TargetName) 9145 return nullptr; 9146 9147 // Warn about access declarations. 9148 if (UsingLoc.isInvalid()) { 9149 Diag(Name.getLocStart(), 9150 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9151 : diag::warn_access_decl_deprecated) 9152 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9153 } 9154 9155 if (EllipsisLoc.isInvalid()) { 9156 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9157 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9158 return nullptr; 9159 } else { 9160 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9161 !TargetNameInfo.containsUnexpandedParameterPack()) { 9162 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9163 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9164 EllipsisLoc = SourceLocation(); 9165 } 9166 } 9167 9168 NamedDecl *UD = 9169 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9170 SS, TargetNameInfo, EllipsisLoc, AttrList, 9171 /*IsInstantiation*/false); 9172 if (UD) 9173 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9174 9175 return UD; 9176 } 9177 9178 /// \brief Determine whether a using declaration considers the given 9179 /// declarations as "equivalent", e.g., if they are redeclarations of 9180 /// the same entity or are both typedefs of the same type. 9181 static bool 9182 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9183 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9184 return true; 9185 9186 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9187 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9188 return Context.hasSameType(TD1->getUnderlyingType(), 9189 TD2->getUnderlyingType()); 9190 9191 return false; 9192 } 9193 9194 9195 /// Determines whether to create a using shadow decl for a particular 9196 /// decl, given the set of decls existing prior to this using lookup. 9197 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9198 const LookupResult &Previous, 9199 UsingShadowDecl *&PrevShadow) { 9200 // Diagnose finding a decl which is not from a base class of the 9201 // current class. We do this now because there are cases where this 9202 // function will silently decide not to build a shadow decl, which 9203 // will pre-empt further diagnostics. 9204 // 9205 // We don't need to do this in C++11 because we do the check once on 9206 // the qualifier. 9207 // 9208 // FIXME: diagnose the following if we care enough: 9209 // struct A { int foo; }; 9210 // struct B : A { using A::foo; }; 9211 // template <class T> struct C : A {}; 9212 // template <class T> struct D : C<T> { using B::foo; } // <--- 9213 // This is invalid (during instantiation) in C++03 because B::foo 9214 // resolves to the using decl in B, which is not a base class of D<T>. 9215 // We can't diagnose it immediately because C<T> is an unknown 9216 // specialization. The UsingShadowDecl in D<T> then points directly 9217 // to A::foo, which will look well-formed when we instantiate. 9218 // The right solution is to not collapse the shadow-decl chain. 9219 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9220 DeclContext *OrigDC = Orig->getDeclContext(); 9221 9222 // Handle enums and anonymous structs. 9223 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9224 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9225 while (OrigRec->isAnonymousStructOrUnion()) 9226 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9227 9228 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9229 if (OrigDC == CurContext) { 9230 Diag(Using->getLocation(), 9231 diag::err_using_decl_nested_name_specifier_is_current_class) 9232 << Using->getQualifierLoc().getSourceRange(); 9233 Diag(Orig->getLocation(), diag::note_using_decl_target); 9234 Using->setInvalidDecl(); 9235 return true; 9236 } 9237 9238 Diag(Using->getQualifierLoc().getBeginLoc(), 9239 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9240 << Using->getQualifier() 9241 << cast<CXXRecordDecl>(CurContext) 9242 << Using->getQualifierLoc().getSourceRange(); 9243 Diag(Orig->getLocation(), diag::note_using_decl_target); 9244 Using->setInvalidDecl(); 9245 return true; 9246 } 9247 } 9248 9249 if (Previous.empty()) return false; 9250 9251 NamedDecl *Target = Orig; 9252 if (isa<UsingShadowDecl>(Target)) 9253 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9254 9255 // If the target happens to be one of the previous declarations, we 9256 // don't have a conflict. 9257 // 9258 // FIXME: but we might be increasing its access, in which case we 9259 // should redeclare it. 9260 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9261 bool FoundEquivalentDecl = false; 9262 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9263 I != E; ++I) { 9264 NamedDecl *D = (*I)->getUnderlyingDecl(); 9265 // We can have UsingDecls in our Previous results because we use the same 9266 // LookupResult for checking whether the UsingDecl itself is a valid 9267 // redeclaration. 9268 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9269 continue; 9270 9271 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9272 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9273 PrevShadow = Shadow; 9274 FoundEquivalentDecl = true; 9275 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9276 // We don't conflict with an existing using shadow decl of an equivalent 9277 // declaration, but we're not a redeclaration of it. 9278 FoundEquivalentDecl = true; 9279 } 9280 9281 if (isVisible(D)) 9282 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9283 } 9284 9285 if (FoundEquivalentDecl) 9286 return false; 9287 9288 if (FunctionDecl *FD = Target->getAsFunction()) { 9289 NamedDecl *OldDecl = nullptr; 9290 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9291 /*IsForUsingDecl*/ true)) { 9292 case Ovl_Overload: 9293 return false; 9294 9295 case Ovl_NonFunction: 9296 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9297 break; 9298 9299 // We found a decl with the exact signature. 9300 case Ovl_Match: 9301 // If we're in a record, we want to hide the target, so we 9302 // return true (without a diagnostic) to tell the caller not to 9303 // build a shadow decl. 9304 if (CurContext->isRecord()) 9305 return true; 9306 9307 // If we're not in a record, this is an error. 9308 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9309 break; 9310 } 9311 9312 Diag(Target->getLocation(), diag::note_using_decl_target); 9313 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9314 Using->setInvalidDecl(); 9315 return true; 9316 } 9317 9318 // Target is not a function. 9319 9320 if (isa<TagDecl>(Target)) { 9321 // No conflict between a tag and a non-tag. 9322 if (!Tag) return false; 9323 9324 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9325 Diag(Target->getLocation(), diag::note_using_decl_target); 9326 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9327 Using->setInvalidDecl(); 9328 return true; 9329 } 9330 9331 // No conflict between a tag and a non-tag. 9332 if (!NonTag) return false; 9333 9334 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9335 Diag(Target->getLocation(), diag::note_using_decl_target); 9336 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9337 Using->setInvalidDecl(); 9338 return true; 9339 } 9340 9341 /// Determine whether a direct base class is a virtual base class. 9342 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9343 if (!Derived->getNumVBases()) 9344 return false; 9345 for (auto &B : Derived->bases()) 9346 if (B.getType()->getAsCXXRecordDecl() == Base) 9347 return B.isVirtual(); 9348 llvm_unreachable("not a direct base class"); 9349 } 9350 9351 /// Builds a shadow declaration corresponding to a 'using' declaration. 9352 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9353 UsingDecl *UD, 9354 NamedDecl *Orig, 9355 UsingShadowDecl *PrevDecl) { 9356 // If we resolved to another shadow declaration, just coalesce them. 9357 NamedDecl *Target = Orig; 9358 if (isa<UsingShadowDecl>(Target)) { 9359 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9360 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9361 } 9362 9363 NamedDecl *NonTemplateTarget = Target; 9364 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9365 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9366 9367 UsingShadowDecl *Shadow; 9368 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9369 bool IsVirtualBase = 9370 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9371 UD->getQualifier()->getAsRecordDecl()); 9372 Shadow = ConstructorUsingShadowDecl::Create( 9373 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9374 } else { 9375 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9376 Target); 9377 } 9378 UD->addShadowDecl(Shadow); 9379 9380 Shadow->setAccess(UD->getAccess()); 9381 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9382 Shadow->setInvalidDecl(); 9383 9384 Shadow->setPreviousDecl(PrevDecl); 9385 9386 if (S) 9387 PushOnScopeChains(Shadow, S); 9388 else 9389 CurContext->addDecl(Shadow); 9390 9391 9392 return Shadow; 9393 } 9394 9395 /// Hides a using shadow declaration. This is required by the current 9396 /// using-decl implementation when a resolvable using declaration in a 9397 /// class is followed by a declaration which would hide or override 9398 /// one or more of the using decl's targets; for example: 9399 /// 9400 /// struct Base { void foo(int); }; 9401 /// struct Derived : Base { 9402 /// using Base::foo; 9403 /// void foo(int); 9404 /// }; 9405 /// 9406 /// The governing language is C++03 [namespace.udecl]p12: 9407 /// 9408 /// When a using-declaration brings names from a base class into a 9409 /// derived class scope, member functions in the derived class 9410 /// override and/or hide member functions with the same name and 9411 /// parameter types in a base class (rather than conflicting). 9412 /// 9413 /// There are two ways to implement this: 9414 /// (1) optimistically create shadow decls when they're not hidden 9415 /// by existing declarations, or 9416 /// (2) don't create any shadow decls (or at least don't make them 9417 /// visible) until we've fully parsed/instantiated the class. 9418 /// The problem with (1) is that we might have to retroactively remove 9419 /// a shadow decl, which requires several O(n) operations because the 9420 /// decl structures are (very reasonably) not designed for removal. 9421 /// (2) avoids this but is very fiddly and phase-dependent. 9422 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9423 if (Shadow->getDeclName().getNameKind() == 9424 DeclarationName::CXXConversionFunctionName) 9425 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9426 9427 // Remove it from the DeclContext... 9428 Shadow->getDeclContext()->removeDecl(Shadow); 9429 9430 // ...and the scope, if applicable... 9431 if (S) { 9432 S->RemoveDecl(Shadow); 9433 IdResolver.RemoveDecl(Shadow); 9434 } 9435 9436 // ...and the using decl. 9437 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9438 9439 // TODO: complain somehow if Shadow was used. It shouldn't 9440 // be possible for this to happen, because...? 9441 } 9442 9443 /// Find the base specifier for a base class with the given type. 9444 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9445 QualType DesiredBase, 9446 bool &AnyDependentBases) { 9447 // Check whether the named type is a direct base class. 9448 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9449 for (auto &Base : Derived->bases()) { 9450 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9451 if (CanonicalDesiredBase == BaseType) 9452 return &Base; 9453 if (BaseType->isDependentType()) 9454 AnyDependentBases = true; 9455 } 9456 return nullptr; 9457 } 9458 9459 namespace { 9460 class UsingValidatorCCC : public CorrectionCandidateCallback { 9461 public: 9462 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9463 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9464 : HasTypenameKeyword(HasTypenameKeyword), 9465 IsInstantiation(IsInstantiation), OldNNS(NNS), 9466 RequireMemberOf(RequireMemberOf) {} 9467 9468 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9469 NamedDecl *ND = Candidate.getCorrectionDecl(); 9470 9471 // Keywords are not valid here. 9472 if (!ND || isa<NamespaceDecl>(ND)) 9473 return false; 9474 9475 // Completely unqualified names are invalid for a 'using' declaration. 9476 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9477 return false; 9478 9479 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9480 // reject. 9481 9482 if (RequireMemberOf) { 9483 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9484 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9485 // No-one ever wants a using-declaration to name an injected-class-name 9486 // of a base class, unless they're declaring an inheriting constructor. 9487 ASTContext &Ctx = ND->getASTContext(); 9488 if (!Ctx.getLangOpts().CPlusPlus11) 9489 return false; 9490 QualType FoundType = Ctx.getRecordType(FoundRecord); 9491 9492 // Check that the injected-class-name is named as a member of its own 9493 // type; we don't want to suggest 'using Derived::Base;', since that 9494 // means something else. 9495 NestedNameSpecifier *Specifier = 9496 Candidate.WillReplaceSpecifier() 9497 ? Candidate.getCorrectionSpecifier() 9498 : OldNNS; 9499 if (!Specifier->getAsType() || 9500 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9501 return false; 9502 9503 // Check that this inheriting constructor declaration actually names a 9504 // direct base class of the current class. 9505 bool AnyDependentBases = false; 9506 if (!findDirectBaseWithType(RequireMemberOf, 9507 Ctx.getRecordType(FoundRecord), 9508 AnyDependentBases) && 9509 !AnyDependentBases) 9510 return false; 9511 } else { 9512 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9513 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9514 return false; 9515 9516 // FIXME: Check that the base class member is accessible? 9517 } 9518 } else { 9519 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9520 if (FoundRecord && FoundRecord->isInjectedClassName()) 9521 return false; 9522 } 9523 9524 if (isa<TypeDecl>(ND)) 9525 return HasTypenameKeyword || !IsInstantiation; 9526 9527 return !HasTypenameKeyword; 9528 } 9529 9530 private: 9531 bool HasTypenameKeyword; 9532 bool IsInstantiation; 9533 NestedNameSpecifier *OldNNS; 9534 CXXRecordDecl *RequireMemberOf; 9535 }; 9536 } // end anonymous namespace 9537 9538 /// Builds a using declaration. 9539 /// 9540 /// \param IsInstantiation - Whether this call arises from an 9541 /// instantiation of an unresolved using declaration. We treat 9542 /// the lookup differently for these declarations. 9543 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9544 SourceLocation UsingLoc, 9545 bool HasTypenameKeyword, 9546 SourceLocation TypenameLoc, 9547 CXXScopeSpec &SS, 9548 DeclarationNameInfo NameInfo, 9549 SourceLocation EllipsisLoc, 9550 AttributeList *AttrList, 9551 bool IsInstantiation) { 9552 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9553 SourceLocation IdentLoc = NameInfo.getLoc(); 9554 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9555 9556 // FIXME: We ignore attributes for now. 9557 9558 // For an inheriting constructor declaration, the name of the using 9559 // declaration is the name of a constructor in this class, not in the 9560 // base class. 9561 DeclarationNameInfo UsingName = NameInfo; 9562 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9563 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9564 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9565 Context.getCanonicalType(Context.getRecordType(RD)))); 9566 9567 // Do the redeclaration lookup in the current scope. 9568 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9569 ForVisibleRedeclaration); 9570 Previous.setHideTags(false); 9571 if (S) { 9572 LookupName(Previous, S); 9573 9574 // It is really dumb that we have to do this. 9575 LookupResult::Filter F = Previous.makeFilter(); 9576 while (F.hasNext()) { 9577 NamedDecl *D = F.next(); 9578 if (!isDeclInScope(D, CurContext, S)) 9579 F.erase(); 9580 // If we found a local extern declaration that's not ordinarily visible, 9581 // and this declaration is being added to a non-block scope, ignore it. 9582 // We're only checking for scope conflicts here, not also for violations 9583 // of the linkage rules. 9584 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9585 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9586 F.erase(); 9587 } 9588 F.done(); 9589 } else { 9590 assert(IsInstantiation && "no scope in non-instantiation"); 9591 if (CurContext->isRecord()) 9592 LookupQualifiedName(Previous, CurContext); 9593 else { 9594 // No redeclaration check is needed here; in non-member contexts we 9595 // diagnosed all possible conflicts with other using-declarations when 9596 // building the template: 9597 // 9598 // For a dependent non-type using declaration, the only valid case is 9599 // if we instantiate to a single enumerator. We check for conflicts 9600 // between shadow declarations we introduce, and we check in the template 9601 // definition for conflicts between a non-type using declaration and any 9602 // other declaration, which together covers all cases. 9603 // 9604 // A dependent typename using declaration will never successfully 9605 // instantiate, since it will always name a class member, so we reject 9606 // that in the template definition. 9607 } 9608 } 9609 9610 // Check for invalid redeclarations. 9611 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9612 SS, IdentLoc, Previous)) 9613 return nullptr; 9614 9615 // Check for bad qualifiers. 9616 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9617 IdentLoc)) 9618 return nullptr; 9619 9620 DeclContext *LookupContext = computeDeclContext(SS); 9621 NamedDecl *D; 9622 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9623 if (!LookupContext || EllipsisLoc.isValid()) { 9624 if (HasTypenameKeyword) { 9625 // FIXME: not all declaration name kinds are legal here 9626 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9627 UsingLoc, TypenameLoc, 9628 QualifierLoc, 9629 IdentLoc, NameInfo.getName(), 9630 EllipsisLoc); 9631 } else { 9632 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9633 QualifierLoc, NameInfo, EllipsisLoc); 9634 } 9635 D->setAccess(AS); 9636 CurContext->addDecl(D); 9637 return D; 9638 } 9639 9640 auto Build = [&](bool Invalid) { 9641 UsingDecl *UD = 9642 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9643 UsingName, HasTypenameKeyword); 9644 UD->setAccess(AS); 9645 CurContext->addDecl(UD); 9646 UD->setInvalidDecl(Invalid); 9647 return UD; 9648 }; 9649 auto BuildInvalid = [&]{ return Build(true); }; 9650 auto BuildValid = [&]{ return Build(false); }; 9651 9652 if (RequireCompleteDeclContext(SS, LookupContext)) 9653 return BuildInvalid(); 9654 9655 // Look up the target name. 9656 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9657 9658 // Unlike most lookups, we don't always want to hide tag 9659 // declarations: tag names are visible through the using declaration 9660 // even if hidden by ordinary names, *except* in a dependent context 9661 // where it's important for the sanity of two-phase lookup. 9662 if (!IsInstantiation) 9663 R.setHideTags(false); 9664 9665 // For the purposes of this lookup, we have a base object type 9666 // equal to that of the current context. 9667 if (CurContext->isRecord()) { 9668 R.setBaseObjectType( 9669 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9670 } 9671 9672 LookupQualifiedName(R, LookupContext); 9673 9674 // Try to correct typos if possible. If constructor name lookup finds no 9675 // results, that means the named class has no explicit constructors, and we 9676 // suppressed declaring implicit ones (probably because it's dependent or 9677 // invalid). 9678 if (R.empty() && 9679 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9680 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9681 // it will believe that glibc provides a ::gets in cases where it does not, 9682 // and will try to pull it into namespace std with a using-declaration. 9683 // Just ignore the using-declaration in that case. 9684 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9685 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9686 CurContext->isStdNamespace() && 9687 isa<TranslationUnitDecl>(LookupContext) && 9688 getSourceManager().isInSystemHeader(UsingLoc)) 9689 return nullptr; 9690 if (TypoCorrection Corrected = CorrectTypo( 9691 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9692 llvm::make_unique<UsingValidatorCCC>( 9693 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9694 dyn_cast<CXXRecordDecl>(CurContext)), 9695 CTK_ErrorRecovery)) { 9696 // We reject candidates where DroppedSpecifier == true, hence the 9697 // literal '0' below. 9698 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9699 << NameInfo.getName() << LookupContext << 0 9700 << SS.getRange()); 9701 9702 // If we picked a correction with no attached Decl we can't do anything 9703 // useful with it, bail out. 9704 NamedDecl *ND = Corrected.getCorrectionDecl(); 9705 if (!ND) 9706 return BuildInvalid(); 9707 9708 // If we corrected to an inheriting constructor, handle it as one. 9709 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9710 if (RD && RD->isInjectedClassName()) { 9711 // The parent of the injected class name is the class itself. 9712 RD = cast<CXXRecordDecl>(RD->getParent()); 9713 9714 // Fix up the information we'll use to build the using declaration. 9715 if (Corrected.WillReplaceSpecifier()) { 9716 NestedNameSpecifierLocBuilder Builder; 9717 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9718 QualifierLoc.getSourceRange()); 9719 QualifierLoc = Builder.getWithLocInContext(Context); 9720 } 9721 9722 // In this case, the name we introduce is the name of a derived class 9723 // constructor. 9724 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9725 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9726 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9727 UsingName.setNamedTypeInfo(nullptr); 9728 for (auto *Ctor : LookupConstructors(RD)) 9729 R.addDecl(Ctor); 9730 R.resolveKind(); 9731 } else { 9732 // FIXME: Pick up all the declarations if we found an overloaded 9733 // function. 9734 UsingName.setName(ND->getDeclName()); 9735 R.addDecl(ND); 9736 } 9737 } else { 9738 Diag(IdentLoc, diag::err_no_member) 9739 << NameInfo.getName() << LookupContext << SS.getRange(); 9740 return BuildInvalid(); 9741 } 9742 } 9743 9744 if (R.isAmbiguous()) 9745 return BuildInvalid(); 9746 9747 if (HasTypenameKeyword) { 9748 // If we asked for a typename and got a non-type decl, error out. 9749 if (!R.getAsSingle<TypeDecl>()) { 9750 Diag(IdentLoc, diag::err_using_typename_non_type); 9751 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9752 Diag((*I)->getUnderlyingDecl()->getLocation(), 9753 diag::note_using_decl_target); 9754 return BuildInvalid(); 9755 } 9756 } else { 9757 // If we asked for a non-typename and we got a type, error out, 9758 // but only if this is an instantiation of an unresolved using 9759 // decl. Otherwise just silently find the type name. 9760 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9761 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9762 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9763 return BuildInvalid(); 9764 } 9765 } 9766 9767 // C++14 [namespace.udecl]p6: 9768 // A using-declaration shall not name a namespace. 9769 if (R.getAsSingle<NamespaceDecl>()) { 9770 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9771 << SS.getRange(); 9772 return BuildInvalid(); 9773 } 9774 9775 // C++14 [namespace.udecl]p7: 9776 // A using-declaration shall not name a scoped enumerator. 9777 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9778 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9779 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9780 << SS.getRange(); 9781 return BuildInvalid(); 9782 } 9783 } 9784 9785 UsingDecl *UD = BuildValid(); 9786 9787 // Some additional rules apply to inheriting constructors. 9788 if (UsingName.getName().getNameKind() == 9789 DeclarationName::CXXConstructorName) { 9790 // Suppress access diagnostics; the access check is instead performed at the 9791 // point of use for an inheriting constructor. 9792 R.suppressDiagnostics(); 9793 if (CheckInheritingConstructorUsingDecl(UD)) 9794 return UD; 9795 } 9796 9797 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9798 UsingShadowDecl *PrevDecl = nullptr; 9799 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9800 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9801 } 9802 9803 return UD; 9804 } 9805 9806 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9807 ArrayRef<NamedDecl *> Expansions) { 9808 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9809 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9810 isa<UsingPackDecl>(InstantiatedFrom)); 9811 9812 auto *UPD = 9813 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9814 UPD->setAccess(InstantiatedFrom->getAccess()); 9815 CurContext->addDecl(UPD); 9816 return UPD; 9817 } 9818 9819 /// Additional checks for a using declaration referring to a constructor name. 9820 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9821 assert(!UD->hasTypename() && "expecting a constructor name"); 9822 9823 const Type *SourceType = UD->getQualifier()->getAsType(); 9824 assert(SourceType && 9825 "Using decl naming constructor doesn't have type in scope spec."); 9826 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9827 9828 // Check whether the named type is a direct base class. 9829 bool AnyDependentBases = false; 9830 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9831 AnyDependentBases); 9832 if (!Base && !AnyDependentBases) { 9833 Diag(UD->getUsingLoc(), 9834 diag::err_using_decl_constructor_not_in_direct_base) 9835 << UD->getNameInfo().getSourceRange() 9836 << QualType(SourceType, 0) << TargetClass; 9837 UD->setInvalidDecl(); 9838 return true; 9839 } 9840 9841 if (Base) 9842 Base->setInheritConstructors(); 9843 9844 return false; 9845 } 9846 9847 /// Checks that the given using declaration is not an invalid 9848 /// redeclaration. Note that this is checking only for the using decl 9849 /// itself, not for any ill-formedness among the UsingShadowDecls. 9850 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9851 bool HasTypenameKeyword, 9852 const CXXScopeSpec &SS, 9853 SourceLocation NameLoc, 9854 const LookupResult &Prev) { 9855 NestedNameSpecifier *Qual = SS.getScopeRep(); 9856 9857 // C++03 [namespace.udecl]p8: 9858 // C++0x [namespace.udecl]p10: 9859 // A using-declaration is a declaration and can therefore be used 9860 // repeatedly where (and only where) multiple declarations are 9861 // allowed. 9862 // 9863 // That's in non-member contexts. 9864 if (!CurContext->getRedeclContext()->isRecord()) { 9865 // A dependent qualifier outside a class can only ever resolve to an 9866 // enumeration type. Therefore it conflicts with any other non-type 9867 // declaration in the same scope. 9868 // FIXME: How should we check for dependent type-type conflicts at block 9869 // scope? 9870 if (Qual->isDependent() && !HasTypenameKeyword) { 9871 for (auto *D : Prev) { 9872 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9873 bool OldCouldBeEnumerator = 9874 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9875 Diag(NameLoc, 9876 OldCouldBeEnumerator ? diag::err_redefinition 9877 : diag::err_redefinition_different_kind) 9878 << Prev.getLookupName(); 9879 Diag(D->getLocation(), diag::note_previous_definition); 9880 return true; 9881 } 9882 } 9883 } 9884 return false; 9885 } 9886 9887 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9888 NamedDecl *D = *I; 9889 9890 bool DTypename; 9891 NestedNameSpecifier *DQual; 9892 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9893 DTypename = UD->hasTypename(); 9894 DQual = UD->getQualifier(); 9895 } else if (UnresolvedUsingValueDecl *UD 9896 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9897 DTypename = false; 9898 DQual = UD->getQualifier(); 9899 } else if (UnresolvedUsingTypenameDecl *UD 9900 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9901 DTypename = true; 9902 DQual = UD->getQualifier(); 9903 } else continue; 9904 9905 // using decls differ if one says 'typename' and the other doesn't. 9906 // FIXME: non-dependent using decls? 9907 if (HasTypenameKeyword != DTypename) continue; 9908 9909 // using decls differ if they name different scopes (but note that 9910 // template instantiation can cause this check to trigger when it 9911 // didn't before instantiation). 9912 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9913 Context.getCanonicalNestedNameSpecifier(DQual)) 9914 continue; 9915 9916 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9917 Diag(D->getLocation(), diag::note_using_decl) << 1; 9918 return true; 9919 } 9920 9921 return false; 9922 } 9923 9924 9925 /// Checks that the given nested-name qualifier used in a using decl 9926 /// in the current context is appropriately related to the current 9927 /// scope. If an error is found, diagnoses it and returns true. 9928 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9929 bool HasTypename, 9930 const CXXScopeSpec &SS, 9931 const DeclarationNameInfo &NameInfo, 9932 SourceLocation NameLoc) { 9933 DeclContext *NamedContext = computeDeclContext(SS); 9934 9935 if (!CurContext->isRecord()) { 9936 // C++03 [namespace.udecl]p3: 9937 // C++0x [namespace.udecl]p8: 9938 // A using-declaration for a class member shall be a member-declaration. 9939 9940 // If we weren't able to compute a valid scope, it might validly be a 9941 // dependent class scope or a dependent enumeration unscoped scope. If 9942 // we have a 'typename' keyword, the scope must resolve to a class type. 9943 if ((HasTypename && !NamedContext) || 9944 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9945 auto *RD = NamedContext 9946 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9947 : nullptr; 9948 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9949 RD = nullptr; 9950 9951 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9952 << SS.getRange(); 9953 9954 // If we have a complete, non-dependent source type, try to suggest a 9955 // way to get the same effect. 9956 if (!RD) 9957 return true; 9958 9959 // Find what this using-declaration was referring to. 9960 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9961 R.setHideTags(false); 9962 R.suppressDiagnostics(); 9963 LookupQualifiedName(R, RD); 9964 9965 if (R.getAsSingle<TypeDecl>()) { 9966 if (getLangOpts().CPlusPlus11) { 9967 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9968 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9969 << 0 // alias declaration 9970 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9971 NameInfo.getName().getAsString() + 9972 " = "); 9973 } else { 9974 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9975 SourceLocation InsertLoc = 9976 getLocForEndOfToken(NameInfo.getLocEnd()); 9977 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9978 << 1 // typedef declaration 9979 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9980 << FixItHint::CreateInsertion( 9981 InsertLoc, " " + NameInfo.getName().getAsString()); 9982 } 9983 } else if (R.getAsSingle<VarDecl>()) { 9984 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9985 // repeating the type of the static data member here. 9986 FixItHint FixIt; 9987 if (getLangOpts().CPlusPlus11) { 9988 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9989 FixIt = FixItHint::CreateReplacement( 9990 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9991 } 9992 9993 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9994 << 2 // reference declaration 9995 << FixIt; 9996 } else if (R.getAsSingle<EnumConstantDecl>()) { 9997 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9998 // repeating the type of the enumeration here, and we can't do so if 9999 // the type is anonymous. 10000 FixItHint FixIt; 10001 if (getLangOpts().CPlusPlus11) { 10002 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10003 FixIt = FixItHint::CreateReplacement( 10004 UsingLoc, 10005 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10006 } 10007 10008 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10009 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10010 << FixIt; 10011 } 10012 return true; 10013 } 10014 10015 // Otherwise, this might be valid. 10016 return false; 10017 } 10018 10019 // The current scope is a record. 10020 10021 // If the named context is dependent, we can't decide much. 10022 if (!NamedContext) { 10023 // FIXME: in C++0x, we can diagnose if we can prove that the 10024 // nested-name-specifier does not refer to a base class, which is 10025 // still possible in some cases. 10026 10027 // Otherwise we have to conservatively report that things might be 10028 // okay. 10029 return false; 10030 } 10031 10032 if (!NamedContext->isRecord()) { 10033 // Ideally this would point at the last name in the specifier, 10034 // but we don't have that level of source info. 10035 Diag(SS.getRange().getBegin(), 10036 diag::err_using_decl_nested_name_specifier_is_not_class) 10037 << SS.getScopeRep() << SS.getRange(); 10038 return true; 10039 } 10040 10041 if (!NamedContext->isDependentContext() && 10042 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10043 return true; 10044 10045 if (getLangOpts().CPlusPlus11) { 10046 // C++11 [namespace.udecl]p3: 10047 // In a using-declaration used as a member-declaration, the 10048 // nested-name-specifier shall name a base class of the class 10049 // being defined. 10050 10051 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10052 cast<CXXRecordDecl>(NamedContext))) { 10053 if (CurContext == NamedContext) { 10054 Diag(NameLoc, 10055 diag::err_using_decl_nested_name_specifier_is_current_class) 10056 << SS.getRange(); 10057 return true; 10058 } 10059 10060 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10061 Diag(SS.getRange().getBegin(), 10062 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10063 << SS.getScopeRep() 10064 << cast<CXXRecordDecl>(CurContext) 10065 << SS.getRange(); 10066 } 10067 return true; 10068 } 10069 10070 return false; 10071 } 10072 10073 // C++03 [namespace.udecl]p4: 10074 // A using-declaration used as a member-declaration shall refer 10075 // to a member of a base class of the class being defined [etc.]. 10076 10077 // Salient point: SS doesn't have to name a base class as long as 10078 // lookup only finds members from base classes. Therefore we can 10079 // diagnose here only if we can prove that that can't happen, 10080 // i.e. if the class hierarchies provably don't intersect. 10081 10082 // TODO: it would be nice if "definitely valid" results were cached 10083 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10084 // need to be repeated. 10085 10086 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10087 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10088 Bases.insert(Base); 10089 return true; 10090 }; 10091 10092 // Collect all bases. Return false if we find a dependent base. 10093 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10094 return false; 10095 10096 // Returns true if the base is dependent or is one of the accumulated base 10097 // classes. 10098 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10099 return !Bases.count(Base); 10100 }; 10101 10102 // Return false if the class has a dependent base or if it or one 10103 // of its bases is present in the base set of the current context. 10104 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10105 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10106 return false; 10107 10108 Diag(SS.getRange().getBegin(), 10109 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10110 << SS.getScopeRep() 10111 << cast<CXXRecordDecl>(CurContext) 10112 << SS.getRange(); 10113 10114 return true; 10115 } 10116 10117 Decl *Sema::ActOnAliasDeclaration(Scope *S, 10118 AccessSpecifier AS, 10119 MultiTemplateParamsArg TemplateParamLists, 10120 SourceLocation UsingLoc, 10121 UnqualifiedId &Name, 10122 AttributeList *AttrList, 10123 TypeResult Type, 10124 Decl *DeclFromDeclSpec) { 10125 // Skip up to the relevant declaration scope. 10126 while (S->isTemplateParamScope()) 10127 S = S->getParent(); 10128 assert((S->getFlags() & Scope::DeclScope) && 10129 "got alias-declaration outside of declaration scope"); 10130 10131 if (Type.isInvalid()) 10132 return nullptr; 10133 10134 bool Invalid = false; 10135 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10136 TypeSourceInfo *TInfo = nullptr; 10137 GetTypeFromParser(Type.get(), &TInfo); 10138 10139 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10140 return nullptr; 10141 10142 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10143 UPPC_DeclarationType)) { 10144 Invalid = true; 10145 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10146 TInfo->getTypeLoc().getBeginLoc()); 10147 } 10148 10149 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10150 TemplateParamLists.size() 10151 ? forRedeclarationInCurContext() 10152 : ForVisibleRedeclaration); 10153 LookupName(Previous, S); 10154 10155 // Warn about shadowing the name of a template parameter. 10156 if (Previous.isSingleResult() && 10157 Previous.getFoundDecl()->isTemplateParameter()) { 10158 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10159 Previous.clear(); 10160 } 10161 10162 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10163 "name in alias declaration must be an identifier"); 10164 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10165 Name.StartLocation, 10166 Name.Identifier, TInfo); 10167 10168 NewTD->setAccess(AS); 10169 10170 if (Invalid) 10171 NewTD->setInvalidDecl(); 10172 10173 ProcessDeclAttributeList(S, NewTD, AttrList); 10174 AddPragmaAttributes(S, NewTD); 10175 10176 CheckTypedefForVariablyModifiedType(S, NewTD); 10177 Invalid |= NewTD->isInvalidDecl(); 10178 10179 bool Redeclaration = false; 10180 10181 NamedDecl *NewND; 10182 if (TemplateParamLists.size()) { 10183 TypeAliasTemplateDecl *OldDecl = nullptr; 10184 TemplateParameterList *OldTemplateParams = nullptr; 10185 10186 if (TemplateParamLists.size() != 1) { 10187 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10188 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10189 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10190 } 10191 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10192 10193 // Check that we can declare a template here. 10194 if (CheckTemplateDeclScope(S, TemplateParams)) 10195 return nullptr; 10196 10197 // Only consider previous declarations in the same scope. 10198 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10199 /*ExplicitInstantiationOrSpecialization*/false); 10200 if (!Previous.empty()) { 10201 Redeclaration = true; 10202 10203 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10204 if (!OldDecl && !Invalid) { 10205 Diag(UsingLoc, diag::err_redefinition_different_kind) 10206 << Name.Identifier; 10207 10208 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10209 if (OldD->getLocation().isValid()) 10210 Diag(OldD->getLocation(), diag::note_previous_definition); 10211 10212 Invalid = true; 10213 } 10214 10215 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10216 if (TemplateParameterListsAreEqual(TemplateParams, 10217 OldDecl->getTemplateParameters(), 10218 /*Complain=*/true, 10219 TPL_TemplateMatch)) 10220 OldTemplateParams = OldDecl->getTemplateParameters(); 10221 else 10222 Invalid = true; 10223 10224 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10225 if (!Invalid && 10226 !Context.hasSameType(OldTD->getUnderlyingType(), 10227 NewTD->getUnderlyingType())) { 10228 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10229 // but we can't reasonably accept it. 10230 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10231 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10232 if (OldTD->getLocation().isValid()) 10233 Diag(OldTD->getLocation(), diag::note_previous_definition); 10234 Invalid = true; 10235 } 10236 } 10237 } 10238 10239 // Merge any previous default template arguments into our parameters, 10240 // and check the parameter list. 10241 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10242 TPC_TypeAliasTemplate)) 10243 return nullptr; 10244 10245 TypeAliasTemplateDecl *NewDecl = 10246 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10247 Name.Identifier, TemplateParams, 10248 NewTD); 10249 NewTD->setDescribedAliasTemplate(NewDecl); 10250 10251 NewDecl->setAccess(AS); 10252 10253 if (Invalid) 10254 NewDecl->setInvalidDecl(); 10255 else if (OldDecl) { 10256 NewDecl->setPreviousDecl(OldDecl); 10257 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10258 } 10259 10260 NewND = NewDecl; 10261 } else { 10262 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10263 setTagNameForLinkagePurposes(TD, NewTD); 10264 handleTagNumbering(TD, S); 10265 } 10266 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10267 NewND = NewTD; 10268 } 10269 10270 PushOnScopeChains(NewND, S); 10271 ActOnDocumentableDecl(NewND); 10272 return NewND; 10273 } 10274 10275 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10276 SourceLocation AliasLoc, 10277 IdentifierInfo *Alias, CXXScopeSpec &SS, 10278 SourceLocation IdentLoc, 10279 IdentifierInfo *Ident) { 10280 10281 // Lookup the namespace name. 10282 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10283 LookupParsedName(R, S, &SS); 10284 10285 if (R.isAmbiguous()) 10286 return nullptr; 10287 10288 if (R.empty()) { 10289 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10290 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10291 return nullptr; 10292 } 10293 } 10294 assert(!R.isAmbiguous() && !R.empty()); 10295 NamedDecl *ND = R.getRepresentativeDecl(); 10296 10297 // Check if we have a previous declaration with the same name. 10298 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10299 ForVisibleRedeclaration); 10300 LookupName(PrevR, S); 10301 10302 // Check we're not shadowing a template parameter. 10303 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10304 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10305 PrevR.clear(); 10306 } 10307 10308 // Filter out any other lookup result from an enclosing scope. 10309 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10310 /*AllowInlineNamespace*/false); 10311 10312 // Find the previous declaration and check that we can redeclare it. 10313 NamespaceAliasDecl *Prev = nullptr; 10314 if (PrevR.isSingleResult()) { 10315 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10316 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10317 // We already have an alias with the same name that points to the same 10318 // namespace; check that it matches. 10319 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10320 Prev = AD; 10321 } else if (isVisible(PrevDecl)) { 10322 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10323 << Alias; 10324 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10325 << AD->getNamespace(); 10326 return nullptr; 10327 } 10328 } else if (isVisible(PrevDecl)) { 10329 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10330 ? diag::err_redefinition 10331 : diag::err_redefinition_different_kind; 10332 Diag(AliasLoc, DiagID) << Alias; 10333 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10334 return nullptr; 10335 } 10336 } 10337 10338 // The use of a nested name specifier may trigger deprecation warnings. 10339 DiagnoseUseOfDecl(ND, IdentLoc); 10340 10341 NamespaceAliasDecl *AliasDecl = 10342 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10343 Alias, SS.getWithLocInContext(Context), 10344 IdentLoc, ND); 10345 if (Prev) 10346 AliasDecl->setPreviousDecl(Prev); 10347 10348 PushOnScopeChains(AliasDecl, S); 10349 return AliasDecl; 10350 } 10351 10352 namespace { 10353 struct SpecialMemberExceptionSpecInfo 10354 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10355 SourceLocation Loc; 10356 Sema::ImplicitExceptionSpecification ExceptSpec; 10357 10358 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10359 Sema::CXXSpecialMember CSM, 10360 Sema::InheritedConstructorInfo *ICI, 10361 SourceLocation Loc) 10362 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10363 10364 bool visitBase(CXXBaseSpecifier *Base); 10365 bool visitField(FieldDecl *FD); 10366 10367 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10368 unsigned Quals); 10369 10370 void visitSubobjectCall(Subobject Subobj, 10371 Sema::SpecialMemberOverloadResult SMOR); 10372 }; 10373 } 10374 10375 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10376 auto *RT = Base->getType()->getAs<RecordType>(); 10377 if (!RT) 10378 return false; 10379 10380 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10381 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10382 if (auto *BaseCtor = SMOR.getMethod()) { 10383 visitSubobjectCall(Base, BaseCtor); 10384 return false; 10385 } 10386 10387 visitClassSubobject(BaseClass, Base, 0); 10388 return false; 10389 } 10390 10391 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10392 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10393 Expr *E = FD->getInClassInitializer(); 10394 if (!E) 10395 // FIXME: It's a little wasteful to build and throw away a 10396 // CXXDefaultInitExpr here. 10397 // FIXME: We should have a single context note pointing at Loc, and 10398 // this location should be MD->getLocation() instead, since that's 10399 // the location where we actually use the default init expression. 10400 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10401 if (E) 10402 ExceptSpec.CalledExpr(E); 10403 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10404 ->getAs<RecordType>()) { 10405 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10406 FD->getType().getCVRQualifiers()); 10407 } 10408 return false; 10409 } 10410 10411 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10412 Subobject Subobj, 10413 unsigned Quals) { 10414 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10415 bool IsMutable = Field && Field->isMutable(); 10416 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10417 } 10418 10419 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10420 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10421 // Note, if lookup fails, it doesn't matter what exception specification we 10422 // choose because the special member will be deleted. 10423 if (CXXMethodDecl *MD = SMOR.getMethod()) 10424 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10425 } 10426 10427 static Sema::ImplicitExceptionSpecification 10428 ComputeDefaultedSpecialMemberExceptionSpec( 10429 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10430 Sema::InheritedConstructorInfo *ICI) { 10431 CXXRecordDecl *ClassDecl = MD->getParent(); 10432 10433 // C++ [except.spec]p14: 10434 // An implicitly declared special member function (Clause 12) shall have an 10435 // exception-specification. [...] 10436 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10437 if (ClassDecl->isInvalidDecl()) 10438 return Info.ExceptSpec; 10439 10440 // C++1z [except.spec]p7: 10441 // [Look for exceptions thrown by] a constructor selected [...] to 10442 // initialize a potentially constructed subobject, 10443 // C++1z [except.spec]p8: 10444 // The exception specification for an implicitly-declared destructor, or a 10445 // destructor without a noexcept-specifier, is potentially-throwing if and 10446 // only if any of the destructors for any of its potentially constructed 10447 // subojects is potentially throwing. 10448 // FIXME: We respect the first rule but ignore the "potentially constructed" 10449 // in the second rule to resolve a core issue (no number yet) that would have 10450 // us reject: 10451 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10452 // struct B : A {}; 10453 // struct C : B { void f(); }; 10454 // ... due to giving B::~B() a non-throwing exception specification. 10455 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10456 : Info.VisitAllBases); 10457 10458 return Info.ExceptSpec; 10459 } 10460 10461 namespace { 10462 /// RAII object to register a special member as being currently declared. 10463 struct DeclaringSpecialMember { 10464 Sema &S; 10465 Sema::SpecialMemberDecl D; 10466 Sema::ContextRAII SavedContext; 10467 bool WasAlreadyBeingDeclared; 10468 10469 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10470 : S(S), D(RD, CSM), SavedContext(S, RD) { 10471 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10472 if (WasAlreadyBeingDeclared) 10473 // This almost never happens, but if it does, ensure that our cache 10474 // doesn't contain a stale result. 10475 S.SpecialMemberCache.clear(); 10476 else { 10477 // Register a note to be produced if we encounter an error while 10478 // declaring the special member. 10479 Sema::CodeSynthesisContext Ctx; 10480 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10481 // FIXME: We don't have a location to use here. Using the class's 10482 // location maintains the fiction that we declare all special members 10483 // with the class, but (1) it's not clear that lying about that helps our 10484 // users understand what's going on, and (2) there may be outer contexts 10485 // on the stack (some of which are relevant) and printing them exposes 10486 // our lies. 10487 Ctx.PointOfInstantiation = RD->getLocation(); 10488 Ctx.Entity = RD; 10489 Ctx.SpecialMember = CSM; 10490 S.pushCodeSynthesisContext(Ctx); 10491 } 10492 } 10493 ~DeclaringSpecialMember() { 10494 if (!WasAlreadyBeingDeclared) { 10495 S.SpecialMembersBeingDeclared.erase(D); 10496 S.popCodeSynthesisContext(); 10497 } 10498 } 10499 10500 /// \brief Are we already trying to declare this special member? 10501 bool isAlreadyBeingDeclared() const { 10502 return WasAlreadyBeingDeclared; 10503 } 10504 }; 10505 } 10506 10507 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10508 // Look up any existing declarations, but don't trigger declaration of all 10509 // implicit special members with this name. 10510 DeclarationName Name = FD->getDeclName(); 10511 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10512 ForExternalRedeclaration); 10513 for (auto *D : FD->getParent()->lookup(Name)) 10514 if (auto *Acceptable = R.getAcceptableDecl(D)) 10515 R.addDecl(Acceptable); 10516 R.resolveKind(); 10517 R.suppressDiagnostics(); 10518 10519 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10520 } 10521 10522 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10523 CXXRecordDecl *ClassDecl) { 10524 // C++ [class.ctor]p5: 10525 // A default constructor for a class X is a constructor of class X 10526 // that can be called without an argument. If there is no 10527 // user-declared constructor for class X, a default constructor is 10528 // implicitly declared. An implicitly-declared default constructor 10529 // is an inline public member of its class. 10530 assert(ClassDecl->needsImplicitDefaultConstructor() && 10531 "Should not build implicit default constructor!"); 10532 10533 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10534 if (DSM.isAlreadyBeingDeclared()) 10535 return nullptr; 10536 10537 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10538 CXXDefaultConstructor, 10539 false); 10540 10541 // Create the actual constructor declaration. 10542 CanQualType ClassType 10543 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10544 SourceLocation ClassLoc = ClassDecl->getLocation(); 10545 DeclarationName Name 10546 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10547 DeclarationNameInfo NameInfo(Name, ClassLoc); 10548 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10549 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10550 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10551 /*isImplicitlyDeclared=*/true, Constexpr); 10552 DefaultCon->setAccess(AS_public); 10553 DefaultCon->setDefaulted(); 10554 10555 if (getLangOpts().CUDA) { 10556 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10557 DefaultCon, 10558 /* ConstRHS */ false, 10559 /* Diagnose */ false); 10560 } 10561 10562 // Build an exception specification pointing back at this constructor. 10563 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10564 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10565 10566 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10567 // constructors is easy to compute. 10568 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10569 10570 // Note that we have declared this constructor. 10571 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10572 10573 Scope *S = getScopeForContext(ClassDecl); 10574 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10575 10576 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10577 SetDeclDeleted(DefaultCon, ClassLoc); 10578 10579 if (S) 10580 PushOnScopeChains(DefaultCon, S, false); 10581 ClassDecl->addDecl(DefaultCon); 10582 10583 return DefaultCon; 10584 } 10585 10586 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10587 CXXConstructorDecl *Constructor) { 10588 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10589 !Constructor->doesThisDeclarationHaveABody() && 10590 !Constructor->isDeleted()) && 10591 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10592 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10593 return; 10594 10595 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10596 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10597 10598 SynthesizedFunctionScope Scope(*this, Constructor); 10599 10600 // The exception specification is needed because we are defining the 10601 // function. 10602 ResolveExceptionSpec(CurrentLocation, 10603 Constructor->getType()->castAs<FunctionProtoType>()); 10604 MarkVTableUsed(CurrentLocation, ClassDecl); 10605 10606 // Add a context note for diagnostics produced after this point. 10607 Scope.addContextNote(CurrentLocation); 10608 10609 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10610 Constructor->setInvalidDecl(); 10611 return; 10612 } 10613 10614 SourceLocation Loc = Constructor->getLocEnd().isValid() 10615 ? Constructor->getLocEnd() 10616 : Constructor->getLocation(); 10617 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10618 Constructor->markUsed(Context); 10619 10620 if (ASTMutationListener *L = getASTMutationListener()) { 10621 L->CompletedImplicitDefinition(Constructor); 10622 } 10623 10624 DiagnoseUninitializedFields(*this, Constructor); 10625 } 10626 10627 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10628 // Perform any delayed checks on exception specifications. 10629 CheckDelayedMemberExceptionSpecs(); 10630 } 10631 10632 /// Find or create the fake constructor we synthesize to model constructing an 10633 /// object of a derived class via a constructor of a base class. 10634 CXXConstructorDecl * 10635 Sema::findInheritingConstructor(SourceLocation Loc, 10636 CXXConstructorDecl *BaseCtor, 10637 ConstructorUsingShadowDecl *Shadow) { 10638 CXXRecordDecl *Derived = Shadow->getParent(); 10639 SourceLocation UsingLoc = Shadow->getLocation(); 10640 10641 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10642 // For now we use the name of the base class constructor as a member of the 10643 // derived class to indicate a (fake) inherited constructor name. 10644 DeclarationName Name = BaseCtor->getDeclName(); 10645 10646 // Check to see if we already have a fake constructor for this inherited 10647 // constructor call. 10648 for (NamedDecl *Ctor : Derived->lookup(Name)) 10649 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10650 ->getInheritedConstructor() 10651 .getConstructor(), 10652 BaseCtor)) 10653 return cast<CXXConstructorDecl>(Ctor); 10654 10655 DeclarationNameInfo NameInfo(Name, UsingLoc); 10656 TypeSourceInfo *TInfo = 10657 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10658 FunctionProtoTypeLoc ProtoLoc = 10659 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10660 10661 // Check the inherited constructor is valid and find the list of base classes 10662 // from which it was inherited. 10663 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10664 10665 bool Constexpr = 10666 BaseCtor->isConstexpr() && 10667 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10668 false, BaseCtor, &ICI); 10669 10670 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10671 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10672 BaseCtor->isExplicit(), /*Inline=*/true, 10673 /*ImplicitlyDeclared=*/true, Constexpr, 10674 InheritedConstructor(Shadow, BaseCtor)); 10675 if (Shadow->isInvalidDecl()) 10676 DerivedCtor->setInvalidDecl(); 10677 10678 // Build an unevaluated exception specification for this fake constructor. 10679 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10680 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10681 EPI.ExceptionSpec.Type = EST_Unevaluated; 10682 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10683 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10684 FPT->getParamTypes(), EPI)); 10685 10686 // Build the parameter declarations. 10687 SmallVector<ParmVarDecl *, 16> ParamDecls; 10688 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10689 TypeSourceInfo *TInfo = 10690 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10691 ParmVarDecl *PD = ParmVarDecl::Create( 10692 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10693 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10694 PD->setScopeInfo(0, I); 10695 PD->setImplicit(); 10696 // Ensure attributes are propagated onto parameters (this matters for 10697 // format, pass_object_size, ...). 10698 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10699 ParamDecls.push_back(PD); 10700 ProtoLoc.setParam(I, PD); 10701 } 10702 10703 // Set up the new constructor. 10704 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10705 DerivedCtor->setAccess(BaseCtor->getAccess()); 10706 DerivedCtor->setParams(ParamDecls); 10707 Derived->addDecl(DerivedCtor); 10708 10709 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10710 SetDeclDeleted(DerivedCtor, UsingLoc); 10711 10712 return DerivedCtor; 10713 } 10714 10715 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10716 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10717 Ctor->getInheritedConstructor().getShadowDecl()); 10718 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10719 /*Diagnose*/true); 10720 } 10721 10722 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10723 CXXConstructorDecl *Constructor) { 10724 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10725 assert(Constructor->getInheritedConstructor() && 10726 !Constructor->doesThisDeclarationHaveABody() && 10727 !Constructor->isDeleted()); 10728 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10729 return; 10730 10731 // Initializations are performed "as if by a defaulted default constructor", 10732 // so enter the appropriate scope. 10733 SynthesizedFunctionScope Scope(*this, Constructor); 10734 10735 // The exception specification is needed because we are defining the 10736 // function. 10737 ResolveExceptionSpec(CurrentLocation, 10738 Constructor->getType()->castAs<FunctionProtoType>()); 10739 MarkVTableUsed(CurrentLocation, ClassDecl); 10740 10741 // Add a context note for diagnostics produced after this point. 10742 Scope.addContextNote(CurrentLocation); 10743 10744 ConstructorUsingShadowDecl *Shadow = 10745 Constructor->getInheritedConstructor().getShadowDecl(); 10746 CXXConstructorDecl *InheritedCtor = 10747 Constructor->getInheritedConstructor().getConstructor(); 10748 10749 // [class.inhctor.init]p1: 10750 // initialization proceeds as if a defaulted default constructor is used to 10751 // initialize the D object and each base class subobject from which the 10752 // constructor was inherited 10753 10754 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10755 CXXRecordDecl *RD = Shadow->getParent(); 10756 SourceLocation InitLoc = Shadow->getLocation(); 10757 10758 // Build explicit initializers for all base classes from which the 10759 // constructor was inherited. 10760 SmallVector<CXXCtorInitializer*, 8> Inits; 10761 for (bool VBase : {false, true}) { 10762 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10763 if (B.isVirtual() != VBase) 10764 continue; 10765 10766 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10767 if (!BaseRD) 10768 continue; 10769 10770 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10771 if (!BaseCtor.first) 10772 continue; 10773 10774 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10775 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10776 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10777 10778 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10779 Inits.push_back(new (Context) CXXCtorInitializer( 10780 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10781 SourceLocation())); 10782 } 10783 } 10784 10785 // We now proceed as if for a defaulted default constructor, with the relevant 10786 // initializers replaced. 10787 10788 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10789 Constructor->setInvalidDecl(); 10790 return; 10791 } 10792 10793 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10794 Constructor->markUsed(Context); 10795 10796 if (ASTMutationListener *L = getASTMutationListener()) { 10797 L->CompletedImplicitDefinition(Constructor); 10798 } 10799 10800 DiagnoseUninitializedFields(*this, Constructor); 10801 } 10802 10803 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10804 // C++ [class.dtor]p2: 10805 // If a class has no user-declared destructor, a destructor is 10806 // declared implicitly. An implicitly-declared destructor is an 10807 // inline public member of its class. 10808 assert(ClassDecl->needsImplicitDestructor()); 10809 10810 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10811 if (DSM.isAlreadyBeingDeclared()) 10812 return nullptr; 10813 10814 // Create the actual destructor declaration. 10815 CanQualType ClassType 10816 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10817 SourceLocation ClassLoc = ClassDecl->getLocation(); 10818 DeclarationName Name 10819 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10820 DeclarationNameInfo NameInfo(Name, ClassLoc); 10821 CXXDestructorDecl *Destructor 10822 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10823 QualType(), nullptr, /*isInline=*/true, 10824 /*isImplicitlyDeclared=*/true); 10825 Destructor->setAccess(AS_public); 10826 Destructor->setDefaulted(); 10827 10828 if (getLangOpts().CUDA) { 10829 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10830 Destructor, 10831 /* ConstRHS */ false, 10832 /* Diagnose */ false); 10833 } 10834 10835 // Build an exception specification pointing back at this destructor. 10836 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10837 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10838 10839 // We don't need to use SpecialMemberIsTrivial here; triviality for 10840 // destructors is easy to compute. 10841 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10842 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 10843 ClassDecl->hasTrivialDestructorForCall()); 10844 10845 // Note that we have declared this destructor. 10846 ++ASTContext::NumImplicitDestructorsDeclared; 10847 10848 Scope *S = getScopeForContext(ClassDecl); 10849 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10850 10851 // We can't check whether an implicit destructor is deleted before we complete 10852 // the definition of the class, because its validity depends on the alignment 10853 // of the class. We'll check this from ActOnFields once the class is complete. 10854 if (ClassDecl->isCompleteDefinition() && 10855 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10856 SetDeclDeleted(Destructor, ClassLoc); 10857 10858 // Introduce this destructor into its scope. 10859 if (S) 10860 PushOnScopeChains(Destructor, S, false); 10861 ClassDecl->addDecl(Destructor); 10862 10863 return Destructor; 10864 } 10865 10866 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10867 CXXDestructorDecl *Destructor) { 10868 assert((Destructor->isDefaulted() && 10869 !Destructor->doesThisDeclarationHaveABody() && 10870 !Destructor->isDeleted()) && 10871 "DefineImplicitDestructor - call it for implicit default dtor"); 10872 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10873 return; 10874 10875 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10876 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10877 10878 SynthesizedFunctionScope Scope(*this, Destructor); 10879 10880 // The exception specification is needed because we are defining the 10881 // function. 10882 ResolveExceptionSpec(CurrentLocation, 10883 Destructor->getType()->castAs<FunctionProtoType>()); 10884 MarkVTableUsed(CurrentLocation, ClassDecl); 10885 10886 // Add a context note for diagnostics produced after this point. 10887 Scope.addContextNote(CurrentLocation); 10888 10889 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10890 Destructor->getParent()); 10891 10892 if (CheckDestructor(Destructor)) { 10893 Destructor->setInvalidDecl(); 10894 return; 10895 } 10896 10897 SourceLocation Loc = Destructor->getLocEnd().isValid() 10898 ? Destructor->getLocEnd() 10899 : Destructor->getLocation(); 10900 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10901 Destructor->markUsed(Context); 10902 10903 if (ASTMutationListener *L = getASTMutationListener()) { 10904 L->CompletedImplicitDefinition(Destructor); 10905 } 10906 } 10907 10908 /// \brief Perform any semantic analysis which needs to be delayed until all 10909 /// pending class member declarations have been parsed. 10910 void Sema::ActOnFinishCXXMemberDecls() { 10911 // If the context is an invalid C++ class, just suppress these checks. 10912 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10913 if (Record->isInvalidDecl()) { 10914 DelayedDefaultedMemberExceptionSpecs.clear(); 10915 DelayedExceptionSpecChecks.clear(); 10916 return; 10917 } 10918 checkForMultipleExportedDefaultConstructors(*this, Record); 10919 } 10920 } 10921 10922 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10923 referenceDLLExportedClassMethods(); 10924 } 10925 10926 void Sema::referenceDLLExportedClassMethods() { 10927 if (!DelayedDllExportClasses.empty()) { 10928 // Calling ReferenceDllExportedMembers might cause the current function to 10929 // be called again, so use a local copy of DelayedDllExportClasses. 10930 SmallVector<CXXRecordDecl *, 4> WorkList; 10931 std::swap(DelayedDllExportClasses, WorkList); 10932 for (CXXRecordDecl *Class : WorkList) 10933 ReferenceDllExportedMembers(*this, Class); 10934 } 10935 } 10936 10937 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10938 CXXDestructorDecl *Destructor) { 10939 assert(getLangOpts().CPlusPlus11 && 10940 "adjusting dtor exception specs was introduced in c++11"); 10941 10942 // C++11 [class.dtor]p3: 10943 // A declaration of a destructor that does not have an exception- 10944 // specification is implicitly considered to have the same exception- 10945 // specification as an implicit declaration. 10946 const FunctionProtoType *DtorType = Destructor->getType()-> 10947 getAs<FunctionProtoType>(); 10948 if (DtorType->hasExceptionSpec()) 10949 return; 10950 10951 // Replace the destructor's type, building off the existing one. Fortunately, 10952 // the only thing of interest in the destructor type is its extended info. 10953 // The return and arguments are fixed. 10954 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10955 EPI.ExceptionSpec.Type = EST_Unevaluated; 10956 EPI.ExceptionSpec.SourceDecl = Destructor; 10957 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10958 10959 // FIXME: If the destructor has a body that could throw, and the newly created 10960 // spec doesn't allow exceptions, we should emit a warning, because this 10961 // change in behavior can break conforming C++03 programs at runtime. 10962 // However, we don't have a body or an exception specification yet, so it 10963 // needs to be done somewhere else. 10964 } 10965 10966 namespace { 10967 /// \brief An abstract base class for all helper classes used in building the 10968 // copy/move operators. These classes serve as factory functions and help us 10969 // avoid using the same Expr* in the AST twice. 10970 class ExprBuilder { 10971 ExprBuilder(const ExprBuilder&) = delete; 10972 ExprBuilder &operator=(const ExprBuilder&) = delete; 10973 10974 protected: 10975 static Expr *assertNotNull(Expr *E) { 10976 assert(E && "Expression construction must not fail."); 10977 return E; 10978 } 10979 10980 public: 10981 ExprBuilder() {} 10982 virtual ~ExprBuilder() {} 10983 10984 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10985 }; 10986 10987 class RefBuilder: public ExprBuilder { 10988 VarDecl *Var; 10989 QualType VarType; 10990 10991 public: 10992 Expr *build(Sema &S, SourceLocation Loc) const override { 10993 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10994 } 10995 10996 RefBuilder(VarDecl *Var, QualType VarType) 10997 : Var(Var), VarType(VarType) {} 10998 }; 10999 11000 class ThisBuilder: public ExprBuilder { 11001 public: 11002 Expr *build(Sema &S, SourceLocation Loc) const override { 11003 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11004 } 11005 }; 11006 11007 class CastBuilder: public ExprBuilder { 11008 const ExprBuilder &Builder; 11009 QualType Type; 11010 ExprValueKind Kind; 11011 const CXXCastPath &Path; 11012 11013 public: 11014 Expr *build(Sema &S, SourceLocation Loc) const override { 11015 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11016 CK_UncheckedDerivedToBase, Kind, 11017 &Path).get()); 11018 } 11019 11020 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11021 const CXXCastPath &Path) 11022 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11023 }; 11024 11025 class DerefBuilder: public ExprBuilder { 11026 const ExprBuilder &Builder; 11027 11028 public: 11029 Expr *build(Sema &S, SourceLocation Loc) const override { 11030 return assertNotNull( 11031 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11032 } 11033 11034 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11035 }; 11036 11037 class MemberBuilder: public ExprBuilder { 11038 const ExprBuilder &Builder; 11039 QualType Type; 11040 CXXScopeSpec SS; 11041 bool IsArrow; 11042 LookupResult &MemberLookup; 11043 11044 public: 11045 Expr *build(Sema &S, SourceLocation Loc) const override { 11046 return assertNotNull(S.BuildMemberReferenceExpr( 11047 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11048 nullptr, MemberLookup, nullptr, nullptr).get()); 11049 } 11050 11051 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11052 LookupResult &MemberLookup) 11053 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11054 MemberLookup(MemberLookup) {} 11055 }; 11056 11057 class MoveCastBuilder: public ExprBuilder { 11058 const ExprBuilder &Builder; 11059 11060 public: 11061 Expr *build(Sema &S, SourceLocation Loc) const override { 11062 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11063 } 11064 11065 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11066 }; 11067 11068 class LvalueConvBuilder: public ExprBuilder { 11069 const ExprBuilder &Builder; 11070 11071 public: 11072 Expr *build(Sema &S, SourceLocation Loc) const override { 11073 return assertNotNull( 11074 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11075 } 11076 11077 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11078 }; 11079 11080 class SubscriptBuilder: public ExprBuilder { 11081 const ExprBuilder &Base; 11082 const ExprBuilder &Index; 11083 11084 public: 11085 Expr *build(Sema &S, SourceLocation Loc) const override { 11086 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11087 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11088 } 11089 11090 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11091 : Base(Base), Index(Index) {} 11092 }; 11093 11094 } // end anonymous namespace 11095 11096 /// When generating a defaulted copy or move assignment operator, if a field 11097 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11098 /// do so. This optimization only applies for arrays of scalars, and for arrays 11099 /// of class type where the selected copy/move-assignment operator is trivial. 11100 static StmtResult 11101 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11102 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11103 // Compute the size of the memory buffer to be copied. 11104 QualType SizeType = S.Context.getSizeType(); 11105 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11106 S.Context.getTypeSizeInChars(T).getQuantity()); 11107 11108 // Take the address of the field references for "from" and "to". We 11109 // directly construct UnaryOperators here because semantic analysis 11110 // does not permit us to take the address of an xvalue. 11111 Expr *From = FromB.build(S, Loc); 11112 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11113 S.Context.getPointerType(From->getType()), 11114 VK_RValue, OK_Ordinary, Loc, false); 11115 Expr *To = ToB.build(S, Loc); 11116 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11117 S.Context.getPointerType(To->getType()), 11118 VK_RValue, OK_Ordinary, Loc, false); 11119 11120 const Type *E = T->getBaseElementTypeUnsafe(); 11121 bool NeedsCollectableMemCpy = 11122 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11123 11124 // Create a reference to the __builtin_objc_memmove_collectable function 11125 StringRef MemCpyName = NeedsCollectableMemCpy ? 11126 "__builtin_objc_memmove_collectable" : 11127 "__builtin_memcpy"; 11128 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11129 Sema::LookupOrdinaryName); 11130 S.LookupName(R, S.TUScope, true); 11131 11132 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11133 if (!MemCpy) 11134 // Something went horribly wrong earlier, and we will have complained 11135 // about it. 11136 return StmtError(); 11137 11138 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11139 VK_RValue, Loc, nullptr); 11140 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11141 11142 Expr *CallArgs[] = { 11143 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11144 }; 11145 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11146 Loc, CallArgs, Loc); 11147 11148 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11149 return Call.getAs<Stmt>(); 11150 } 11151 11152 /// \brief Builds a statement that copies/moves the given entity from \p From to 11153 /// \c To. 11154 /// 11155 /// This routine is used to copy/move the members of a class with an 11156 /// implicitly-declared copy/move assignment operator. When the entities being 11157 /// copied are arrays, this routine builds for loops to copy them. 11158 /// 11159 /// \param S The Sema object used for type-checking. 11160 /// 11161 /// \param Loc The location where the implicit copy/move is being generated. 11162 /// 11163 /// \param T The type of the expressions being copied/moved. Both expressions 11164 /// must have this type. 11165 /// 11166 /// \param To The expression we are copying/moving to. 11167 /// 11168 /// \param From The expression we are copying/moving from. 11169 /// 11170 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11171 /// Otherwise, it's a non-static member subobject. 11172 /// 11173 /// \param Copying Whether we're copying or moving. 11174 /// 11175 /// \param Depth Internal parameter recording the depth of the recursion. 11176 /// 11177 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11178 /// if a memcpy should be used instead. 11179 static StmtResult 11180 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11181 const ExprBuilder &To, const ExprBuilder &From, 11182 bool CopyingBaseSubobject, bool Copying, 11183 unsigned Depth = 0) { 11184 // C++11 [class.copy]p28: 11185 // Each subobject is assigned in the manner appropriate to its type: 11186 // 11187 // - if the subobject is of class type, as if by a call to operator= with 11188 // the subobject as the object expression and the corresponding 11189 // subobject of x as a single function argument (as if by explicit 11190 // qualification; that is, ignoring any possible virtual overriding 11191 // functions in more derived classes); 11192 // 11193 // C++03 [class.copy]p13: 11194 // - if the subobject is of class type, the copy assignment operator for 11195 // the class is used (as if by explicit qualification; that is, 11196 // ignoring any possible virtual overriding functions in more derived 11197 // classes); 11198 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11199 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11200 11201 // Look for operator=. 11202 DeclarationName Name 11203 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11204 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11205 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11206 11207 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11208 // operator. 11209 if (!S.getLangOpts().CPlusPlus11) { 11210 LookupResult::Filter F = OpLookup.makeFilter(); 11211 while (F.hasNext()) { 11212 NamedDecl *D = F.next(); 11213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11214 if (Method->isCopyAssignmentOperator() || 11215 (!Copying && Method->isMoveAssignmentOperator())) 11216 continue; 11217 11218 F.erase(); 11219 } 11220 F.done(); 11221 } 11222 11223 // Suppress the protected check (C++ [class.protected]) for each of the 11224 // assignment operators we found. This strange dance is required when 11225 // we're assigning via a base classes's copy-assignment operator. To 11226 // ensure that we're getting the right base class subobject (without 11227 // ambiguities), we need to cast "this" to that subobject type; to 11228 // ensure that we don't go through the virtual call mechanism, we need 11229 // to qualify the operator= name with the base class (see below). However, 11230 // this means that if the base class has a protected copy assignment 11231 // operator, the protected member access check will fail. So, we 11232 // rewrite "protected" access to "public" access in this case, since we 11233 // know by construction that we're calling from a derived class. 11234 if (CopyingBaseSubobject) { 11235 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11236 L != LEnd; ++L) { 11237 if (L.getAccess() == AS_protected) 11238 L.setAccess(AS_public); 11239 } 11240 } 11241 11242 // Create the nested-name-specifier that will be used to qualify the 11243 // reference to operator=; this is required to suppress the virtual 11244 // call mechanism. 11245 CXXScopeSpec SS; 11246 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11247 SS.MakeTrivial(S.Context, 11248 NestedNameSpecifier::Create(S.Context, nullptr, false, 11249 CanonicalT), 11250 Loc); 11251 11252 // Create the reference to operator=. 11253 ExprResult OpEqualRef 11254 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11255 SS, /*TemplateKWLoc=*/SourceLocation(), 11256 /*FirstQualifierInScope=*/nullptr, 11257 OpLookup, 11258 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11259 /*SuppressQualifierCheck=*/true); 11260 if (OpEqualRef.isInvalid()) 11261 return StmtError(); 11262 11263 // Build the call to the assignment operator. 11264 11265 Expr *FromInst = From.build(S, Loc); 11266 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11267 OpEqualRef.getAs<Expr>(), 11268 Loc, FromInst, Loc); 11269 if (Call.isInvalid()) 11270 return StmtError(); 11271 11272 // If we built a call to a trivial 'operator=' while copying an array, 11273 // bail out. We'll replace the whole shebang with a memcpy. 11274 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11275 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11276 return StmtResult((Stmt*)nullptr); 11277 11278 // Convert to an expression-statement, and clean up any produced 11279 // temporaries. 11280 return S.ActOnExprStmt(Call); 11281 } 11282 11283 // - if the subobject is of scalar type, the built-in assignment 11284 // operator is used. 11285 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11286 if (!ArrayTy) { 11287 ExprResult Assignment = S.CreateBuiltinBinOp( 11288 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11289 if (Assignment.isInvalid()) 11290 return StmtError(); 11291 return S.ActOnExprStmt(Assignment); 11292 } 11293 11294 // - if the subobject is an array, each element is assigned, in the 11295 // manner appropriate to the element type; 11296 11297 // Construct a loop over the array bounds, e.g., 11298 // 11299 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11300 // 11301 // that will copy each of the array elements. 11302 QualType SizeType = S.Context.getSizeType(); 11303 11304 // Create the iteration variable. 11305 IdentifierInfo *IterationVarName = nullptr; 11306 { 11307 SmallString<8> Str; 11308 llvm::raw_svector_ostream OS(Str); 11309 OS << "__i" << Depth; 11310 IterationVarName = &S.Context.Idents.get(OS.str()); 11311 } 11312 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11313 IterationVarName, SizeType, 11314 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11315 SC_None); 11316 11317 // Initialize the iteration variable to zero. 11318 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11319 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11320 11321 // Creates a reference to the iteration variable. 11322 RefBuilder IterationVarRef(IterationVar, SizeType); 11323 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11324 11325 // Create the DeclStmt that holds the iteration variable. 11326 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11327 11328 // Subscript the "from" and "to" expressions with the iteration variable. 11329 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11330 MoveCastBuilder FromIndexMove(FromIndexCopy); 11331 const ExprBuilder *FromIndex; 11332 if (Copying) 11333 FromIndex = &FromIndexCopy; 11334 else 11335 FromIndex = &FromIndexMove; 11336 11337 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11338 11339 // Build the copy/move for an individual element of the array. 11340 StmtResult Copy = 11341 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11342 ToIndex, *FromIndex, CopyingBaseSubobject, 11343 Copying, Depth + 1); 11344 // Bail out if copying fails or if we determined that we should use memcpy. 11345 if (Copy.isInvalid() || !Copy.get()) 11346 return Copy; 11347 11348 // Create the comparison against the array bound. 11349 llvm::APInt Upper 11350 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11351 Expr *Comparison 11352 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11353 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11354 BO_NE, S.Context.BoolTy, 11355 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11356 11357 // Create the pre-increment of the iteration variable. We can determine 11358 // whether the increment will overflow based on the value of the array 11359 // bound. 11360 Expr *Increment = new (S.Context) 11361 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11362 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11363 11364 // Construct the loop that copies all elements of this array. 11365 return S.ActOnForStmt( 11366 Loc, Loc, InitStmt, 11367 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11368 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11369 } 11370 11371 static StmtResult 11372 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11373 const ExprBuilder &To, const ExprBuilder &From, 11374 bool CopyingBaseSubobject, bool Copying) { 11375 // Maybe we should use a memcpy? 11376 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11377 T.isTriviallyCopyableType(S.Context)) 11378 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11379 11380 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11381 CopyingBaseSubobject, 11382 Copying, 0)); 11383 11384 // If we ended up picking a trivial assignment operator for an array of a 11385 // non-trivially-copyable class type, just emit a memcpy. 11386 if (!Result.isInvalid() && !Result.get()) 11387 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11388 11389 return Result; 11390 } 11391 11392 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11393 // Note: The following rules are largely analoguous to the copy 11394 // constructor rules. Note that virtual bases are not taken into account 11395 // for determining the argument type of the operator. Note also that 11396 // operators taking an object instead of a reference are allowed. 11397 assert(ClassDecl->needsImplicitCopyAssignment()); 11398 11399 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11400 if (DSM.isAlreadyBeingDeclared()) 11401 return nullptr; 11402 11403 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11404 QualType RetType = Context.getLValueReferenceType(ArgType); 11405 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11406 if (Const) 11407 ArgType = ArgType.withConst(); 11408 ArgType = Context.getLValueReferenceType(ArgType); 11409 11410 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11411 CXXCopyAssignment, 11412 Const); 11413 11414 // An implicitly-declared copy assignment operator is an inline public 11415 // member of its class. 11416 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11417 SourceLocation ClassLoc = ClassDecl->getLocation(); 11418 DeclarationNameInfo NameInfo(Name, ClassLoc); 11419 CXXMethodDecl *CopyAssignment = 11420 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11421 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11422 /*isInline=*/true, Constexpr, SourceLocation()); 11423 CopyAssignment->setAccess(AS_public); 11424 CopyAssignment->setDefaulted(); 11425 CopyAssignment->setImplicit(); 11426 11427 if (getLangOpts().CUDA) { 11428 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11429 CopyAssignment, 11430 /* ConstRHS */ Const, 11431 /* Diagnose */ false); 11432 } 11433 11434 // Build an exception specification pointing back at this member. 11435 FunctionProtoType::ExtProtoInfo EPI = 11436 getImplicitMethodEPI(*this, CopyAssignment); 11437 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11438 11439 // Add the parameter to the operator. 11440 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11441 ClassLoc, ClassLoc, 11442 /*Id=*/nullptr, ArgType, 11443 /*TInfo=*/nullptr, SC_None, 11444 nullptr); 11445 CopyAssignment->setParams(FromParam); 11446 11447 CopyAssignment->setTrivial( 11448 ClassDecl->needsOverloadResolutionForCopyAssignment() 11449 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11450 : ClassDecl->hasTrivialCopyAssignment()); 11451 11452 // Note that we have added this copy-assignment operator. 11453 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11454 11455 Scope *S = getScopeForContext(ClassDecl); 11456 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11457 11458 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11459 SetDeclDeleted(CopyAssignment, ClassLoc); 11460 11461 if (S) 11462 PushOnScopeChains(CopyAssignment, S, false); 11463 ClassDecl->addDecl(CopyAssignment); 11464 11465 return CopyAssignment; 11466 } 11467 11468 /// Diagnose an implicit copy operation for a class which is odr-used, but 11469 /// which is deprecated because the class has a user-declared copy constructor, 11470 /// copy assignment operator, or destructor. 11471 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11472 assert(CopyOp->isImplicit()); 11473 11474 CXXRecordDecl *RD = CopyOp->getParent(); 11475 CXXMethodDecl *UserDeclaredOperation = nullptr; 11476 11477 // In Microsoft mode, assignment operations don't affect constructors and 11478 // vice versa. 11479 if (RD->hasUserDeclaredDestructor()) { 11480 UserDeclaredOperation = RD->getDestructor(); 11481 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11482 RD->hasUserDeclaredCopyConstructor() && 11483 !S.getLangOpts().MSVCCompat) { 11484 // Find any user-declared copy constructor. 11485 for (auto *I : RD->ctors()) { 11486 if (I->isCopyConstructor()) { 11487 UserDeclaredOperation = I; 11488 break; 11489 } 11490 } 11491 assert(UserDeclaredOperation); 11492 } else if (isa<CXXConstructorDecl>(CopyOp) && 11493 RD->hasUserDeclaredCopyAssignment() && 11494 !S.getLangOpts().MSVCCompat) { 11495 // Find any user-declared move assignment operator. 11496 for (auto *I : RD->methods()) { 11497 if (I->isCopyAssignmentOperator()) { 11498 UserDeclaredOperation = I; 11499 break; 11500 } 11501 } 11502 assert(UserDeclaredOperation); 11503 } 11504 11505 if (UserDeclaredOperation) { 11506 S.Diag(UserDeclaredOperation->getLocation(), 11507 diag::warn_deprecated_copy_operation) 11508 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11509 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11510 } 11511 } 11512 11513 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11514 CXXMethodDecl *CopyAssignOperator) { 11515 assert((CopyAssignOperator->isDefaulted() && 11516 CopyAssignOperator->isOverloadedOperator() && 11517 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11518 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11519 !CopyAssignOperator->isDeleted()) && 11520 "DefineImplicitCopyAssignment called for wrong function"); 11521 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11522 return; 11523 11524 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11525 if (ClassDecl->isInvalidDecl()) { 11526 CopyAssignOperator->setInvalidDecl(); 11527 return; 11528 } 11529 11530 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11531 11532 // The exception specification is needed because we are defining the 11533 // function. 11534 ResolveExceptionSpec(CurrentLocation, 11535 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11536 11537 // Add a context note for diagnostics produced after this point. 11538 Scope.addContextNote(CurrentLocation); 11539 11540 // C++11 [class.copy]p18: 11541 // The [definition of an implicitly declared copy assignment operator] is 11542 // deprecated if the class has a user-declared copy constructor or a 11543 // user-declared destructor. 11544 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11545 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11546 11547 // C++0x [class.copy]p30: 11548 // The implicitly-defined or explicitly-defaulted copy assignment operator 11549 // for a non-union class X performs memberwise copy assignment of its 11550 // subobjects. The direct base classes of X are assigned first, in the 11551 // order of their declaration in the base-specifier-list, and then the 11552 // immediate non-static data members of X are assigned, in the order in 11553 // which they were declared in the class definition. 11554 11555 // The statements that form the synthesized function body. 11556 SmallVector<Stmt*, 8> Statements; 11557 11558 // The parameter for the "other" object, which we are copying from. 11559 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11560 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11561 QualType OtherRefType = Other->getType(); 11562 if (const LValueReferenceType *OtherRef 11563 = OtherRefType->getAs<LValueReferenceType>()) { 11564 OtherRefType = OtherRef->getPointeeType(); 11565 OtherQuals = OtherRefType.getQualifiers(); 11566 } 11567 11568 // Our location for everything implicitly-generated. 11569 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11570 ? CopyAssignOperator->getLocEnd() 11571 : CopyAssignOperator->getLocation(); 11572 11573 // Builds a DeclRefExpr for the "other" object. 11574 RefBuilder OtherRef(Other, OtherRefType); 11575 11576 // Builds the "this" pointer. 11577 ThisBuilder This; 11578 11579 // Assign base classes. 11580 bool Invalid = false; 11581 for (auto &Base : ClassDecl->bases()) { 11582 // Form the assignment: 11583 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11584 QualType BaseType = Base.getType().getUnqualifiedType(); 11585 if (!BaseType->isRecordType()) { 11586 Invalid = true; 11587 continue; 11588 } 11589 11590 CXXCastPath BasePath; 11591 BasePath.push_back(&Base); 11592 11593 // Construct the "from" expression, which is an implicit cast to the 11594 // appropriately-qualified base type. 11595 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11596 VK_LValue, BasePath); 11597 11598 // Dereference "this". 11599 DerefBuilder DerefThis(This); 11600 CastBuilder To(DerefThis, 11601 Context.getCVRQualifiedType( 11602 BaseType, CopyAssignOperator->getTypeQualifiers()), 11603 VK_LValue, BasePath); 11604 11605 // Build the copy. 11606 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11607 To, From, 11608 /*CopyingBaseSubobject=*/true, 11609 /*Copying=*/true); 11610 if (Copy.isInvalid()) { 11611 CopyAssignOperator->setInvalidDecl(); 11612 return; 11613 } 11614 11615 // Success! Record the copy. 11616 Statements.push_back(Copy.getAs<Expr>()); 11617 } 11618 11619 // Assign non-static members. 11620 for (auto *Field : ClassDecl->fields()) { 11621 // FIXME: We should form some kind of AST representation for the implied 11622 // memcpy in a union copy operation. 11623 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11624 continue; 11625 11626 if (Field->isInvalidDecl()) { 11627 Invalid = true; 11628 continue; 11629 } 11630 11631 // Check for members of reference type; we can't copy those. 11632 if (Field->getType()->isReferenceType()) { 11633 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11634 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11635 Diag(Field->getLocation(), diag::note_declared_at); 11636 Invalid = true; 11637 continue; 11638 } 11639 11640 // Check for members of const-qualified, non-class type. 11641 QualType BaseType = Context.getBaseElementType(Field->getType()); 11642 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11643 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11644 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11645 Diag(Field->getLocation(), diag::note_declared_at); 11646 Invalid = true; 11647 continue; 11648 } 11649 11650 // Suppress assigning zero-width bitfields. 11651 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11652 continue; 11653 11654 QualType FieldType = Field->getType().getNonReferenceType(); 11655 if (FieldType->isIncompleteArrayType()) { 11656 assert(ClassDecl->hasFlexibleArrayMember() && 11657 "Incomplete array type is not valid"); 11658 continue; 11659 } 11660 11661 // Build references to the field in the object we're copying from and to. 11662 CXXScopeSpec SS; // Intentionally empty 11663 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11664 LookupMemberName); 11665 MemberLookup.addDecl(Field); 11666 MemberLookup.resolveKind(); 11667 11668 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11669 11670 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11671 11672 // Build the copy of this field. 11673 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11674 To, From, 11675 /*CopyingBaseSubobject=*/false, 11676 /*Copying=*/true); 11677 if (Copy.isInvalid()) { 11678 CopyAssignOperator->setInvalidDecl(); 11679 return; 11680 } 11681 11682 // Success! Record the copy. 11683 Statements.push_back(Copy.getAs<Stmt>()); 11684 } 11685 11686 if (!Invalid) { 11687 // Add a "return *this;" 11688 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11689 11690 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11691 if (Return.isInvalid()) 11692 Invalid = true; 11693 else 11694 Statements.push_back(Return.getAs<Stmt>()); 11695 } 11696 11697 if (Invalid) { 11698 CopyAssignOperator->setInvalidDecl(); 11699 return; 11700 } 11701 11702 StmtResult Body; 11703 { 11704 CompoundScopeRAII CompoundScope(*this); 11705 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11706 /*isStmtExpr=*/false); 11707 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11708 } 11709 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11710 CopyAssignOperator->markUsed(Context); 11711 11712 if (ASTMutationListener *L = getASTMutationListener()) { 11713 L->CompletedImplicitDefinition(CopyAssignOperator); 11714 } 11715 } 11716 11717 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11718 assert(ClassDecl->needsImplicitMoveAssignment()); 11719 11720 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11721 if (DSM.isAlreadyBeingDeclared()) 11722 return nullptr; 11723 11724 // Note: The following rules are largely analoguous to the move 11725 // constructor rules. 11726 11727 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11728 QualType RetType = Context.getLValueReferenceType(ArgType); 11729 ArgType = Context.getRValueReferenceType(ArgType); 11730 11731 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11732 CXXMoveAssignment, 11733 false); 11734 11735 // An implicitly-declared move assignment operator is an inline public 11736 // member of its class. 11737 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11738 SourceLocation ClassLoc = ClassDecl->getLocation(); 11739 DeclarationNameInfo NameInfo(Name, ClassLoc); 11740 CXXMethodDecl *MoveAssignment = 11741 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11742 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11743 /*isInline=*/true, Constexpr, SourceLocation()); 11744 MoveAssignment->setAccess(AS_public); 11745 MoveAssignment->setDefaulted(); 11746 MoveAssignment->setImplicit(); 11747 11748 if (getLangOpts().CUDA) { 11749 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11750 MoveAssignment, 11751 /* ConstRHS */ false, 11752 /* Diagnose */ false); 11753 } 11754 11755 // Build an exception specification pointing back at this member. 11756 FunctionProtoType::ExtProtoInfo EPI = 11757 getImplicitMethodEPI(*this, MoveAssignment); 11758 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11759 11760 // Add the parameter to the operator. 11761 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11762 ClassLoc, ClassLoc, 11763 /*Id=*/nullptr, ArgType, 11764 /*TInfo=*/nullptr, SC_None, 11765 nullptr); 11766 MoveAssignment->setParams(FromParam); 11767 11768 MoveAssignment->setTrivial( 11769 ClassDecl->needsOverloadResolutionForMoveAssignment() 11770 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11771 : ClassDecl->hasTrivialMoveAssignment()); 11772 11773 // Note that we have added this copy-assignment operator. 11774 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11775 11776 Scope *S = getScopeForContext(ClassDecl); 11777 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11778 11779 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11780 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11781 SetDeclDeleted(MoveAssignment, ClassLoc); 11782 } 11783 11784 if (S) 11785 PushOnScopeChains(MoveAssignment, S, false); 11786 ClassDecl->addDecl(MoveAssignment); 11787 11788 return MoveAssignment; 11789 } 11790 11791 /// Check if we're implicitly defining a move assignment operator for a class 11792 /// with virtual bases. Such a move assignment might move-assign the virtual 11793 /// base multiple times. 11794 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11795 SourceLocation CurrentLocation) { 11796 assert(!Class->isDependentContext() && "should not define dependent move"); 11797 11798 // Only a virtual base could get implicitly move-assigned multiple times. 11799 // Only a non-trivial move assignment can observe this. We only want to 11800 // diagnose if we implicitly define an assignment operator that assigns 11801 // two base classes, both of which move-assign the same virtual base. 11802 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11803 Class->getNumBases() < 2) 11804 return; 11805 11806 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11807 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11808 VBaseMap VBases; 11809 11810 for (auto &BI : Class->bases()) { 11811 Worklist.push_back(&BI); 11812 while (!Worklist.empty()) { 11813 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11814 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11815 11816 // If the base has no non-trivial move assignment operators, 11817 // we don't care about moves from it. 11818 if (!Base->hasNonTrivialMoveAssignment()) 11819 continue; 11820 11821 // If there's nothing virtual here, skip it. 11822 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11823 continue; 11824 11825 // If we're not actually going to call a move assignment for this base, 11826 // or the selected move assignment is trivial, skip it. 11827 Sema::SpecialMemberOverloadResult SMOR = 11828 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11829 /*ConstArg*/false, /*VolatileArg*/false, 11830 /*RValueThis*/true, /*ConstThis*/false, 11831 /*VolatileThis*/false); 11832 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11833 !SMOR.getMethod()->isMoveAssignmentOperator()) 11834 continue; 11835 11836 if (BaseSpec->isVirtual()) { 11837 // We're going to move-assign this virtual base, and its move 11838 // assignment operator is not trivial. If this can happen for 11839 // multiple distinct direct bases of Class, diagnose it. (If it 11840 // only happens in one base, we'll diagnose it when synthesizing 11841 // that base class's move assignment operator.) 11842 CXXBaseSpecifier *&Existing = 11843 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11844 .first->second; 11845 if (Existing && Existing != &BI) { 11846 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11847 << Class << Base; 11848 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11849 << (Base->getCanonicalDecl() == 11850 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11851 << Base << Existing->getType() << Existing->getSourceRange(); 11852 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11853 << (Base->getCanonicalDecl() == 11854 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11855 << Base << BI.getType() << BaseSpec->getSourceRange(); 11856 11857 // Only diagnose each vbase once. 11858 Existing = nullptr; 11859 } 11860 } else { 11861 // Only walk over bases that have defaulted move assignment operators. 11862 // We assume that any user-provided move assignment operator handles 11863 // the multiple-moves-of-vbase case itself somehow. 11864 if (!SMOR.getMethod()->isDefaulted()) 11865 continue; 11866 11867 // We're going to move the base classes of Base. Add them to the list. 11868 for (auto &BI : Base->bases()) 11869 Worklist.push_back(&BI); 11870 } 11871 } 11872 } 11873 } 11874 11875 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11876 CXXMethodDecl *MoveAssignOperator) { 11877 assert((MoveAssignOperator->isDefaulted() && 11878 MoveAssignOperator->isOverloadedOperator() && 11879 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11880 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11881 !MoveAssignOperator->isDeleted()) && 11882 "DefineImplicitMoveAssignment called for wrong function"); 11883 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11884 return; 11885 11886 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11887 if (ClassDecl->isInvalidDecl()) { 11888 MoveAssignOperator->setInvalidDecl(); 11889 return; 11890 } 11891 11892 // C++0x [class.copy]p28: 11893 // The implicitly-defined or move assignment operator for a non-union class 11894 // X performs memberwise move assignment of its subobjects. The direct base 11895 // classes of X are assigned first, in the order of their declaration in the 11896 // base-specifier-list, and then the immediate non-static data members of X 11897 // are assigned, in the order in which they were declared in the class 11898 // definition. 11899 11900 // Issue a warning if our implicit move assignment operator will move 11901 // from a virtual base more than once. 11902 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11903 11904 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11905 11906 // The exception specification is needed because we are defining the 11907 // function. 11908 ResolveExceptionSpec(CurrentLocation, 11909 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11910 11911 // Add a context note for diagnostics produced after this point. 11912 Scope.addContextNote(CurrentLocation); 11913 11914 // The statements that form the synthesized function body. 11915 SmallVector<Stmt*, 8> Statements; 11916 11917 // The parameter for the "other" object, which we are move from. 11918 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11919 QualType OtherRefType = Other->getType()-> 11920 getAs<RValueReferenceType>()->getPointeeType(); 11921 assert(!OtherRefType.getQualifiers() && 11922 "Bad argument type of defaulted move assignment"); 11923 11924 // Our location for everything implicitly-generated. 11925 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11926 ? MoveAssignOperator->getLocEnd() 11927 : MoveAssignOperator->getLocation(); 11928 11929 // Builds a reference to the "other" object. 11930 RefBuilder OtherRef(Other, OtherRefType); 11931 // Cast to rvalue. 11932 MoveCastBuilder MoveOther(OtherRef); 11933 11934 // Builds the "this" pointer. 11935 ThisBuilder This; 11936 11937 // Assign base classes. 11938 bool Invalid = false; 11939 for (auto &Base : ClassDecl->bases()) { 11940 // C++11 [class.copy]p28: 11941 // It is unspecified whether subobjects representing virtual base classes 11942 // are assigned more than once by the implicitly-defined copy assignment 11943 // operator. 11944 // FIXME: Do not assign to a vbase that will be assigned by some other base 11945 // class. For a move-assignment, this can result in the vbase being moved 11946 // multiple times. 11947 11948 // Form the assignment: 11949 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11950 QualType BaseType = Base.getType().getUnqualifiedType(); 11951 if (!BaseType->isRecordType()) { 11952 Invalid = true; 11953 continue; 11954 } 11955 11956 CXXCastPath BasePath; 11957 BasePath.push_back(&Base); 11958 11959 // Construct the "from" expression, which is an implicit cast to the 11960 // appropriately-qualified base type. 11961 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11962 11963 // Dereference "this". 11964 DerefBuilder DerefThis(This); 11965 11966 // Implicitly cast "this" to the appropriately-qualified base type. 11967 CastBuilder To(DerefThis, 11968 Context.getCVRQualifiedType( 11969 BaseType, MoveAssignOperator->getTypeQualifiers()), 11970 VK_LValue, BasePath); 11971 11972 // Build the move. 11973 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11974 To, From, 11975 /*CopyingBaseSubobject=*/true, 11976 /*Copying=*/false); 11977 if (Move.isInvalid()) { 11978 MoveAssignOperator->setInvalidDecl(); 11979 return; 11980 } 11981 11982 // Success! Record the move. 11983 Statements.push_back(Move.getAs<Expr>()); 11984 } 11985 11986 // Assign non-static members. 11987 for (auto *Field : ClassDecl->fields()) { 11988 // FIXME: We should form some kind of AST representation for the implied 11989 // memcpy in a union copy operation. 11990 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11991 continue; 11992 11993 if (Field->isInvalidDecl()) { 11994 Invalid = true; 11995 continue; 11996 } 11997 11998 // Check for members of reference type; we can't move those. 11999 if (Field->getType()->isReferenceType()) { 12000 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12001 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12002 Diag(Field->getLocation(), diag::note_declared_at); 12003 Invalid = true; 12004 continue; 12005 } 12006 12007 // Check for members of const-qualified, non-class type. 12008 QualType BaseType = Context.getBaseElementType(Field->getType()); 12009 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12010 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12011 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12012 Diag(Field->getLocation(), diag::note_declared_at); 12013 Invalid = true; 12014 continue; 12015 } 12016 12017 // Suppress assigning zero-width bitfields. 12018 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 12019 continue; 12020 12021 QualType FieldType = Field->getType().getNonReferenceType(); 12022 if (FieldType->isIncompleteArrayType()) { 12023 assert(ClassDecl->hasFlexibleArrayMember() && 12024 "Incomplete array type is not valid"); 12025 continue; 12026 } 12027 12028 // Build references to the field in the object we're copying from and to. 12029 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12030 LookupMemberName); 12031 MemberLookup.addDecl(Field); 12032 MemberLookup.resolveKind(); 12033 MemberBuilder From(MoveOther, OtherRefType, 12034 /*IsArrow=*/false, MemberLookup); 12035 MemberBuilder To(This, getCurrentThisType(), 12036 /*IsArrow=*/true, MemberLookup); 12037 12038 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12039 "Member reference with rvalue base must be rvalue except for reference " 12040 "members, which aren't allowed for move assignment."); 12041 12042 // Build the move of this field. 12043 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12044 To, From, 12045 /*CopyingBaseSubobject=*/false, 12046 /*Copying=*/false); 12047 if (Move.isInvalid()) { 12048 MoveAssignOperator->setInvalidDecl(); 12049 return; 12050 } 12051 12052 // Success! Record the copy. 12053 Statements.push_back(Move.getAs<Stmt>()); 12054 } 12055 12056 if (!Invalid) { 12057 // Add a "return *this;" 12058 ExprResult ThisObj = 12059 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12060 12061 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12062 if (Return.isInvalid()) 12063 Invalid = true; 12064 else 12065 Statements.push_back(Return.getAs<Stmt>()); 12066 } 12067 12068 if (Invalid) { 12069 MoveAssignOperator->setInvalidDecl(); 12070 return; 12071 } 12072 12073 StmtResult Body; 12074 { 12075 CompoundScopeRAII CompoundScope(*this); 12076 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12077 /*isStmtExpr=*/false); 12078 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12079 } 12080 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12081 MoveAssignOperator->markUsed(Context); 12082 12083 if (ASTMutationListener *L = getASTMutationListener()) { 12084 L->CompletedImplicitDefinition(MoveAssignOperator); 12085 } 12086 } 12087 12088 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12089 CXXRecordDecl *ClassDecl) { 12090 // C++ [class.copy]p4: 12091 // If the class definition does not explicitly declare a copy 12092 // constructor, one is declared implicitly. 12093 assert(ClassDecl->needsImplicitCopyConstructor()); 12094 12095 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12096 if (DSM.isAlreadyBeingDeclared()) 12097 return nullptr; 12098 12099 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12100 QualType ArgType = ClassType; 12101 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12102 if (Const) 12103 ArgType = ArgType.withConst(); 12104 ArgType = Context.getLValueReferenceType(ArgType); 12105 12106 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12107 CXXCopyConstructor, 12108 Const); 12109 12110 DeclarationName Name 12111 = Context.DeclarationNames.getCXXConstructorName( 12112 Context.getCanonicalType(ClassType)); 12113 SourceLocation ClassLoc = ClassDecl->getLocation(); 12114 DeclarationNameInfo NameInfo(Name, ClassLoc); 12115 12116 // An implicitly-declared copy constructor is an inline public 12117 // member of its class. 12118 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12119 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12120 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12121 Constexpr); 12122 CopyConstructor->setAccess(AS_public); 12123 CopyConstructor->setDefaulted(); 12124 12125 if (getLangOpts().CUDA) { 12126 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12127 CopyConstructor, 12128 /* ConstRHS */ Const, 12129 /* Diagnose */ false); 12130 } 12131 12132 // Build an exception specification pointing back at this member. 12133 FunctionProtoType::ExtProtoInfo EPI = 12134 getImplicitMethodEPI(*this, CopyConstructor); 12135 CopyConstructor->setType( 12136 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12137 12138 // Add the parameter to the constructor. 12139 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12140 ClassLoc, ClassLoc, 12141 /*IdentifierInfo=*/nullptr, 12142 ArgType, /*TInfo=*/nullptr, 12143 SC_None, nullptr); 12144 CopyConstructor->setParams(FromParam); 12145 12146 CopyConstructor->setTrivial( 12147 ClassDecl->needsOverloadResolutionForCopyConstructor() 12148 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12149 : ClassDecl->hasTrivialCopyConstructor()); 12150 12151 CopyConstructor->setTrivialForCall( 12152 ClassDecl->hasAttr<TrivialABIAttr>() || 12153 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12154 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12155 TAH_ConsiderTrivialABI) 12156 : ClassDecl->hasTrivialCopyConstructorForCall())); 12157 12158 // Note that we have declared this constructor. 12159 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12160 12161 Scope *S = getScopeForContext(ClassDecl); 12162 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12163 12164 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12165 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12166 SetDeclDeleted(CopyConstructor, ClassLoc); 12167 } 12168 12169 if (S) 12170 PushOnScopeChains(CopyConstructor, S, false); 12171 ClassDecl->addDecl(CopyConstructor); 12172 12173 return CopyConstructor; 12174 } 12175 12176 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12177 CXXConstructorDecl *CopyConstructor) { 12178 assert((CopyConstructor->isDefaulted() && 12179 CopyConstructor->isCopyConstructor() && 12180 !CopyConstructor->doesThisDeclarationHaveABody() && 12181 !CopyConstructor->isDeleted()) && 12182 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12183 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12184 return; 12185 12186 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12187 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12188 12189 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12190 12191 // The exception specification is needed because we are defining the 12192 // function. 12193 ResolveExceptionSpec(CurrentLocation, 12194 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12195 MarkVTableUsed(CurrentLocation, ClassDecl); 12196 12197 // Add a context note for diagnostics produced after this point. 12198 Scope.addContextNote(CurrentLocation); 12199 12200 // C++11 [class.copy]p7: 12201 // The [definition of an implicitly declared copy constructor] is 12202 // deprecated if the class has a user-declared copy assignment operator 12203 // or a user-declared destructor. 12204 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12205 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12206 12207 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12208 CopyConstructor->setInvalidDecl(); 12209 } else { 12210 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12211 ? CopyConstructor->getLocEnd() 12212 : CopyConstructor->getLocation(); 12213 Sema::CompoundScopeRAII CompoundScope(*this); 12214 CopyConstructor->setBody( 12215 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12216 CopyConstructor->markUsed(Context); 12217 } 12218 12219 if (ASTMutationListener *L = getASTMutationListener()) { 12220 L->CompletedImplicitDefinition(CopyConstructor); 12221 } 12222 } 12223 12224 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12225 CXXRecordDecl *ClassDecl) { 12226 assert(ClassDecl->needsImplicitMoveConstructor()); 12227 12228 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12229 if (DSM.isAlreadyBeingDeclared()) 12230 return nullptr; 12231 12232 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12233 QualType ArgType = Context.getRValueReferenceType(ClassType); 12234 12235 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12236 CXXMoveConstructor, 12237 false); 12238 12239 DeclarationName Name 12240 = Context.DeclarationNames.getCXXConstructorName( 12241 Context.getCanonicalType(ClassType)); 12242 SourceLocation ClassLoc = ClassDecl->getLocation(); 12243 DeclarationNameInfo NameInfo(Name, ClassLoc); 12244 12245 // C++11 [class.copy]p11: 12246 // An implicitly-declared copy/move constructor is an inline public 12247 // member of its class. 12248 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12249 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12250 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12251 Constexpr); 12252 MoveConstructor->setAccess(AS_public); 12253 MoveConstructor->setDefaulted(); 12254 12255 if (getLangOpts().CUDA) { 12256 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12257 MoveConstructor, 12258 /* ConstRHS */ false, 12259 /* Diagnose */ false); 12260 } 12261 12262 // Build an exception specification pointing back at this member. 12263 FunctionProtoType::ExtProtoInfo EPI = 12264 getImplicitMethodEPI(*this, MoveConstructor); 12265 MoveConstructor->setType( 12266 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12267 12268 // Add the parameter to the constructor. 12269 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12270 ClassLoc, ClassLoc, 12271 /*IdentifierInfo=*/nullptr, 12272 ArgType, /*TInfo=*/nullptr, 12273 SC_None, nullptr); 12274 MoveConstructor->setParams(FromParam); 12275 12276 MoveConstructor->setTrivial( 12277 ClassDecl->needsOverloadResolutionForMoveConstructor() 12278 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12279 : ClassDecl->hasTrivialMoveConstructor()); 12280 12281 MoveConstructor->setTrivialForCall( 12282 ClassDecl->hasAttr<TrivialABIAttr>() || 12283 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12284 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12285 TAH_ConsiderTrivialABI) 12286 : ClassDecl->hasTrivialMoveConstructorForCall())); 12287 12288 // Note that we have declared this constructor. 12289 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12290 12291 Scope *S = getScopeForContext(ClassDecl); 12292 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12293 12294 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12295 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12296 SetDeclDeleted(MoveConstructor, ClassLoc); 12297 } 12298 12299 if (S) 12300 PushOnScopeChains(MoveConstructor, S, false); 12301 ClassDecl->addDecl(MoveConstructor); 12302 12303 return MoveConstructor; 12304 } 12305 12306 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12307 CXXConstructorDecl *MoveConstructor) { 12308 assert((MoveConstructor->isDefaulted() && 12309 MoveConstructor->isMoveConstructor() && 12310 !MoveConstructor->doesThisDeclarationHaveABody() && 12311 !MoveConstructor->isDeleted()) && 12312 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12313 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12314 return; 12315 12316 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12317 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12318 12319 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12320 12321 // The exception specification is needed because we are defining the 12322 // function. 12323 ResolveExceptionSpec(CurrentLocation, 12324 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12325 MarkVTableUsed(CurrentLocation, ClassDecl); 12326 12327 // Add a context note for diagnostics produced after this point. 12328 Scope.addContextNote(CurrentLocation); 12329 12330 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12331 MoveConstructor->setInvalidDecl(); 12332 } else { 12333 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12334 ? MoveConstructor->getLocEnd() 12335 : MoveConstructor->getLocation(); 12336 Sema::CompoundScopeRAII CompoundScope(*this); 12337 MoveConstructor->setBody(ActOnCompoundStmt( 12338 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12339 MoveConstructor->markUsed(Context); 12340 } 12341 12342 if (ASTMutationListener *L = getASTMutationListener()) { 12343 L->CompletedImplicitDefinition(MoveConstructor); 12344 } 12345 } 12346 12347 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12348 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12349 } 12350 12351 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12352 SourceLocation CurrentLocation, 12353 CXXConversionDecl *Conv) { 12354 SynthesizedFunctionScope Scope(*this, Conv); 12355 assert(!Conv->getReturnType()->isUndeducedType()); 12356 12357 CXXRecordDecl *Lambda = Conv->getParent(); 12358 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12359 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12360 12361 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12362 CallOp = InstantiateFunctionDeclaration( 12363 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12364 if (!CallOp) 12365 return; 12366 12367 Invoker = InstantiateFunctionDeclaration( 12368 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12369 if (!Invoker) 12370 return; 12371 } 12372 12373 if (CallOp->isInvalidDecl()) 12374 return; 12375 12376 // Mark the call operator referenced (and add to pending instantiations 12377 // if necessary). 12378 // For both the conversion and static-invoker template specializations 12379 // we construct their body's in this function, so no need to add them 12380 // to the PendingInstantiations. 12381 MarkFunctionReferenced(CurrentLocation, CallOp); 12382 12383 // Fill in the __invoke function with a dummy implementation. IR generation 12384 // will fill in the actual details. Update its type in case it contained 12385 // an 'auto'. 12386 Invoker->markUsed(Context); 12387 Invoker->setReferenced(); 12388 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12389 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12390 12391 // Construct the body of the conversion function { return __invoke; }. 12392 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12393 VK_LValue, Conv->getLocation()).get(); 12394 assert(FunctionRef && "Can't refer to __invoke function?"); 12395 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12396 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12397 Conv->getLocation())); 12398 Conv->markUsed(Context); 12399 Conv->setReferenced(); 12400 12401 if (ASTMutationListener *L = getASTMutationListener()) { 12402 L->CompletedImplicitDefinition(Conv); 12403 L->CompletedImplicitDefinition(Invoker); 12404 } 12405 } 12406 12407 12408 12409 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12410 SourceLocation CurrentLocation, 12411 CXXConversionDecl *Conv) 12412 { 12413 assert(!Conv->getParent()->isGenericLambda()); 12414 12415 SynthesizedFunctionScope Scope(*this, Conv); 12416 12417 // Copy-initialize the lambda object as needed to capture it. 12418 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12419 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12420 12421 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12422 Conv->getLocation(), 12423 Conv, DerefThis); 12424 12425 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12426 // behavior. Note that only the general conversion function does this 12427 // (since it's unusable otherwise); in the case where we inline the 12428 // block literal, it has block literal lifetime semantics. 12429 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12430 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12431 CK_CopyAndAutoreleaseBlockObject, 12432 BuildBlock.get(), nullptr, VK_RValue); 12433 12434 if (BuildBlock.isInvalid()) { 12435 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12436 Conv->setInvalidDecl(); 12437 return; 12438 } 12439 12440 // Create the return statement that returns the block from the conversion 12441 // function. 12442 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12443 if (Return.isInvalid()) { 12444 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12445 Conv->setInvalidDecl(); 12446 return; 12447 } 12448 12449 // Set the body of the conversion function. 12450 Stmt *ReturnS = Return.get(); 12451 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12452 Conv->getLocation())); 12453 Conv->markUsed(Context); 12454 12455 // We're done; notify the mutation listener, if any. 12456 if (ASTMutationListener *L = getASTMutationListener()) { 12457 L->CompletedImplicitDefinition(Conv); 12458 } 12459 } 12460 12461 /// \brief Determine whether the given list arguments contains exactly one 12462 /// "real" (non-default) argument. 12463 static bool hasOneRealArgument(MultiExprArg Args) { 12464 switch (Args.size()) { 12465 case 0: 12466 return false; 12467 12468 default: 12469 if (!Args[1]->isDefaultArgument()) 12470 return false; 12471 12472 LLVM_FALLTHROUGH; 12473 case 1: 12474 return !Args[0]->isDefaultArgument(); 12475 } 12476 12477 return false; 12478 } 12479 12480 ExprResult 12481 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12482 NamedDecl *FoundDecl, 12483 CXXConstructorDecl *Constructor, 12484 MultiExprArg ExprArgs, 12485 bool HadMultipleCandidates, 12486 bool IsListInitialization, 12487 bool IsStdInitListInitialization, 12488 bool RequiresZeroInit, 12489 unsigned ConstructKind, 12490 SourceRange ParenRange) { 12491 bool Elidable = false; 12492 12493 // C++0x [class.copy]p34: 12494 // When certain criteria are met, an implementation is allowed to 12495 // omit the copy/move construction of a class object, even if the 12496 // copy/move constructor and/or destructor for the object have 12497 // side effects. [...] 12498 // - when a temporary class object that has not been bound to a 12499 // reference (12.2) would be copied/moved to a class object 12500 // with the same cv-unqualified type, the copy/move operation 12501 // can be omitted by constructing the temporary object 12502 // directly into the target of the omitted copy/move 12503 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12504 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12505 Expr *SubExpr = ExprArgs[0]; 12506 Elidable = SubExpr->isTemporaryObject( 12507 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12508 } 12509 12510 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12511 FoundDecl, Constructor, 12512 Elidable, ExprArgs, HadMultipleCandidates, 12513 IsListInitialization, 12514 IsStdInitListInitialization, RequiresZeroInit, 12515 ConstructKind, ParenRange); 12516 } 12517 12518 ExprResult 12519 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12520 NamedDecl *FoundDecl, 12521 CXXConstructorDecl *Constructor, 12522 bool Elidable, 12523 MultiExprArg ExprArgs, 12524 bool HadMultipleCandidates, 12525 bool IsListInitialization, 12526 bool IsStdInitListInitialization, 12527 bool RequiresZeroInit, 12528 unsigned ConstructKind, 12529 SourceRange ParenRange) { 12530 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12531 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12532 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12533 return ExprError(); 12534 } 12535 12536 return BuildCXXConstructExpr( 12537 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12538 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12539 RequiresZeroInit, ConstructKind, ParenRange); 12540 } 12541 12542 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12543 /// including handling of its default argument expressions. 12544 ExprResult 12545 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12546 CXXConstructorDecl *Constructor, 12547 bool Elidable, 12548 MultiExprArg ExprArgs, 12549 bool HadMultipleCandidates, 12550 bool IsListInitialization, 12551 bool IsStdInitListInitialization, 12552 bool RequiresZeroInit, 12553 unsigned ConstructKind, 12554 SourceRange ParenRange) { 12555 assert(declaresSameEntity( 12556 Constructor->getParent(), 12557 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12558 "given constructor for wrong type"); 12559 MarkFunctionReferenced(ConstructLoc, Constructor); 12560 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12561 return ExprError(); 12562 12563 return CXXConstructExpr::Create( 12564 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12565 ExprArgs, HadMultipleCandidates, IsListInitialization, 12566 IsStdInitListInitialization, RequiresZeroInit, 12567 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12568 ParenRange); 12569 } 12570 12571 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12572 assert(Field->hasInClassInitializer()); 12573 12574 // If we already have the in-class initializer nothing needs to be done. 12575 if (Field->getInClassInitializer()) 12576 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12577 12578 // If we might have already tried and failed to instantiate, don't try again. 12579 if (Field->isInvalidDecl()) 12580 return ExprError(); 12581 12582 // Maybe we haven't instantiated the in-class initializer. Go check the 12583 // pattern FieldDecl to see if it has one. 12584 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12585 12586 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12587 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12588 DeclContext::lookup_result Lookup = 12589 ClassPattern->lookup(Field->getDeclName()); 12590 12591 // Lookup can return at most two results: the pattern for the field, or the 12592 // injected class name of the parent record. No other member can have the 12593 // same name as the field. 12594 // In modules mode, lookup can return multiple results (coming from 12595 // different modules). 12596 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12597 "more than two lookup results for field name"); 12598 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12599 if (!Pattern) { 12600 assert(isa<CXXRecordDecl>(Lookup[0]) && 12601 "cannot have other non-field member with same name"); 12602 for (auto L : Lookup) 12603 if (isa<FieldDecl>(L)) { 12604 Pattern = cast<FieldDecl>(L); 12605 break; 12606 } 12607 assert(Pattern && "We must have set the Pattern!"); 12608 } 12609 12610 if (!Pattern->hasInClassInitializer() || 12611 InstantiateInClassInitializer(Loc, Field, Pattern, 12612 getTemplateInstantiationArgs(Field))) { 12613 // Don't diagnose this again. 12614 Field->setInvalidDecl(); 12615 return ExprError(); 12616 } 12617 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12618 } 12619 12620 // DR1351: 12621 // If the brace-or-equal-initializer of a non-static data member 12622 // invokes a defaulted default constructor of its class or of an 12623 // enclosing class in a potentially evaluated subexpression, the 12624 // program is ill-formed. 12625 // 12626 // This resolution is unworkable: the exception specification of the 12627 // default constructor can be needed in an unevaluated context, in 12628 // particular, in the operand of a noexcept-expression, and we can be 12629 // unable to compute an exception specification for an enclosed class. 12630 // 12631 // Any attempt to resolve the exception specification of a defaulted default 12632 // constructor before the initializer is lexically complete will ultimately 12633 // come here at which point we can diagnose it. 12634 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12635 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12636 << OutermostClass << Field; 12637 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12638 // Recover by marking the field invalid, unless we're in a SFINAE context. 12639 if (!isSFINAEContext()) 12640 Field->setInvalidDecl(); 12641 return ExprError(); 12642 } 12643 12644 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12645 if (VD->isInvalidDecl()) return; 12646 12647 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12648 if (ClassDecl->isInvalidDecl()) return; 12649 if (ClassDecl->hasIrrelevantDestructor()) return; 12650 if (ClassDecl->isDependentContext()) return; 12651 12652 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12653 MarkFunctionReferenced(VD->getLocation(), Destructor); 12654 CheckDestructorAccess(VD->getLocation(), Destructor, 12655 PDiag(diag::err_access_dtor_var) 12656 << VD->getDeclName() 12657 << VD->getType()); 12658 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12659 12660 if (Destructor->isTrivial()) return; 12661 if (!VD->hasGlobalStorage()) return; 12662 12663 // Emit warning for non-trivial dtor in global scope (a real global, 12664 // class-static, function-static). 12665 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12666 12667 // TODO: this should be re-enabled for static locals by !CXAAtExit 12668 if (!VD->isStaticLocal()) 12669 Diag(VD->getLocation(), diag::warn_global_destructor); 12670 } 12671 12672 /// \brief Given a constructor and the set of arguments provided for the 12673 /// constructor, convert the arguments and add any required default arguments 12674 /// to form a proper call to this constructor. 12675 /// 12676 /// \returns true if an error occurred, false otherwise. 12677 bool 12678 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12679 MultiExprArg ArgsPtr, 12680 SourceLocation Loc, 12681 SmallVectorImpl<Expr*> &ConvertedArgs, 12682 bool AllowExplicit, 12683 bool IsListInitialization) { 12684 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12685 unsigned NumArgs = ArgsPtr.size(); 12686 Expr **Args = ArgsPtr.data(); 12687 12688 const FunctionProtoType *Proto 12689 = Constructor->getType()->getAs<FunctionProtoType>(); 12690 assert(Proto && "Constructor without a prototype?"); 12691 unsigned NumParams = Proto->getNumParams(); 12692 12693 // If too few arguments are available, we'll fill in the rest with defaults. 12694 if (NumArgs < NumParams) 12695 ConvertedArgs.reserve(NumParams); 12696 else 12697 ConvertedArgs.reserve(NumArgs); 12698 12699 VariadicCallType CallType = 12700 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12701 SmallVector<Expr *, 8> AllArgs; 12702 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12703 Proto, 0, 12704 llvm::makeArrayRef(Args, NumArgs), 12705 AllArgs, 12706 CallType, AllowExplicit, 12707 IsListInitialization); 12708 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12709 12710 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12711 12712 CheckConstructorCall(Constructor, 12713 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12714 Proto, Loc); 12715 12716 return Invalid; 12717 } 12718 12719 static inline bool 12720 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12721 const FunctionDecl *FnDecl) { 12722 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12723 if (isa<NamespaceDecl>(DC)) { 12724 return SemaRef.Diag(FnDecl->getLocation(), 12725 diag::err_operator_new_delete_declared_in_namespace) 12726 << FnDecl->getDeclName(); 12727 } 12728 12729 if (isa<TranslationUnitDecl>(DC) && 12730 FnDecl->getStorageClass() == SC_Static) { 12731 return SemaRef.Diag(FnDecl->getLocation(), 12732 diag::err_operator_new_delete_declared_static) 12733 << FnDecl->getDeclName(); 12734 } 12735 12736 return false; 12737 } 12738 12739 static inline bool 12740 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12741 CanQualType ExpectedResultType, 12742 CanQualType ExpectedFirstParamType, 12743 unsigned DependentParamTypeDiag, 12744 unsigned InvalidParamTypeDiag) { 12745 QualType ResultType = 12746 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12747 12748 // Check that the result type is not dependent. 12749 if (ResultType->isDependentType()) 12750 return SemaRef.Diag(FnDecl->getLocation(), 12751 diag::err_operator_new_delete_dependent_result_type) 12752 << FnDecl->getDeclName() << ExpectedResultType; 12753 12754 // Check that the result type is what we expect. 12755 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12756 return SemaRef.Diag(FnDecl->getLocation(), 12757 diag::err_operator_new_delete_invalid_result_type) 12758 << FnDecl->getDeclName() << ExpectedResultType; 12759 12760 // A function template must have at least 2 parameters. 12761 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12762 return SemaRef.Diag(FnDecl->getLocation(), 12763 diag::err_operator_new_delete_template_too_few_parameters) 12764 << FnDecl->getDeclName(); 12765 12766 // The function decl must have at least 1 parameter. 12767 if (FnDecl->getNumParams() == 0) 12768 return SemaRef.Diag(FnDecl->getLocation(), 12769 diag::err_operator_new_delete_too_few_parameters) 12770 << FnDecl->getDeclName(); 12771 12772 // Check the first parameter type is not dependent. 12773 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12774 if (FirstParamType->isDependentType()) 12775 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12776 << FnDecl->getDeclName() << ExpectedFirstParamType; 12777 12778 // Check that the first parameter type is what we expect. 12779 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12780 ExpectedFirstParamType) 12781 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12782 << FnDecl->getDeclName() << ExpectedFirstParamType; 12783 12784 return false; 12785 } 12786 12787 static bool 12788 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12789 // C++ [basic.stc.dynamic.allocation]p1: 12790 // A program is ill-formed if an allocation function is declared in a 12791 // namespace scope other than global scope or declared static in global 12792 // scope. 12793 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12794 return true; 12795 12796 CanQualType SizeTy = 12797 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12798 12799 // C++ [basic.stc.dynamic.allocation]p1: 12800 // The return type shall be void*. The first parameter shall have type 12801 // std::size_t. 12802 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12803 SizeTy, 12804 diag::err_operator_new_dependent_param_type, 12805 diag::err_operator_new_param_type)) 12806 return true; 12807 12808 // C++ [basic.stc.dynamic.allocation]p1: 12809 // The first parameter shall not have an associated default argument. 12810 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12811 return SemaRef.Diag(FnDecl->getLocation(), 12812 diag::err_operator_new_default_arg) 12813 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12814 12815 return false; 12816 } 12817 12818 static bool 12819 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12820 // C++ [basic.stc.dynamic.deallocation]p1: 12821 // A program is ill-formed if deallocation functions are declared in a 12822 // namespace scope other than global scope or declared static in global 12823 // scope. 12824 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12825 return true; 12826 12827 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 12828 12829 // C++ P0722: 12830 // Within a class C, the first parameter of a destroying operator delete 12831 // shall be of type C *. The first parameter of any other deallocation 12832 // function shall be of type void *. 12833 CanQualType ExpectedFirstParamType = 12834 MD && MD->isDestroyingOperatorDelete() 12835 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 12836 SemaRef.Context.getRecordType(MD->getParent()))) 12837 : SemaRef.Context.VoidPtrTy; 12838 12839 // C++ [basic.stc.dynamic.deallocation]p2: 12840 // Each deallocation function shall return void 12841 if (CheckOperatorNewDeleteTypes( 12842 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 12843 diag::err_operator_delete_dependent_param_type, 12844 diag::err_operator_delete_param_type)) 12845 return true; 12846 12847 // C++ P0722: 12848 // A destroying operator delete shall be a usual deallocation function. 12849 if (MD && !MD->getParent()->isDependentContext() && 12850 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 12851 SemaRef.Diag(MD->getLocation(), 12852 diag::err_destroying_operator_delete_not_usual); 12853 return true; 12854 } 12855 12856 return false; 12857 } 12858 12859 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12860 /// of this overloaded operator is well-formed. If so, returns false; 12861 /// otherwise, emits appropriate diagnostics and returns true. 12862 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12863 assert(FnDecl && FnDecl->isOverloadedOperator() && 12864 "Expected an overloaded operator declaration"); 12865 12866 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12867 12868 // C++ [over.oper]p5: 12869 // The allocation and deallocation functions, operator new, 12870 // operator new[], operator delete and operator delete[], are 12871 // described completely in 3.7.3. The attributes and restrictions 12872 // found in the rest of this subclause do not apply to them unless 12873 // explicitly stated in 3.7.3. 12874 if (Op == OO_Delete || Op == OO_Array_Delete) 12875 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12876 12877 if (Op == OO_New || Op == OO_Array_New) 12878 return CheckOperatorNewDeclaration(*this, FnDecl); 12879 12880 // C++ [over.oper]p6: 12881 // An operator function shall either be a non-static member 12882 // function or be a non-member function and have at least one 12883 // parameter whose type is a class, a reference to a class, an 12884 // enumeration, or a reference to an enumeration. 12885 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12886 if (MethodDecl->isStatic()) 12887 return Diag(FnDecl->getLocation(), 12888 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12889 } else { 12890 bool ClassOrEnumParam = false; 12891 for (auto Param : FnDecl->parameters()) { 12892 QualType ParamType = Param->getType().getNonReferenceType(); 12893 if (ParamType->isDependentType() || ParamType->isRecordType() || 12894 ParamType->isEnumeralType()) { 12895 ClassOrEnumParam = true; 12896 break; 12897 } 12898 } 12899 12900 if (!ClassOrEnumParam) 12901 return Diag(FnDecl->getLocation(), 12902 diag::err_operator_overload_needs_class_or_enum) 12903 << FnDecl->getDeclName(); 12904 } 12905 12906 // C++ [over.oper]p8: 12907 // An operator function cannot have default arguments (8.3.6), 12908 // except where explicitly stated below. 12909 // 12910 // Only the function-call operator allows default arguments 12911 // (C++ [over.call]p1). 12912 if (Op != OO_Call) { 12913 for (auto Param : FnDecl->parameters()) { 12914 if (Param->hasDefaultArg()) 12915 return Diag(Param->getLocation(), 12916 diag::err_operator_overload_default_arg) 12917 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12918 } 12919 } 12920 12921 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12922 { false, false, false } 12923 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12924 , { Unary, Binary, MemberOnly } 12925 #include "clang/Basic/OperatorKinds.def" 12926 }; 12927 12928 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12929 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12930 bool MustBeMemberOperator = OperatorUses[Op][2]; 12931 12932 // C++ [over.oper]p8: 12933 // [...] Operator functions cannot have more or fewer parameters 12934 // than the number required for the corresponding operator, as 12935 // described in the rest of this subclause. 12936 unsigned NumParams = FnDecl->getNumParams() 12937 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12938 if (Op != OO_Call && 12939 ((NumParams == 1 && !CanBeUnaryOperator) || 12940 (NumParams == 2 && !CanBeBinaryOperator) || 12941 (NumParams < 1) || (NumParams > 2))) { 12942 // We have the wrong number of parameters. 12943 unsigned ErrorKind; 12944 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12945 ErrorKind = 2; // 2 -> unary or binary. 12946 } else if (CanBeUnaryOperator) { 12947 ErrorKind = 0; // 0 -> unary 12948 } else { 12949 assert(CanBeBinaryOperator && 12950 "All non-call overloaded operators are unary or binary!"); 12951 ErrorKind = 1; // 1 -> binary 12952 } 12953 12954 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12955 << FnDecl->getDeclName() << NumParams << ErrorKind; 12956 } 12957 12958 // Overloaded operators other than operator() cannot be variadic. 12959 if (Op != OO_Call && 12960 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12961 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12962 << FnDecl->getDeclName(); 12963 } 12964 12965 // Some operators must be non-static member functions. 12966 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12967 return Diag(FnDecl->getLocation(), 12968 diag::err_operator_overload_must_be_member) 12969 << FnDecl->getDeclName(); 12970 } 12971 12972 // C++ [over.inc]p1: 12973 // The user-defined function called operator++ implements the 12974 // prefix and postfix ++ operator. If this function is a member 12975 // function with no parameters, or a non-member function with one 12976 // parameter of class or enumeration type, it defines the prefix 12977 // increment operator ++ for objects of that type. If the function 12978 // is a member function with one parameter (which shall be of type 12979 // int) or a non-member function with two parameters (the second 12980 // of which shall be of type int), it defines the postfix 12981 // increment operator ++ for objects of that type. 12982 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12983 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12984 QualType ParamType = LastParam->getType(); 12985 12986 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12987 !ParamType->isDependentType()) 12988 return Diag(LastParam->getLocation(), 12989 diag::err_operator_overload_post_incdec_must_be_int) 12990 << LastParam->getType() << (Op == OO_MinusMinus); 12991 } 12992 12993 return false; 12994 } 12995 12996 static bool 12997 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12998 FunctionTemplateDecl *TpDecl) { 12999 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13000 13001 // Must have one or two template parameters. 13002 if (TemplateParams->size() == 1) { 13003 NonTypeTemplateParmDecl *PmDecl = 13004 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13005 13006 // The template parameter must be a char parameter pack. 13007 if (PmDecl && PmDecl->isTemplateParameterPack() && 13008 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13009 return false; 13010 13011 } else if (TemplateParams->size() == 2) { 13012 TemplateTypeParmDecl *PmType = 13013 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13014 NonTypeTemplateParmDecl *PmArgs = 13015 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13016 13017 // The second template parameter must be a parameter pack with the 13018 // first template parameter as its type. 13019 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13020 PmArgs->isTemplateParameterPack()) { 13021 const TemplateTypeParmType *TArgs = 13022 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13023 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13024 TArgs->getIndex() == PmType->getIndex()) { 13025 if (!SemaRef.inTemplateInstantiation()) 13026 SemaRef.Diag(TpDecl->getLocation(), 13027 diag::ext_string_literal_operator_template); 13028 return false; 13029 } 13030 } 13031 } 13032 13033 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13034 diag::err_literal_operator_template) 13035 << TpDecl->getTemplateParameters()->getSourceRange(); 13036 return true; 13037 } 13038 13039 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13040 /// of this literal operator function is well-formed. If so, returns 13041 /// false; otherwise, emits appropriate diagnostics and returns true. 13042 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13043 if (isa<CXXMethodDecl>(FnDecl)) { 13044 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13045 << FnDecl->getDeclName(); 13046 return true; 13047 } 13048 13049 if (FnDecl->isExternC()) { 13050 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13051 if (const LinkageSpecDecl *LSD = 13052 FnDecl->getDeclContext()->getExternCContext()) 13053 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13054 return true; 13055 } 13056 13057 // This might be the definition of a literal operator template. 13058 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13059 13060 // This might be a specialization of a literal operator template. 13061 if (!TpDecl) 13062 TpDecl = FnDecl->getPrimaryTemplate(); 13063 13064 // template <char...> type operator "" name() and 13065 // template <class T, T...> type operator "" name() are the only valid 13066 // template signatures, and the only valid signatures with no parameters. 13067 if (TpDecl) { 13068 if (FnDecl->param_size() != 0) { 13069 Diag(FnDecl->getLocation(), 13070 diag::err_literal_operator_template_with_params); 13071 return true; 13072 } 13073 13074 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13075 return true; 13076 13077 } else if (FnDecl->param_size() == 1) { 13078 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13079 13080 QualType ParamType = Param->getType().getUnqualifiedType(); 13081 13082 // Only unsigned long long int, long double, any character type, and const 13083 // char * are allowed as the only parameters. 13084 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13085 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13086 Context.hasSameType(ParamType, Context.CharTy) || 13087 Context.hasSameType(ParamType, Context.WideCharTy) || 13088 Context.hasSameType(ParamType, Context.Char16Ty) || 13089 Context.hasSameType(ParamType, Context.Char32Ty)) { 13090 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13091 QualType InnerType = Ptr->getPointeeType(); 13092 13093 // Pointer parameter must be a const char *. 13094 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13095 Context.CharTy) && 13096 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13097 Diag(Param->getSourceRange().getBegin(), 13098 diag::err_literal_operator_param) 13099 << ParamType << "'const char *'" << Param->getSourceRange(); 13100 return true; 13101 } 13102 13103 } else if (ParamType->isRealFloatingType()) { 13104 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13105 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13106 return true; 13107 13108 } else if (ParamType->isIntegerType()) { 13109 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13110 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13111 return true; 13112 13113 } else { 13114 Diag(Param->getSourceRange().getBegin(), 13115 diag::err_literal_operator_invalid_param) 13116 << ParamType << Param->getSourceRange(); 13117 return true; 13118 } 13119 13120 } else if (FnDecl->param_size() == 2) { 13121 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13122 13123 // First, verify that the first parameter is correct. 13124 13125 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13126 13127 // Two parameter function must have a pointer to const as a 13128 // first parameter; let's strip those qualifiers. 13129 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13130 13131 if (!PT) { 13132 Diag((*Param)->getSourceRange().getBegin(), 13133 diag::err_literal_operator_param) 13134 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13135 return true; 13136 } 13137 13138 QualType PointeeType = PT->getPointeeType(); 13139 // First parameter must be const 13140 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13141 Diag((*Param)->getSourceRange().getBegin(), 13142 diag::err_literal_operator_param) 13143 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13144 return true; 13145 } 13146 13147 QualType InnerType = PointeeType.getUnqualifiedType(); 13148 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 13149 // are allowed as the first parameter to a two-parameter function 13150 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13151 Context.hasSameType(InnerType, Context.WideCharTy) || 13152 Context.hasSameType(InnerType, Context.Char16Ty) || 13153 Context.hasSameType(InnerType, Context.Char32Ty))) { 13154 Diag((*Param)->getSourceRange().getBegin(), 13155 diag::err_literal_operator_param) 13156 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13157 return true; 13158 } 13159 13160 // Move on to the second and final parameter. 13161 ++Param; 13162 13163 // The second parameter must be a std::size_t. 13164 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13165 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13166 Diag((*Param)->getSourceRange().getBegin(), 13167 diag::err_literal_operator_param) 13168 << SecondParamType << Context.getSizeType() 13169 << (*Param)->getSourceRange(); 13170 return true; 13171 } 13172 } else { 13173 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13174 return true; 13175 } 13176 13177 // Parameters are good. 13178 13179 // A parameter-declaration-clause containing a default argument is not 13180 // equivalent to any of the permitted forms. 13181 for (auto Param : FnDecl->parameters()) { 13182 if (Param->hasDefaultArg()) { 13183 Diag(Param->getDefaultArgRange().getBegin(), 13184 diag::err_literal_operator_default_argument) 13185 << Param->getDefaultArgRange(); 13186 break; 13187 } 13188 } 13189 13190 StringRef LiteralName 13191 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13192 if (LiteralName[0] != '_' && 13193 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13194 // C++11 [usrlit.suffix]p1: 13195 // Literal suffix identifiers that do not start with an underscore 13196 // are reserved for future standardization. 13197 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13198 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13199 } 13200 13201 return false; 13202 } 13203 13204 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13205 /// linkage specification, including the language and (if present) 13206 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13207 /// language string literal. LBraceLoc, if valid, provides the location of 13208 /// the '{' brace. Otherwise, this linkage specification does not 13209 /// have any braces. 13210 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13211 Expr *LangStr, 13212 SourceLocation LBraceLoc) { 13213 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13214 if (!Lit->isAscii()) { 13215 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13216 << LangStr->getSourceRange(); 13217 return nullptr; 13218 } 13219 13220 StringRef Lang = Lit->getString(); 13221 LinkageSpecDecl::LanguageIDs Language; 13222 if (Lang == "C") 13223 Language = LinkageSpecDecl::lang_c; 13224 else if (Lang == "C++") 13225 Language = LinkageSpecDecl::lang_cxx; 13226 else { 13227 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13228 << LangStr->getSourceRange(); 13229 return nullptr; 13230 } 13231 13232 // FIXME: Add all the various semantics of linkage specifications 13233 13234 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13235 LangStr->getExprLoc(), Language, 13236 LBraceLoc.isValid()); 13237 CurContext->addDecl(D); 13238 PushDeclContext(S, D); 13239 return D; 13240 } 13241 13242 /// ActOnFinishLinkageSpecification - Complete the definition of 13243 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13244 /// valid, it's the position of the closing '}' brace in a linkage 13245 /// specification that uses braces. 13246 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13247 Decl *LinkageSpec, 13248 SourceLocation RBraceLoc) { 13249 if (RBraceLoc.isValid()) { 13250 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13251 LSDecl->setRBraceLoc(RBraceLoc); 13252 } 13253 PopDeclContext(); 13254 return LinkageSpec; 13255 } 13256 13257 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13258 AttributeList *AttrList, 13259 SourceLocation SemiLoc) { 13260 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13261 // Attribute declarations appertain to empty declaration so we handle 13262 // them here. 13263 if (AttrList) 13264 ProcessDeclAttributeList(S, ED, AttrList); 13265 13266 CurContext->addDecl(ED); 13267 return ED; 13268 } 13269 13270 /// \brief Perform semantic analysis for the variable declaration that 13271 /// occurs within a C++ catch clause, returning the newly-created 13272 /// variable. 13273 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13274 TypeSourceInfo *TInfo, 13275 SourceLocation StartLoc, 13276 SourceLocation Loc, 13277 IdentifierInfo *Name) { 13278 bool Invalid = false; 13279 QualType ExDeclType = TInfo->getType(); 13280 13281 // Arrays and functions decay. 13282 if (ExDeclType->isArrayType()) 13283 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13284 else if (ExDeclType->isFunctionType()) 13285 ExDeclType = Context.getPointerType(ExDeclType); 13286 13287 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13288 // The exception-declaration shall not denote a pointer or reference to an 13289 // incomplete type, other than [cv] void*. 13290 // N2844 forbids rvalue references. 13291 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13292 Diag(Loc, diag::err_catch_rvalue_ref); 13293 Invalid = true; 13294 } 13295 13296 if (ExDeclType->isVariablyModifiedType()) { 13297 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13298 Invalid = true; 13299 } 13300 13301 QualType BaseType = ExDeclType; 13302 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13303 unsigned DK = diag::err_catch_incomplete; 13304 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13305 BaseType = Ptr->getPointeeType(); 13306 Mode = 1; 13307 DK = diag::err_catch_incomplete_ptr; 13308 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13309 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13310 BaseType = Ref->getPointeeType(); 13311 Mode = 2; 13312 DK = diag::err_catch_incomplete_ref; 13313 } 13314 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13315 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13316 Invalid = true; 13317 13318 if (!Invalid && !ExDeclType->isDependentType() && 13319 RequireNonAbstractType(Loc, ExDeclType, 13320 diag::err_abstract_type_in_decl, 13321 AbstractVariableType)) 13322 Invalid = true; 13323 13324 // Only the non-fragile NeXT runtime currently supports C++ catches 13325 // of ObjC types, and no runtime supports catching ObjC types by value. 13326 if (!Invalid && getLangOpts().ObjC1) { 13327 QualType T = ExDeclType; 13328 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13329 T = RT->getPointeeType(); 13330 13331 if (T->isObjCObjectType()) { 13332 Diag(Loc, diag::err_objc_object_catch); 13333 Invalid = true; 13334 } else if (T->isObjCObjectPointerType()) { 13335 // FIXME: should this be a test for macosx-fragile specifically? 13336 if (getLangOpts().ObjCRuntime.isFragile()) 13337 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13338 } 13339 } 13340 13341 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13342 ExDeclType, TInfo, SC_None); 13343 ExDecl->setExceptionVariable(true); 13344 13345 // In ARC, infer 'retaining' for variables of retainable type. 13346 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13347 Invalid = true; 13348 13349 if (!Invalid && !ExDeclType->isDependentType()) { 13350 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13351 // Insulate this from anything else we might currently be parsing. 13352 EnterExpressionEvaluationContext scope( 13353 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13354 13355 // C++ [except.handle]p16: 13356 // The object declared in an exception-declaration or, if the 13357 // exception-declaration does not specify a name, a temporary (12.2) is 13358 // copy-initialized (8.5) from the exception object. [...] 13359 // The object is destroyed when the handler exits, after the destruction 13360 // of any automatic objects initialized within the handler. 13361 // 13362 // We just pretend to initialize the object with itself, then make sure 13363 // it can be destroyed later. 13364 QualType initType = Context.getExceptionObjectType(ExDeclType); 13365 13366 InitializedEntity entity = 13367 InitializedEntity::InitializeVariable(ExDecl); 13368 InitializationKind initKind = 13369 InitializationKind::CreateCopy(Loc, SourceLocation()); 13370 13371 Expr *opaqueValue = 13372 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13373 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13374 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13375 if (result.isInvalid()) 13376 Invalid = true; 13377 else { 13378 // If the constructor used was non-trivial, set this as the 13379 // "initializer". 13380 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13381 if (!construct->getConstructor()->isTrivial()) { 13382 Expr *init = MaybeCreateExprWithCleanups(construct); 13383 ExDecl->setInit(init); 13384 } 13385 13386 // And make sure it's destructable. 13387 FinalizeVarWithDestructor(ExDecl, recordType); 13388 } 13389 } 13390 } 13391 13392 if (Invalid) 13393 ExDecl->setInvalidDecl(); 13394 13395 return ExDecl; 13396 } 13397 13398 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13399 /// handler. 13400 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13401 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13402 bool Invalid = D.isInvalidType(); 13403 13404 // Check for unexpanded parameter packs. 13405 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13406 UPPC_ExceptionType)) { 13407 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13408 D.getIdentifierLoc()); 13409 Invalid = true; 13410 } 13411 13412 IdentifierInfo *II = D.getIdentifier(); 13413 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13414 LookupOrdinaryName, 13415 ForVisibleRedeclaration)) { 13416 // The scope should be freshly made just for us. There is just no way 13417 // it contains any previous declaration, except for function parameters in 13418 // a function-try-block's catch statement. 13419 assert(!S->isDeclScope(PrevDecl)); 13420 if (isDeclInScope(PrevDecl, CurContext, S)) { 13421 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13422 << D.getIdentifier(); 13423 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13424 Invalid = true; 13425 } else if (PrevDecl->isTemplateParameter()) 13426 // Maybe we will complain about the shadowed template parameter. 13427 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13428 } 13429 13430 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13431 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13432 << D.getCXXScopeSpec().getRange(); 13433 Invalid = true; 13434 } 13435 13436 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13437 D.getLocStart(), 13438 D.getIdentifierLoc(), 13439 D.getIdentifier()); 13440 if (Invalid) 13441 ExDecl->setInvalidDecl(); 13442 13443 // Add the exception declaration into this scope. 13444 if (II) 13445 PushOnScopeChains(ExDecl, S); 13446 else 13447 CurContext->addDecl(ExDecl); 13448 13449 ProcessDeclAttributes(S, ExDecl, D); 13450 return ExDecl; 13451 } 13452 13453 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13454 Expr *AssertExpr, 13455 Expr *AssertMessageExpr, 13456 SourceLocation RParenLoc) { 13457 StringLiteral *AssertMessage = 13458 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13459 13460 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13461 return nullptr; 13462 13463 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13464 AssertMessage, RParenLoc, false); 13465 } 13466 13467 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13468 Expr *AssertExpr, 13469 StringLiteral *AssertMessage, 13470 SourceLocation RParenLoc, 13471 bool Failed) { 13472 assert(AssertExpr != nullptr && "Expected non-null condition"); 13473 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13474 !Failed) { 13475 // In a static_assert-declaration, the constant-expression shall be a 13476 // constant expression that can be contextually converted to bool. 13477 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13478 if (Converted.isInvalid()) 13479 Failed = true; 13480 13481 llvm::APSInt Cond; 13482 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13483 diag::err_static_assert_expression_is_not_constant, 13484 /*AllowFold=*/false).isInvalid()) 13485 Failed = true; 13486 13487 if (!Failed && !Cond) { 13488 SmallString<256> MsgBuffer; 13489 llvm::raw_svector_ostream Msg(MsgBuffer); 13490 if (AssertMessage) 13491 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13492 13493 Expr *InnerCond = nullptr; 13494 std::string InnerCondDescription; 13495 std::tie(InnerCond, InnerCondDescription) = 13496 findFailedBooleanCondition(Converted.get(), 13497 /*AllowTopLevelCond=*/false); 13498 if (InnerCond) { 13499 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13500 << InnerCondDescription << !AssertMessage 13501 << Msg.str() << InnerCond->getSourceRange(); 13502 } else { 13503 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13504 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13505 } 13506 Failed = true; 13507 } 13508 } 13509 13510 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13511 /*DiscardedValue*/false, 13512 /*IsConstexpr*/true); 13513 if (FullAssertExpr.isInvalid()) 13514 Failed = true; 13515 else 13516 AssertExpr = FullAssertExpr.get(); 13517 13518 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13519 AssertExpr, AssertMessage, RParenLoc, 13520 Failed); 13521 13522 CurContext->addDecl(Decl); 13523 return Decl; 13524 } 13525 13526 /// \brief Perform semantic analysis of the given friend type declaration. 13527 /// 13528 /// \returns A friend declaration that. 13529 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13530 SourceLocation FriendLoc, 13531 TypeSourceInfo *TSInfo) { 13532 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13533 13534 QualType T = TSInfo->getType(); 13535 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13536 13537 // C++03 [class.friend]p2: 13538 // An elaborated-type-specifier shall be used in a friend declaration 13539 // for a class.* 13540 // 13541 // * The class-key of the elaborated-type-specifier is required. 13542 if (!CodeSynthesisContexts.empty()) { 13543 // Do not complain about the form of friend template types during any kind 13544 // of code synthesis. For template instantiation, we will have complained 13545 // when the template was defined. 13546 } else { 13547 if (!T->isElaboratedTypeSpecifier()) { 13548 // If we evaluated the type to a record type, suggest putting 13549 // a tag in front. 13550 if (const RecordType *RT = T->getAs<RecordType>()) { 13551 RecordDecl *RD = RT->getDecl(); 13552 13553 SmallString<16> InsertionText(" "); 13554 InsertionText += RD->getKindName(); 13555 13556 Diag(TypeRange.getBegin(), 13557 getLangOpts().CPlusPlus11 ? 13558 diag::warn_cxx98_compat_unelaborated_friend_type : 13559 diag::ext_unelaborated_friend_type) 13560 << (unsigned) RD->getTagKind() 13561 << T 13562 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13563 InsertionText); 13564 } else { 13565 Diag(FriendLoc, 13566 getLangOpts().CPlusPlus11 ? 13567 diag::warn_cxx98_compat_nonclass_type_friend : 13568 diag::ext_nonclass_type_friend) 13569 << T 13570 << TypeRange; 13571 } 13572 } else if (T->getAs<EnumType>()) { 13573 Diag(FriendLoc, 13574 getLangOpts().CPlusPlus11 ? 13575 diag::warn_cxx98_compat_enum_friend : 13576 diag::ext_enum_friend) 13577 << T 13578 << TypeRange; 13579 } 13580 13581 // C++11 [class.friend]p3: 13582 // A friend declaration that does not declare a function shall have one 13583 // of the following forms: 13584 // friend elaborated-type-specifier ; 13585 // friend simple-type-specifier ; 13586 // friend typename-specifier ; 13587 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13588 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13589 } 13590 13591 // If the type specifier in a friend declaration designates a (possibly 13592 // cv-qualified) class type, that class is declared as a friend; otherwise, 13593 // the friend declaration is ignored. 13594 return FriendDecl::Create(Context, CurContext, 13595 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13596 FriendLoc); 13597 } 13598 13599 /// Handle a friend tag declaration where the scope specifier was 13600 /// templated. 13601 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13602 unsigned TagSpec, SourceLocation TagLoc, 13603 CXXScopeSpec &SS, 13604 IdentifierInfo *Name, 13605 SourceLocation NameLoc, 13606 AttributeList *Attr, 13607 MultiTemplateParamsArg TempParamLists) { 13608 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13609 13610 bool IsMemberSpecialization = false; 13611 bool Invalid = false; 13612 13613 if (TemplateParameterList *TemplateParams = 13614 MatchTemplateParametersToScopeSpecifier( 13615 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13616 IsMemberSpecialization, Invalid)) { 13617 if (TemplateParams->size() > 0) { 13618 // This is a declaration of a class template. 13619 if (Invalid) 13620 return nullptr; 13621 13622 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13623 NameLoc, Attr, TemplateParams, AS_public, 13624 /*ModulePrivateLoc=*/SourceLocation(), 13625 FriendLoc, TempParamLists.size() - 1, 13626 TempParamLists.data()).get(); 13627 } else { 13628 // The "template<>" header is extraneous. 13629 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13630 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13631 IsMemberSpecialization = true; 13632 } 13633 } 13634 13635 if (Invalid) return nullptr; 13636 13637 bool isAllExplicitSpecializations = true; 13638 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13639 if (TempParamLists[I]->size()) { 13640 isAllExplicitSpecializations = false; 13641 break; 13642 } 13643 } 13644 13645 // FIXME: don't ignore attributes. 13646 13647 // If it's explicit specializations all the way down, just forget 13648 // about the template header and build an appropriate non-templated 13649 // friend. TODO: for source fidelity, remember the headers. 13650 if (isAllExplicitSpecializations) { 13651 if (SS.isEmpty()) { 13652 bool Owned = false; 13653 bool IsDependent = false; 13654 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13655 Attr, AS_public, 13656 /*ModulePrivateLoc=*/SourceLocation(), 13657 MultiTemplateParamsArg(), Owned, IsDependent, 13658 /*ScopedEnumKWLoc=*/SourceLocation(), 13659 /*ScopedEnumUsesClassTag=*/false, 13660 /*UnderlyingType=*/TypeResult(), 13661 /*IsTypeSpecifier=*/false, 13662 /*IsTemplateParamOrArg=*/false); 13663 } 13664 13665 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13666 ElaboratedTypeKeyword Keyword 13667 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13668 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13669 *Name, NameLoc); 13670 if (T.isNull()) 13671 return nullptr; 13672 13673 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13674 if (isa<DependentNameType>(T)) { 13675 DependentNameTypeLoc TL = 13676 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13677 TL.setElaboratedKeywordLoc(TagLoc); 13678 TL.setQualifierLoc(QualifierLoc); 13679 TL.setNameLoc(NameLoc); 13680 } else { 13681 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13682 TL.setElaboratedKeywordLoc(TagLoc); 13683 TL.setQualifierLoc(QualifierLoc); 13684 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13685 } 13686 13687 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13688 TSI, FriendLoc, TempParamLists); 13689 Friend->setAccess(AS_public); 13690 CurContext->addDecl(Friend); 13691 return Friend; 13692 } 13693 13694 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13695 13696 13697 13698 // Handle the case of a templated-scope friend class. e.g. 13699 // template <class T> class A<T>::B; 13700 // FIXME: we don't support these right now. 13701 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13702 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13703 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13704 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13705 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13706 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13707 TL.setElaboratedKeywordLoc(TagLoc); 13708 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13709 TL.setNameLoc(NameLoc); 13710 13711 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13712 TSI, FriendLoc, TempParamLists); 13713 Friend->setAccess(AS_public); 13714 Friend->setUnsupportedFriend(true); 13715 CurContext->addDecl(Friend); 13716 return Friend; 13717 } 13718 13719 13720 /// Handle a friend type declaration. This works in tandem with 13721 /// ActOnTag. 13722 /// 13723 /// Notes on friend class templates: 13724 /// 13725 /// We generally treat friend class declarations as if they were 13726 /// declaring a class. So, for example, the elaborated type specifier 13727 /// in a friend declaration is required to obey the restrictions of a 13728 /// class-head (i.e. no typedefs in the scope chain), template 13729 /// parameters are required to match up with simple template-ids, &c. 13730 /// However, unlike when declaring a template specialization, it's 13731 /// okay to refer to a template specialization without an empty 13732 /// template parameter declaration, e.g. 13733 /// friend class A<T>::B<unsigned>; 13734 /// We permit this as a special case; if there are any template 13735 /// parameters present at all, require proper matching, i.e. 13736 /// template <> template \<class T> friend class A<int>::B; 13737 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13738 MultiTemplateParamsArg TempParams) { 13739 SourceLocation Loc = DS.getLocStart(); 13740 13741 assert(DS.isFriendSpecified()); 13742 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13743 13744 // Try to convert the decl specifier to a type. This works for 13745 // friend templates because ActOnTag never produces a ClassTemplateDecl 13746 // for a TUK_Friend. 13747 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 13748 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13749 QualType T = TSI->getType(); 13750 if (TheDeclarator.isInvalidType()) 13751 return nullptr; 13752 13753 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13754 return nullptr; 13755 13756 // This is definitely an error in C++98. It's probably meant to 13757 // be forbidden in C++0x, too, but the specification is just 13758 // poorly written. 13759 // 13760 // The problem is with declarations like the following: 13761 // template <T> friend A<T>::foo; 13762 // where deciding whether a class C is a friend or not now hinges 13763 // on whether there exists an instantiation of A that causes 13764 // 'foo' to equal C. There are restrictions on class-heads 13765 // (which we declare (by fiat) elaborated friend declarations to 13766 // be) that makes this tractable. 13767 // 13768 // FIXME: handle "template <> friend class A<T>;", which 13769 // is possibly well-formed? Who even knows? 13770 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13771 Diag(Loc, diag::err_tagless_friend_type_template) 13772 << DS.getSourceRange(); 13773 return nullptr; 13774 } 13775 13776 // C++98 [class.friend]p1: A friend of a class is a function 13777 // or class that is not a member of the class . . . 13778 // This is fixed in DR77, which just barely didn't make the C++03 13779 // deadline. It's also a very silly restriction that seriously 13780 // affects inner classes and which nobody else seems to implement; 13781 // thus we never diagnose it, not even in -pedantic. 13782 // 13783 // But note that we could warn about it: it's always useless to 13784 // friend one of your own members (it's not, however, worthless to 13785 // friend a member of an arbitrary specialization of your template). 13786 13787 Decl *D; 13788 if (!TempParams.empty()) 13789 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13790 TempParams, 13791 TSI, 13792 DS.getFriendSpecLoc()); 13793 else 13794 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13795 13796 if (!D) 13797 return nullptr; 13798 13799 D->setAccess(AS_public); 13800 CurContext->addDecl(D); 13801 13802 return D; 13803 } 13804 13805 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13806 MultiTemplateParamsArg TemplateParams) { 13807 const DeclSpec &DS = D.getDeclSpec(); 13808 13809 assert(DS.isFriendSpecified()); 13810 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13811 13812 SourceLocation Loc = D.getIdentifierLoc(); 13813 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13814 13815 // C++ [class.friend]p1 13816 // A friend of a class is a function or class.... 13817 // Note that this sees through typedefs, which is intended. 13818 // It *doesn't* see through dependent types, which is correct 13819 // according to [temp.arg.type]p3: 13820 // If a declaration acquires a function type through a 13821 // type dependent on a template-parameter and this causes 13822 // a declaration that does not use the syntactic form of a 13823 // function declarator to have a function type, the program 13824 // is ill-formed. 13825 if (!TInfo->getType()->isFunctionType()) { 13826 Diag(Loc, diag::err_unexpected_friend); 13827 13828 // It might be worthwhile to try to recover by creating an 13829 // appropriate declaration. 13830 return nullptr; 13831 } 13832 13833 // C++ [namespace.memdef]p3 13834 // - If a friend declaration in a non-local class first declares a 13835 // class or function, the friend class or function is a member 13836 // of the innermost enclosing namespace. 13837 // - The name of the friend is not found by simple name lookup 13838 // until a matching declaration is provided in that namespace 13839 // scope (either before or after the class declaration granting 13840 // friendship). 13841 // - If a friend function is called, its name may be found by the 13842 // name lookup that considers functions from namespaces and 13843 // classes associated with the types of the function arguments. 13844 // - When looking for a prior declaration of a class or a function 13845 // declared as a friend, scopes outside the innermost enclosing 13846 // namespace scope are not considered. 13847 13848 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13849 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13850 DeclarationName Name = NameInfo.getName(); 13851 assert(Name); 13852 13853 // Check for unexpanded parameter packs. 13854 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13855 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13856 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13857 return nullptr; 13858 13859 // The context we found the declaration in, or in which we should 13860 // create the declaration. 13861 DeclContext *DC; 13862 Scope *DCScope = S; 13863 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13864 ForExternalRedeclaration); 13865 13866 // There are five cases here. 13867 // - There's no scope specifier and we're in a local class. Only look 13868 // for functions declared in the immediately-enclosing block scope. 13869 // We recover from invalid scope qualifiers as if they just weren't there. 13870 FunctionDecl *FunctionContainingLocalClass = nullptr; 13871 if ((SS.isInvalid() || !SS.isSet()) && 13872 (FunctionContainingLocalClass = 13873 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13874 // C++11 [class.friend]p11: 13875 // If a friend declaration appears in a local class and the name 13876 // specified is an unqualified name, a prior declaration is 13877 // looked up without considering scopes that are outside the 13878 // innermost enclosing non-class scope. For a friend function 13879 // declaration, if there is no prior declaration, the program is 13880 // ill-formed. 13881 13882 // Find the innermost enclosing non-class scope. This is the block 13883 // scope containing the local class definition (or for a nested class, 13884 // the outer local class). 13885 DCScope = S->getFnParent(); 13886 13887 // Look up the function name in the scope. 13888 Previous.clear(LookupLocalFriendName); 13889 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13890 13891 if (!Previous.empty()) { 13892 // All possible previous declarations must have the same context: 13893 // either they were declared at block scope or they are members of 13894 // one of the enclosing local classes. 13895 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13896 } else { 13897 // This is ill-formed, but provide the context that we would have 13898 // declared the function in, if we were permitted to, for error recovery. 13899 DC = FunctionContainingLocalClass; 13900 } 13901 adjustContextForLocalExternDecl(DC); 13902 13903 // C++ [class.friend]p6: 13904 // A function can be defined in a friend declaration of a class if and 13905 // only if the class is a non-local class (9.8), the function name is 13906 // unqualified, and the function has namespace scope. 13907 if (D.isFunctionDefinition()) { 13908 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13909 } 13910 13911 // - There's no scope specifier, in which case we just go to the 13912 // appropriate scope and look for a function or function template 13913 // there as appropriate. 13914 } else if (SS.isInvalid() || !SS.isSet()) { 13915 // C++11 [namespace.memdef]p3: 13916 // If the name in a friend declaration is neither qualified nor 13917 // a template-id and the declaration is a function or an 13918 // elaborated-type-specifier, the lookup to determine whether 13919 // the entity has been previously declared shall not consider 13920 // any scopes outside the innermost enclosing namespace. 13921 bool isTemplateId = 13922 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 13923 13924 // Find the appropriate context according to the above. 13925 DC = CurContext; 13926 13927 // Skip class contexts. If someone can cite chapter and verse 13928 // for this behavior, that would be nice --- it's what GCC and 13929 // EDG do, and it seems like a reasonable intent, but the spec 13930 // really only says that checks for unqualified existing 13931 // declarations should stop at the nearest enclosing namespace, 13932 // not that they should only consider the nearest enclosing 13933 // namespace. 13934 while (DC->isRecord()) 13935 DC = DC->getParent(); 13936 13937 DeclContext *LookupDC = DC; 13938 while (LookupDC->isTransparentContext()) 13939 LookupDC = LookupDC->getParent(); 13940 13941 while (true) { 13942 LookupQualifiedName(Previous, LookupDC); 13943 13944 if (!Previous.empty()) { 13945 DC = LookupDC; 13946 break; 13947 } 13948 13949 if (isTemplateId) { 13950 if (isa<TranslationUnitDecl>(LookupDC)) break; 13951 } else { 13952 if (LookupDC->isFileContext()) break; 13953 } 13954 LookupDC = LookupDC->getParent(); 13955 } 13956 13957 DCScope = getScopeForDeclContext(S, DC); 13958 13959 // - There's a non-dependent scope specifier, in which case we 13960 // compute it and do a previous lookup there for a function 13961 // or function template. 13962 } else if (!SS.getScopeRep()->isDependent()) { 13963 DC = computeDeclContext(SS); 13964 if (!DC) return nullptr; 13965 13966 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13967 13968 LookupQualifiedName(Previous, DC); 13969 13970 // Ignore things found implicitly in the wrong scope. 13971 // TODO: better diagnostics for this case. Suggesting the right 13972 // qualified scope would be nice... 13973 LookupResult::Filter F = Previous.makeFilter(); 13974 while (F.hasNext()) { 13975 NamedDecl *D = F.next(); 13976 if (!DC->InEnclosingNamespaceSetOf( 13977 D->getDeclContext()->getRedeclContext())) 13978 F.erase(); 13979 } 13980 F.done(); 13981 13982 if (Previous.empty()) { 13983 D.setInvalidType(); 13984 Diag(Loc, diag::err_qualified_friend_not_found) 13985 << Name << TInfo->getType(); 13986 return nullptr; 13987 } 13988 13989 // C++ [class.friend]p1: A friend of a class is a function or 13990 // class that is not a member of the class . . . 13991 if (DC->Equals(CurContext)) 13992 Diag(DS.getFriendSpecLoc(), 13993 getLangOpts().CPlusPlus11 ? 13994 diag::warn_cxx98_compat_friend_is_member : 13995 diag::err_friend_is_member); 13996 13997 if (D.isFunctionDefinition()) { 13998 // C++ [class.friend]p6: 13999 // A function can be defined in a friend declaration of a class if and 14000 // only if the class is a non-local class (9.8), the function name is 14001 // unqualified, and the function has namespace scope. 14002 SemaDiagnosticBuilder DB 14003 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14004 14005 DB << SS.getScopeRep(); 14006 if (DC->isFileContext()) 14007 DB << FixItHint::CreateRemoval(SS.getRange()); 14008 SS.clear(); 14009 } 14010 14011 // - There's a scope specifier that does not match any template 14012 // parameter lists, in which case we use some arbitrary context, 14013 // create a method or method template, and wait for instantiation. 14014 // - There's a scope specifier that does match some template 14015 // parameter lists, which we don't handle right now. 14016 } else { 14017 if (D.isFunctionDefinition()) { 14018 // C++ [class.friend]p6: 14019 // A function can be defined in a friend declaration of a class if and 14020 // only if the class is a non-local class (9.8), the function name is 14021 // unqualified, and the function has namespace scope. 14022 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14023 << SS.getScopeRep(); 14024 } 14025 14026 DC = CurContext; 14027 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14028 } 14029 14030 if (!DC->isRecord()) { 14031 int DiagArg = -1; 14032 switch (D.getName().getKind()) { 14033 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14034 case UnqualifiedIdKind::IK_ConstructorName: 14035 DiagArg = 0; 14036 break; 14037 case UnqualifiedIdKind::IK_DestructorName: 14038 DiagArg = 1; 14039 break; 14040 case UnqualifiedIdKind::IK_ConversionFunctionId: 14041 DiagArg = 2; 14042 break; 14043 case UnqualifiedIdKind::IK_DeductionGuideName: 14044 DiagArg = 3; 14045 break; 14046 case UnqualifiedIdKind::IK_Identifier: 14047 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14048 case UnqualifiedIdKind::IK_LiteralOperatorId: 14049 case UnqualifiedIdKind::IK_OperatorFunctionId: 14050 case UnqualifiedIdKind::IK_TemplateId: 14051 break; 14052 } 14053 // This implies that it has to be an operator or function. 14054 if (DiagArg >= 0) { 14055 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14056 return nullptr; 14057 } 14058 } 14059 14060 // FIXME: This is an egregious hack to cope with cases where the scope stack 14061 // does not contain the declaration context, i.e., in an out-of-line 14062 // definition of a class. 14063 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14064 if (!DCScope) { 14065 FakeDCScope.setEntity(DC); 14066 DCScope = &FakeDCScope; 14067 } 14068 14069 bool AddToScope = true; 14070 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14071 TemplateParams, AddToScope); 14072 if (!ND) return nullptr; 14073 14074 assert(ND->getLexicalDeclContext() == CurContext); 14075 14076 // If we performed typo correction, we might have added a scope specifier 14077 // and changed the decl context. 14078 DC = ND->getDeclContext(); 14079 14080 // Add the function declaration to the appropriate lookup tables, 14081 // adjusting the redeclarations list as necessary. We don't 14082 // want to do this yet if the friending class is dependent. 14083 // 14084 // Also update the scope-based lookup if the target context's 14085 // lookup context is in lexical scope. 14086 if (!CurContext->isDependentContext()) { 14087 DC = DC->getRedeclContext(); 14088 DC->makeDeclVisibleInContext(ND); 14089 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14090 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14091 } 14092 14093 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14094 D.getIdentifierLoc(), ND, 14095 DS.getFriendSpecLoc()); 14096 FrD->setAccess(AS_public); 14097 CurContext->addDecl(FrD); 14098 14099 if (ND->isInvalidDecl()) { 14100 FrD->setInvalidDecl(); 14101 } else { 14102 if (DC->isRecord()) CheckFriendAccess(ND); 14103 14104 FunctionDecl *FD; 14105 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14106 FD = FTD->getTemplatedDecl(); 14107 else 14108 FD = cast<FunctionDecl>(ND); 14109 14110 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14111 // default argument expression, that declaration shall be a definition 14112 // and shall be the only declaration of the function or function 14113 // template in the translation unit. 14114 if (functionDeclHasDefaultArgument(FD)) { 14115 // We can't look at FD->getPreviousDecl() because it may not have been set 14116 // if we're in a dependent context. If the function is known to be a 14117 // redeclaration, we will have narrowed Previous down to the right decl. 14118 if (D.isRedeclaration()) { 14119 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14120 Diag(Previous.getRepresentativeDecl()->getLocation(), 14121 diag::note_previous_declaration); 14122 } else if (!D.isFunctionDefinition()) 14123 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14124 } 14125 14126 // Mark templated-scope function declarations as unsupported. 14127 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14128 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14129 << SS.getScopeRep() << SS.getRange() 14130 << cast<CXXRecordDecl>(CurContext); 14131 FrD->setUnsupportedFriend(true); 14132 } 14133 } 14134 14135 return ND; 14136 } 14137 14138 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14139 AdjustDeclIfTemplate(Dcl); 14140 14141 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14142 if (!Fn) { 14143 Diag(DelLoc, diag::err_deleted_non_function); 14144 return; 14145 } 14146 14147 // Deleted function does not have a body. 14148 Fn->setWillHaveBody(false); 14149 14150 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14151 // Don't consider the implicit declaration we generate for explicit 14152 // specializations. FIXME: Do not generate these implicit declarations. 14153 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14154 Prev->getPreviousDecl()) && 14155 !Prev->isDefined()) { 14156 Diag(DelLoc, diag::err_deleted_decl_not_first); 14157 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14158 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14159 : diag::note_previous_declaration); 14160 } 14161 // If the declaration wasn't the first, we delete the function anyway for 14162 // recovery. 14163 Fn = Fn->getCanonicalDecl(); 14164 } 14165 14166 // dllimport/dllexport cannot be deleted. 14167 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14168 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14169 Fn->setInvalidDecl(); 14170 } 14171 14172 if (Fn->isDeleted()) 14173 return; 14174 14175 // See if we're deleting a function which is already known to override a 14176 // non-deleted virtual function. 14177 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14178 bool IssuedDiagnostic = false; 14179 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14180 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14181 if (!IssuedDiagnostic) { 14182 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14183 IssuedDiagnostic = true; 14184 } 14185 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14186 } 14187 } 14188 // If this function was implicitly deleted because it was defaulted, 14189 // explain why it was deleted. 14190 if (IssuedDiagnostic && MD->isDefaulted()) 14191 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14192 /*Diagnose*/true); 14193 } 14194 14195 // C++11 [basic.start.main]p3: 14196 // A program that defines main as deleted [...] is ill-formed. 14197 if (Fn->isMain()) 14198 Diag(DelLoc, diag::err_deleted_main); 14199 14200 // C++11 [dcl.fct.def.delete]p4: 14201 // A deleted function is implicitly inline. 14202 Fn->setImplicitlyInline(); 14203 Fn->setDeletedAsWritten(); 14204 } 14205 14206 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14207 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14208 14209 if (MD) { 14210 if (MD->getParent()->isDependentType()) { 14211 MD->setDefaulted(); 14212 MD->setExplicitlyDefaulted(); 14213 return; 14214 } 14215 14216 CXXSpecialMember Member = getSpecialMember(MD); 14217 if (Member == CXXInvalid) { 14218 if (!MD->isInvalidDecl()) 14219 Diag(DefaultLoc, diag::err_default_special_members); 14220 return; 14221 } 14222 14223 MD->setDefaulted(); 14224 MD->setExplicitlyDefaulted(); 14225 14226 // Unset that we will have a body for this function. We might not, 14227 // if it turns out to be trivial, and we don't need this marking now 14228 // that we've marked it as defaulted. 14229 MD->setWillHaveBody(false); 14230 14231 // If this definition appears within the record, do the checking when 14232 // the record is complete. 14233 const FunctionDecl *Primary = MD; 14234 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14235 // Ask the template instantiation pattern that actually had the 14236 // '= default' on it. 14237 Primary = Pattern; 14238 14239 // If the method was defaulted on its first declaration, we will have 14240 // already performed the checking in CheckCompletedCXXClass. Such a 14241 // declaration doesn't trigger an implicit definition. 14242 if (Primary->getCanonicalDecl()->isDefaulted()) 14243 return; 14244 14245 CheckExplicitlyDefaultedSpecialMember(MD); 14246 14247 if (!MD->isInvalidDecl()) 14248 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14249 } else { 14250 Diag(DefaultLoc, diag::err_default_special_members); 14251 } 14252 } 14253 14254 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14255 for (Stmt *SubStmt : S->children()) { 14256 if (!SubStmt) 14257 continue; 14258 if (isa<ReturnStmt>(SubStmt)) 14259 Self.Diag(SubStmt->getLocStart(), 14260 diag::err_return_in_constructor_handler); 14261 if (!isa<Expr>(SubStmt)) 14262 SearchForReturnInStmt(Self, SubStmt); 14263 } 14264 } 14265 14266 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14267 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14268 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14269 SearchForReturnInStmt(*this, Handler); 14270 } 14271 } 14272 14273 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14274 const CXXMethodDecl *Old) { 14275 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14276 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14277 14278 if (OldFT->hasExtParameterInfos()) { 14279 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14280 // A parameter of the overriding method should be annotated with noescape 14281 // if the corresponding parameter of the overridden method is annotated. 14282 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14283 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14284 Diag(New->getParamDecl(I)->getLocation(), 14285 diag::warn_overriding_method_missing_noescape); 14286 Diag(Old->getParamDecl(I)->getLocation(), 14287 diag::note_overridden_marked_noescape); 14288 } 14289 } 14290 14291 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14292 14293 // If the calling conventions match, everything is fine 14294 if (NewCC == OldCC) 14295 return false; 14296 14297 // If the calling conventions mismatch because the new function is static, 14298 // suppress the calling convention mismatch error; the error about static 14299 // function override (err_static_overrides_virtual from 14300 // Sema::CheckFunctionDeclaration) is more clear. 14301 if (New->getStorageClass() == SC_Static) 14302 return false; 14303 14304 Diag(New->getLocation(), 14305 diag::err_conflicting_overriding_cc_attributes) 14306 << New->getDeclName() << New->getType() << Old->getType(); 14307 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14308 return true; 14309 } 14310 14311 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14312 const CXXMethodDecl *Old) { 14313 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14314 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14315 14316 if (Context.hasSameType(NewTy, OldTy) || 14317 NewTy->isDependentType() || OldTy->isDependentType()) 14318 return false; 14319 14320 // Check if the return types are covariant 14321 QualType NewClassTy, OldClassTy; 14322 14323 /// Both types must be pointers or references to classes. 14324 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14325 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14326 NewClassTy = NewPT->getPointeeType(); 14327 OldClassTy = OldPT->getPointeeType(); 14328 } 14329 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14330 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14331 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14332 NewClassTy = NewRT->getPointeeType(); 14333 OldClassTy = OldRT->getPointeeType(); 14334 } 14335 } 14336 } 14337 14338 // The return types aren't either both pointers or references to a class type. 14339 if (NewClassTy.isNull()) { 14340 Diag(New->getLocation(), 14341 diag::err_different_return_type_for_overriding_virtual_function) 14342 << New->getDeclName() << NewTy << OldTy 14343 << New->getReturnTypeSourceRange(); 14344 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14345 << Old->getReturnTypeSourceRange(); 14346 14347 return true; 14348 } 14349 14350 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14351 // C++14 [class.virtual]p8: 14352 // If the class type in the covariant return type of D::f differs from 14353 // that of B::f, the class type in the return type of D::f shall be 14354 // complete at the point of declaration of D::f or shall be the class 14355 // type D. 14356 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14357 if (!RT->isBeingDefined() && 14358 RequireCompleteType(New->getLocation(), NewClassTy, 14359 diag::err_covariant_return_incomplete, 14360 New->getDeclName())) 14361 return true; 14362 } 14363 14364 // Check if the new class derives from the old class. 14365 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14366 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14367 << New->getDeclName() << NewTy << OldTy 14368 << New->getReturnTypeSourceRange(); 14369 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14370 << Old->getReturnTypeSourceRange(); 14371 return true; 14372 } 14373 14374 // Check if we the conversion from derived to base is valid. 14375 if (CheckDerivedToBaseConversion( 14376 NewClassTy, OldClassTy, 14377 diag::err_covariant_return_inaccessible_base, 14378 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14379 New->getLocation(), New->getReturnTypeSourceRange(), 14380 New->getDeclName(), nullptr)) { 14381 // FIXME: this note won't trigger for delayed access control 14382 // diagnostics, and it's impossible to get an undelayed error 14383 // here from access control during the original parse because 14384 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14385 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14386 << Old->getReturnTypeSourceRange(); 14387 return true; 14388 } 14389 } 14390 14391 // The qualifiers of the return types must be the same. 14392 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14393 Diag(New->getLocation(), 14394 diag::err_covariant_return_type_different_qualifications) 14395 << New->getDeclName() << NewTy << OldTy 14396 << New->getReturnTypeSourceRange(); 14397 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14398 << Old->getReturnTypeSourceRange(); 14399 return true; 14400 } 14401 14402 14403 // The new class type must have the same or less qualifiers as the old type. 14404 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14405 Diag(New->getLocation(), 14406 diag::err_covariant_return_type_class_type_more_qualified) 14407 << New->getDeclName() << NewTy << OldTy 14408 << New->getReturnTypeSourceRange(); 14409 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14410 << Old->getReturnTypeSourceRange(); 14411 return true; 14412 } 14413 14414 return false; 14415 } 14416 14417 /// \brief Mark the given method pure. 14418 /// 14419 /// \param Method the method to be marked pure. 14420 /// 14421 /// \param InitRange the source range that covers the "0" initializer. 14422 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14423 SourceLocation EndLoc = InitRange.getEnd(); 14424 if (EndLoc.isValid()) 14425 Method->setRangeEnd(EndLoc); 14426 14427 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14428 Method->setPure(); 14429 return false; 14430 } 14431 14432 if (!Method->isInvalidDecl()) 14433 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14434 << Method->getDeclName() << InitRange; 14435 return true; 14436 } 14437 14438 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14439 if (D->getFriendObjectKind()) 14440 Diag(D->getLocation(), diag::err_pure_friend); 14441 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14442 CheckPureMethod(M, ZeroLoc); 14443 else 14444 Diag(D->getLocation(), diag::err_illegal_initializer); 14445 } 14446 14447 /// \brief Determine whether the given declaration is a global variable or 14448 /// static data member. 14449 static bool isNonlocalVariable(const Decl *D) { 14450 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14451 return Var->hasGlobalStorage(); 14452 14453 return false; 14454 } 14455 14456 /// Invoked when we are about to parse an initializer for the declaration 14457 /// 'Dcl'. 14458 /// 14459 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14460 /// static data member of class X, names should be looked up in the scope of 14461 /// class X. If the declaration had a scope specifier, a scope will have 14462 /// been created and passed in for this purpose. Otherwise, S will be null. 14463 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14464 // If there is no declaration, there was an error parsing it. 14465 if (!D || D->isInvalidDecl()) 14466 return; 14467 14468 // We will always have a nested name specifier here, but this declaration 14469 // might not be out of line if the specifier names the current namespace: 14470 // extern int n; 14471 // int ::n = 0; 14472 if (S && D->isOutOfLine()) 14473 EnterDeclaratorContext(S, D->getDeclContext()); 14474 14475 // If we are parsing the initializer for a static data member, push a 14476 // new expression evaluation context that is associated with this static 14477 // data member. 14478 if (isNonlocalVariable(D)) 14479 PushExpressionEvaluationContext( 14480 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14481 } 14482 14483 /// Invoked after we are finished parsing an initializer for the declaration D. 14484 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14485 // If there is no declaration, there was an error parsing it. 14486 if (!D || D->isInvalidDecl()) 14487 return; 14488 14489 if (isNonlocalVariable(D)) 14490 PopExpressionEvaluationContext(); 14491 14492 if (S && D->isOutOfLine()) 14493 ExitDeclaratorContext(S); 14494 } 14495 14496 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14497 /// C++ if/switch/while/for statement. 14498 /// e.g: "if (int x = f()) {...}" 14499 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14500 // C++ 6.4p2: 14501 // The declarator shall not specify a function or an array. 14502 // The type-specifier-seq shall not contain typedef and shall not declare a 14503 // new class or enumeration. 14504 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14505 "Parser allowed 'typedef' as storage class of condition decl."); 14506 14507 Decl *Dcl = ActOnDeclarator(S, D); 14508 if (!Dcl) 14509 return true; 14510 14511 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14512 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14513 << D.getSourceRange(); 14514 return true; 14515 } 14516 14517 return Dcl; 14518 } 14519 14520 void Sema::LoadExternalVTableUses() { 14521 if (!ExternalSource) 14522 return; 14523 14524 SmallVector<ExternalVTableUse, 4> VTables; 14525 ExternalSource->ReadUsedVTables(VTables); 14526 SmallVector<VTableUse, 4> NewUses; 14527 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14528 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14529 = VTablesUsed.find(VTables[I].Record); 14530 // Even if a definition wasn't required before, it may be required now. 14531 if (Pos != VTablesUsed.end()) { 14532 if (!Pos->second && VTables[I].DefinitionRequired) 14533 Pos->second = true; 14534 continue; 14535 } 14536 14537 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14538 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14539 } 14540 14541 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14542 } 14543 14544 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14545 bool DefinitionRequired) { 14546 // Ignore any vtable uses in unevaluated operands or for classes that do 14547 // not have a vtable. 14548 if (!Class->isDynamicClass() || Class->isDependentContext() || 14549 CurContext->isDependentContext() || isUnevaluatedContext()) 14550 return; 14551 14552 // Try to insert this class into the map. 14553 LoadExternalVTableUses(); 14554 Class = Class->getCanonicalDecl(); 14555 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14556 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14557 if (!Pos.second) { 14558 // If we already had an entry, check to see if we are promoting this vtable 14559 // to require a definition. If so, we need to reappend to the VTableUses 14560 // list, since we may have already processed the first entry. 14561 if (DefinitionRequired && !Pos.first->second) { 14562 Pos.first->second = true; 14563 } else { 14564 // Otherwise, we can early exit. 14565 return; 14566 } 14567 } else { 14568 // The Microsoft ABI requires that we perform the destructor body 14569 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14570 // the deleting destructor is emitted with the vtable, not with the 14571 // destructor definition as in the Itanium ABI. 14572 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14573 CXXDestructorDecl *DD = Class->getDestructor(); 14574 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14575 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14576 // If this is an out-of-line declaration, marking it referenced will 14577 // not do anything. Manually call CheckDestructor to look up operator 14578 // delete(). 14579 ContextRAII SavedContext(*this, DD); 14580 CheckDestructor(DD); 14581 } else { 14582 MarkFunctionReferenced(Loc, Class->getDestructor()); 14583 } 14584 } 14585 } 14586 } 14587 14588 // Local classes need to have their virtual members marked 14589 // immediately. For all other classes, we mark their virtual members 14590 // at the end of the translation unit. 14591 if (Class->isLocalClass()) 14592 MarkVirtualMembersReferenced(Loc, Class); 14593 else 14594 VTableUses.push_back(std::make_pair(Class, Loc)); 14595 } 14596 14597 bool Sema::DefineUsedVTables() { 14598 LoadExternalVTableUses(); 14599 if (VTableUses.empty()) 14600 return false; 14601 14602 // Note: The VTableUses vector could grow as a result of marking 14603 // the members of a class as "used", so we check the size each 14604 // time through the loop and prefer indices (which are stable) to 14605 // iterators (which are not). 14606 bool DefinedAnything = false; 14607 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14608 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14609 if (!Class) 14610 continue; 14611 TemplateSpecializationKind ClassTSK = 14612 Class->getTemplateSpecializationKind(); 14613 14614 SourceLocation Loc = VTableUses[I].second; 14615 14616 bool DefineVTable = true; 14617 14618 // If this class has a key function, but that key function is 14619 // defined in another translation unit, we don't need to emit the 14620 // vtable even though we're using it. 14621 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14622 if (KeyFunction && !KeyFunction->hasBody()) { 14623 // The key function is in another translation unit. 14624 DefineVTable = false; 14625 TemplateSpecializationKind TSK = 14626 KeyFunction->getTemplateSpecializationKind(); 14627 assert(TSK != TSK_ExplicitInstantiationDefinition && 14628 TSK != TSK_ImplicitInstantiation && 14629 "Instantiations don't have key functions"); 14630 (void)TSK; 14631 } else if (!KeyFunction) { 14632 // If we have a class with no key function that is the subject 14633 // of an explicit instantiation declaration, suppress the 14634 // vtable; it will live with the explicit instantiation 14635 // definition. 14636 bool IsExplicitInstantiationDeclaration = 14637 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14638 for (auto R : Class->redecls()) { 14639 TemplateSpecializationKind TSK 14640 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14641 if (TSK == TSK_ExplicitInstantiationDeclaration) 14642 IsExplicitInstantiationDeclaration = true; 14643 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14644 IsExplicitInstantiationDeclaration = false; 14645 break; 14646 } 14647 } 14648 14649 if (IsExplicitInstantiationDeclaration) 14650 DefineVTable = false; 14651 } 14652 14653 // The exception specifications for all virtual members may be needed even 14654 // if we are not providing an authoritative form of the vtable in this TU. 14655 // We may choose to emit it available_externally anyway. 14656 if (!DefineVTable) { 14657 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14658 continue; 14659 } 14660 14661 // Mark all of the virtual members of this class as referenced, so 14662 // that we can build a vtable. Then, tell the AST consumer that a 14663 // vtable for this class is required. 14664 DefinedAnything = true; 14665 MarkVirtualMembersReferenced(Loc, Class); 14666 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 14667 if (VTablesUsed[Canonical]) 14668 Consumer.HandleVTable(Class); 14669 14670 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14671 // no key function or the key function is inlined. Don't warn in C++ ABIs 14672 // that lack key functions, since the user won't be able to make one. 14673 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14674 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14675 const FunctionDecl *KeyFunctionDef = nullptr; 14676 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14677 KeyFunctionDef->isInlined())) { 14678 Diag(Class->getLocation(), 14679 ClassTSK == TSK_ExplicitInstantiationDefinition 14680 ? diag::warn_weak_template_vtable 14681 : diag::warn_weak_vtable) 14682 << Class; 14683 } 14684 } 14685 } 14686 VTableUses.clear(); 14687 14688 return DefinedAnything; 14689 } 14690 14691 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14692 const CXXRecordDecl *RD) { 14693 for (const auto *I : RD->methods()) 14694 if (I->isVirtual() && !I->isPure()) 14695 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14696 } 14697 14698 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14699 const CXXRecordDecl *RD) { 14700 // Mark all functions which will appear in RD's vtable as used. 14701 CXXFinalOverriderMap FinalOverriders; 14702 RD->getFinalOverriders(FinalOverriders); 14703 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14704 E = FinalOverriders.end(); 14705 I != E; ++I) { 14706 for (OverridingMethods::const_iterator OI = I->second.begin(), 14707 OE = I->second.end(); 14708 OI != OE; ++OI) { 14709 assert(OI->second.size() > 0 && "no final overrider"); 14710 CXXMethodDecl *Overrider = OI->second.front().Method; 14711 14712 // C++ [basic.def.odr]p2: 14713 // [...] A virtual member function is used if it is not pure. [...] 14714 if (!Overrider->isPure()) 14715 MarkFunctionReferenced(Loc, Overrider); 14716 } 14717 } 14718 14719 // Only classes that have virtual bases need a VTT. 14720 if (RD->getNumVBases() == 0) 14721 return; 14722 14723 for (const auto &I : RD->bases()) { 14724 const CXXRecordDecl *Base = 14725 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14726 if (Base->getNumVBases() == 0) 14727 continue; 14728 MarkVirtualMembersReferenced(Loc, Base); 14729 } 14730 } 14731 14732 /// SetIvarInitializers - This routine builds initialization ASTs for the 14733 /// Objective-C implementation whose ivars need be initialized. 14734 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14735 if (!getLangOpts().CPlusPlus) 14736 return; 14737 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14738 SmallVector<ObjCIvarDecl*, 8> ivars; 14739 CollectIvarsToConstructOrDestruct(OID, ivars); 14740 if (ivars.empty()) 14741 return; 14742 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14743 for (unsigned i = 0; i < ivars.size(); i++) { 14744 FieldDecl *Field = ivars[i]; 14745 if (Field->isInvalidDecl()) 14746 continue; 14747 14748 CXXCtorInitializer *Member; 14749 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14750 InitializationKind InitKind = 14751 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14752 14753 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14754 ExprResult MemberInit = 14755 InitSeq.Perform(*this, InitEntity, InitKind, None); 14756 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14757 // Note, MemberInit could actually come back empty if no initialization 14758 // is required (e.g., because it would call a trivial default constructor) 14759 if (!MemberInit.get() || MemberInit.isInvalid()) 14760 continue; 14761 14762 Member = 14763 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14764 SourceLocation(), 14765 MemberInit.getAs<Expr>(), 14766 SourceLocation()); 14767 AllToInit.push_back(Member); 14768 14769 // Be sure that the destructor is accessible and is marked as referenced. 14770 if (const RecordType *RecordTy = 14771 Context.getBaseElementType(Field->getType()) 14772 ->getAs<RecordType>()) { 14773 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14774 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14775 MarkFunctionReferenced(Field->getLocation(), Destructor); 14776 CheckDestructorAccess(Field->getLocation(), Destructor, 14777 PDiag(diag::err_access_dtor_ivar) 14778 << Context.getBaseElementType(Field->getType())); 14779 } 14780 } 14781 } 14782 ObjCImplementation->setIvarInitializers(Context, 14783 AllToInit.data(), AllToInit.size()); 14784 } 14785 } 14786 14787 static 14788 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14789 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14790 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14791 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14792 Sema &S) { 14793 if (Ctor->isInvalidDecl()) 14794 return; 14795 14796 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14797 14798 // Target may not be determinable yet, for instance if this is a dependent 14799 // call in an uninstantiated template. 14800 if (Target) { 14801 const FunctionDecl *FNTarget = nullptr; 14802 (void)Target->hasBody(FNTarget); 14803 Target = const_cast<CXXConstructorDecl*>( 14804 cast_or_null<CXXConstructorDecl>(FNTarget)); 14805 } 14806 14807 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14808 // Avoid dereferencing a null pointer here. 14809 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14810 14811 if (!Current.insert(Canonical).second) 14812 return; 14813 14814 // We know that beyond here, we aren't chaining into a cycle. 14815 if (!Target || !Target->isDelegatingConstructor() || 14816 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14817 Valid.insert(Current.begin(), Current.end()); 14818 Current.clear(); 14819 // We've hit a cycle. 14820 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14821 Current.count(TCanonical)) { 14822 // If we haven't diagnosed this cycle yet, do so now. 14823 if (!Invalid.count(TCanonical)) { 14824 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14825 diag::warn_delegating_ctor_cycle) 14826 << Ctor; 14827 14828 // Don't add a note for a function delegating directly to itself. 14829 if (TCanonical != Canonical) 14830 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14831 14832 CXXConstructorDecl *C = Target; 14833 while (C->getCanonicalDecl() != Canonical) { 14834 const FunctionDecl *FNTarget = nullptr; 14835 (void)C->getTargetConstructor()->hasBody(FNTarget); 14836 assert(FNTarget && "Ctor cycle through bodiless function"); 14837 14838 C = const_cast<CXXConstructorDecl*>( 14839 cast<CXXConstructorDecl>(FNTarget)); 14840 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14841 } 14842 } 14843 14844 Invalid.insert(Current.begin(), Current.end()); 14845 Current.clear(); 14846 } else { 14847 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14848 } 14849 } 14850 14851 14852 void Sema::CheckDelegatingCtorCycles() { 14853 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14854 14855 for (DelegatingCtorDeclsType::iterator 14856 I = DelegatingCtorDecls.begin(ExternalSource), 14857 E = DelegatingCtorDecls.end(); 14858 I != E; ++I) 14859 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14860 14861 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14862 CE = Invalid.end(); 14863 CI != CE; ++CI) 14864 (*CI)->setInvalidDecl(); 14865 } 14866 14867 namespace { 14868 /// \brief AST visitor that finds references to the 'this' expression. 14869 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14870 Sema &S; 14871 14872 public: 14873 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14874 14875 bool VisitCXXThisExpr(CXXThisExpr *E) { 14876 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14877 << E->isImplicit(); 14878 return false; 14879 } 14880 }; 14881 } 14882 14883 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14884 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14885 if (!TSInfo) 14886 return false; 14887 14888 TypeLoc TL = TSInfo->getTypeLoc(); 14889 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14890 if (!ProtoTL) 14891 return false; 14892 14893 // C++11 [expr.prim.general]p3: 14894 // [The expression this] shall not appear before the optional 14895 // cv-qualifier-seq and it shall not appear within the declaration of a 14896 // static member function (although its type and value category are defined 14897 // within a static member function as they are within a non-static member 14898 // function). [ Note: this is because declaration matching does not occur 14899 // until the complete declarator is known. - end note ] 14900 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14901 FindCXXThisExpr Finder(*this); 14902 14903 // If the return type came after the cv-qualifier-seq, check it now. 14904 if (Proto->hasTrailingReturn() && 14905 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14906 return true; 14907 14908 // Check the exception specification. 14909 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14910 return true; 14911 14912 return checkThisInStaticMemberFunctionAttributes(Method); 14913 } 14914 14915 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14916 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14917 if (!TSInfo) 14918 return false; 14919 14920 TypeLoc TL = TSInfo->getTypeLoc(); 14921 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14922 if (!ProtoTL) 14923 return false; 14924 14925 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14926 FindCXXThisExpr Finder(*this); 14927 14928 switch (Proto->getExceptionSpecType()) { 14929 case EST_Unparsed: 14930 case EST_Uninstantiated: 14931 case EST_Unevaluated: 14932 case EST_BasicNoexcept: 14933 case EST_DynamicNone: 14934 case EST_MSAny: 14935 case EST_None: 14936 break; 14937 14938 case EST_ComputedNoexcept: 14939 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14940 return true; 14941 LLVM_FALLTHROUGH; 14942 14943 case EST_Dynamic: 14944 for (const auto &E : Proto->exceptions()) { 14945 if (!Finder.TraverseType(E)) 14946 return true; 14947 } 14948 break; 14949 } 14950 14951 return false; 14952 } 14953 14954 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14955 FindCXXThisExpr Finder(*this); 14956 14957 // Check attributes. 14958 for (const auto *A : Method->attrs()) { 14959 // FIXME: This should be emitted by tblgen. 14960 Expr *Arg = nullptr; 14961 ArrayRef<Expr *> Args; 14962 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14963 Arg = G->getArg(); 14964 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14965 Arg = G->getArg(); 14966 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14967 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14968 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14969 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14970 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14971 Arg = ETLF->getSuccessValue(); 14972 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14973 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14974 Arg = STLF->getSuccessValue(); 14975 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14976 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14977 Arg = LR->getArg(); 14978 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14979 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14980 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14981 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14982 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14983 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14984 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14985 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14986 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14987 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14988 14989 if (Arg && !Finder.TraverseStmt(Arg)) 14990 return true; 14991 14992 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14993 if (!Finder.TraverseStmt(Args[I])) 14994 return true; 14995 } 14996 } 14997 14998 return false; 14999 } 15000 15001 void Sema::checkExceptionSpecification( 15002 bool IsTopLevel, ExceptionSpecificationType EST, 15003 ArrayRef<ParsedType> DynamicExceptions, 15004 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15005 SmallVectorImpl<QualType> &Exceptions, 15006 FunctionProtoType::ExceptionSpecInfo &ESI) { 15007 Exceptions.clear(); 15008 ESI.Type = EST; 15009 if (EST == EST_Dynamic) { 15010 Exceptions.reserve(DynamicExceptions.size()); 15011 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15012 // FIXME: Preserve type source info. 15013 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15014 15015 if (IsTopLevel) { 15016 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15017 collectUnexpandedParameterPacks(ET, Unexpanded); 15018 if (!Unexpanded.empty()) { 15019 DiagnoseUnexpandedParameterPacks( 15020 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15021 Unexpanded); 15022 continue; 15023 } 15024 } 15025 15026 // Check that the type is valid for an exception spec, and 15027 // drop it if not. 15028 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15029 Exceptions.push_back(ET); 15030 } 15031 ESI.Exceptions = Exceptions; 15032 return; 15033 } 15034 15035 if (EST == EST_ComputedNoexcept) { 15036 // If an error occurred, there's no expression here. 15037 if (NoexceptExpr) { 15038 assert((NoexceptExpr->isTypeDependent() || 15039 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15040 Context.BoolTy) && 15041 "Parser should have made sure that the expression is boolean"); 15042 if (IsTopLevel && NoexceptExpr && 15043 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15044 ESI.Type = EST_BasicNoexcept; 15045 return; 15046 } 15047 15048 if (!NoexceptExpr->isValueDependent()) { 15049 ExprResult Result = VerifyIntegerConstantExpression( 15050 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression, 15051 /*AllowFold*/ false); 15052 if (Result.isInvalid()) { 15053 ESI.Type = EST_BasicNoexcept; 15054 return; 15055 } 15056 NoexceptExpr = Result.get(); 15057 } 15058 ESI.NoexceptExpr = NoexceptExpr; 15059 } 15060 return; 15061 } 15062 } 15063 15064 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15065 ExceptionSpecificationType EST, 15066 SourceRange SpecificationRange, 15067 ArrayRef<ParsedType> DynamicExceptions, 15068 ArrayRef<SourceRange> DynamicExceptionRanges, 15069 Expr *NoexceptExpr) { 15070 if (!MethodD) 15071 return; 15072 15073 // Dig out the method we're referring to. 15074 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15075 MethodD = FunTmpl->getTemplatedDecl(); 15076 15077 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15078 if (!Method) 15079 return; 15080 15081 // Check the exception specification. 15082 llvm::SmallVector<QualType, 4> Exceptions; 15083 FunctionProtoType::ExceptionSpecInfo ESI; 15084 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15085 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15086 ESI); 15087 15088 // Update the exception specification on the function type. 15089 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15090 15091 if (Method->isStatic()) 15092 checkThisInStaticMemberFunctionExceptionSpec(Method); 15093 15094 if (Method->isVirtual()) { 15095 // Check overrides, which we previously had to delay. 15096 for (const CXXMethodDecl *O : Method->overridden_methods()) 15097 CheckOverridingFunctionExceptionSpec(Method, O); 15098 } 15099 } 15100 15101 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15102 /// 15103 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15104 SourceLocation DeclStart, 15105 Declarator &D, Expr *BitWidth, 15106 InClassInitStyle InitStyle, 15107 AccessSpecifier AS, 15108 AttributeList *MSPropertyAttr) { 15109 IdentifierInfo *II = D.getIdentifier(); 15110 if (!II) { 15111 Diag(DeclStart, diag::err_anonymous_property); 15112 return nullptr; 15113 } 15114 SourceLocation Loc = D.getIdentifierLoc(); 15115 15116 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15117 QualType T = TInfo->getType(); 15118 if (getLangOpts().CPlusPlus) { 15119 CheckExtraCXXDefaultArguments(D); 15120 15121 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15122 UPPC_DataMemberType)) { 15123 D.setInvalidType(); 15124 T = Context.IntTy; 15125 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15126 } 15127 } 15128 15129 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15130 15131 if (D.getDeclSpec().isInlineSpecified()) 15132 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15133 << getLangOpts().CPlusPlus17; 15134 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15135 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15136 diag::err_invalid_thread) 15137 << DeclSpec::getSpecifierName(TSCS); 15138 15139 // Check to see if this name was declared as a member previously 15140 NamedDecl *PrevDecl = nullptr; 15141 LookupResult Previous(*this, II, Loc, LookupMemberName, 15142 ForVisibleRedeclaration); 15143 LookupName(Previous, S); 15144 switch (Previous.getResultKind()) { 15145 case LookupResult::Found: 15146 case LookupResult::FoundUnresolvedValue: 15147 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15148 break; 15149 15150 case LookupResult::FoundOverloaded: 15151 PrevDecl = Previous.getRepresentativeDecl(); 15152 break; 15153 15154 case LookupResult::NotFound: 15155 case LookupResult::NotFoundInCurrentInstantiation: 15156 case LookupResult::Ambiguous: 15157 break; 15158 } 15159 15160 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15161 // Maybe we will complain about the shadowed template parameter. 15162 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15163 // Just pretend that we didn't see the previous declaration. 15164 PrevDecl = nullptr; 15165 } 15166 15167 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15168 PrevDecl = nullptr; 15169 15170 SourceLocation TSSL = D.getLocStart(); 15171 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 15172 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15173 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15174 ProcessDeclAttributes(TUScope, NewPD, D); 15175 NewPD->setAccess(AS); 15176 15177 if (NewPD->isInvalidDecl()) 15178 Record->setInvalidDecl(); 15179 15180 if (D.getDeclSpec().isModulePrivateSpecified()) 15181 NewPD->setModulePrivate(); 15182 15183 if (NewPD->isInvalidDecl() && PrevDecl) { 15184 // Don't introduce NewFD into scope; there's already something 15185 // with the same name in the same scope. 15186 } else if (II) { 15187 PushOnScopeChains(NewPD, S); 15188 } else 15189 Record->addDecl(NewPD); 15190 15191 return NewPD; 15192 } 15193