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/ComparisonCategories.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/StringExtras.h" 44 #include <map> 45 #include <set> 46 47 using namespace clang; 48 49 //===----------------------------------------------------------------------===// 50 // CheckDefaultArgumentVisitor 51 //===----------------------------------------------------------------------===// 52 53 namespace { 54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 55 /// the default argument of a parameter to determine whether it 56 /// contains any ill-formed subexpressions. For example, this will 57 /// diagnose the use of local variables or parameters within the 58 /// default argument expression. 59 class CheckDefaultArgumentVisitor 60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 61 Expr *DefaultArg; 62 Sema *S; 63 64 public: 65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 66 : DefaultArg(defarg), S(s) {} 67 68 bool VisitExpr(Expr *Node); 69 bool VisitDeclRefExpr(DeclRefExpr *DRE); 70 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 71 bool VisitLambdaExpr(LambdaExpr *Lambda); 72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 73 }; 74 75 /// VisitExpr - Visit all of the children of this expression. 76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 77 bool IsInvalid = false; 78 for (Stmt *SubStmt : Node->children()) 79 IsInvalid |= Visit(SubStmt); 80 return IsInvalid; 81 } 82 83 /// VisitDeclRefExpr - Visit a reference to a declaration, to 84 /// determine whether this declaration can be used in the default 85 /// argument expression. 86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 87 NamedDecl *Decl = DRE->getDecl(); 88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 89 // C++ [dcl.fct.default]p9 90 // Default arguments are evaluated each time the function is 91 // called. The order of evaluation of function arguments is 92 // unspecified. Consequently, parameters of a function shall not 93 // be used in default argument expressions, even if they are not 94 // evaluated. Parameters of a function declared before a default 95 // argument expression are in scope and can hide namespace and 96 // class member names. 97 return S->Diag(DRE->getLocStart(), 98 diag::err_param_default_argument_references_param) 99 << Param->getDeclName() << DefaultArg->getSourceRange(); 100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 101 // C++ [dcl.fct.default]p7 102 // Local variables shall not be used in default argument 103 // expressions. 104 if (VDecl->isLocalVarDecl()) 105 return S->Diag(DRE->getLocStart(), 106 diag::err_param_default_argument_references_local) 107 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 108 } 109 110 return false; 111 } 112 113 /// VisitCXXThisExpr - Visit a C++ "this" expression. 114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 115 // C++ [dcl.fct.default]p8: 116 // The keyword this shall not be used in a default argument of a 117 // member function. 118 return S->Diag(ThisE->getLocStart(), 119 diag::err_param_default_argument_references_this) 120 << ThisE->getSourceRange(); 121 } 122 123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 124 bool Invalid = false; 125 for (PseudoObjectExpr::semantics_iterator 126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 127 Expr *E = *i; 128 129 // Look through bindings. 130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 131 E = OVE->getSourceExpr(); 132 assert(E && "pseudo-object binding without source expression?"); 133 } 134 135 Invalid |= Visit(E); 136 } 137 return Invalid; 138 } 139 140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 141 // C++11 [expr.lambda.prim]p13: 142 // A lambda-expression appearing in a default argument shall not 143 // implicitly or explicitly capture any entity. 144 if (Lambda->capture_begin() == Lambda->capture_end()) 145 return false; 146 147 return S->Diag(Lambda->getLocStart(), 148 diag::err_lambda_capture_default_arg); 149 } 150 } 151 152 void 153 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 154 const CXXMethodDecl *Method) { 155 // If we have an MSAny spec already, don't bother. 156 if (!Method || ComputedEST == EST_MSAny) 157 return; 158 159 const FunctionProtoType *Proto 160 = Method->getType()->getAs<FunctionProtoType>(); 161 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 162 if (!Proto) 163 return; 164 165 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 166 167 // If we have a throw-all spec at this point, ignore the function. 168 if (ComputedEST == EST_None) 169 return; 170 171 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 172 EST = EST_BasicNoexcept; 173 174 switch (EST) { 175 case EST_Unparsed: 176 case EST_Uninstantiated: 177 case EST_Unevaluated: 178 llvm_unreachable("should not see unresolved exception specs here"); 179 180 // If this function can throw any exceptions, make a note of that. 181 case EST_MSAny: 182 case EST_None: 183 // FIXME: Whichever we see last of MSAny and None determines our result. 184 // We should make a consistent, order-independent choice here. 185 ClearExceptions(); 186 ComputedEST = EST; 187 return; 188 case EST_NoexceptFalse: 189 ClearExceptions(); 190 ComputedEST = EST_None; 191 return; 192 // FIXME: If the call to this decl is using any of its default arguments, we 193 // need to search them for potentially-throwing calls. 194 // If this function has a basic noexcept, it doesn't affect the outcome. 195 case EST_BasicNoexcept: 196 case EST_NoexceptTrue: 197 return; 198 // If we're still at noexcept(true) and there's a throw() callee, 199 // change to that specification. 200 case EST_DynamicNone: 201 if (ComputedEST == EST_BasicNoexcept) 202 ComputedEST = EST_DynamicNone; 203 return; 204 case EST_DependentNoexcept: 205 llvm_unreachable( 206 "should not generate implicit declarations for dependent cases"); 207 case EST_Dynamic: 208 break; 209 } 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // C++11 [dcl.fct.default]p3 322 // A default argument expression [...] shall not be specified for a 323 // parameter pack. 324 if (Param->isParameterPack()) { 325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 326 << DefaultArg->getSourceRange(); 327 return; 328 } 329 330 // Check that the default argument is well-formed 331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 332 if (DefaultArgChecker.Visit(DefaultArg)) { 333 Param->setInvalidDecl(); 334 return; 335 } 336 337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 338 } 339 340 /// ActOnParamUnparsedDefaultArgument - We've seen a default 341 /// argument for a function parameter, but we can't parse it yet 342 /// because we're inside a class definition. Note that this default 343 /// argument will be parsed later. 344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 345 SourceLocation EqualLoc, 346 SourceLocation ArgLoc) { 347 if (!param) 348 return; 349 350 ParmVarDecl *Param = cast<ParmVarDecl>(param); 351 Param->setUnparsedDefaultArg(); 352 UnparsedDefaultArgLocs[Param] = ArgLoc; 353 } 354 355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 356 /// the default argument for the parameter param failed. 357 void Sema::ActOnParamDefaultArgumentError(Decl *param, 358 SourceLocation EqualLoc) { 359 if (!param) 360 return; 361 362 ParmVarDecl *Param = cast<ParmVarDecl>(param); 363 Param->setInvalidDecl(); 364 UnparsedDefaultArgLocs.erase(Param); 365 Param->setDefaultArg(new(Context) 366 OpaqueValueExpr(EqualLoc, 367 Param->getType().getNonReferenceType(), 368 VK_RValue)); 369 } 370 371 /// CheckExtraCXXDefaultArguments - Check for any extra default 372 /// arguments in the declarator, which is not a function declaration 373 /// or definition and therefore is not permitted to have default 374 /// arguments. This routine should be invoked for every declarator 375 /// that is not a function declaration or definition. 376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 377 // C++ [dcl.fct.default]p3 378 // A default argument expression shall be specified only in the 379 // parameter-declaration-clause of a function declaration or in a 380 // template-parameter (14.1). It shall not be specified for a 381 // parameter pack. If it is specified in a 382 // parameter-declaration-clause, it shall not occur within a 383 // declarator or abstract-declarator of a parameter-declaration. 384 bool MightBeFunction = D.isFunctionDeclarationContext(); 385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 386 DeclaratorChunk &chunk = D.getTypeObject(i); 387 if (chunk.Kind == DeclaratorChunk::Function) { 388 if (MightBeFunction) { 389 // This is a function declaration. It can have default arguments, but 390 // keep looking in case its return type is a function type with default 391 // arguments. 392 MightBeFunction = false; 393 continue; 394 } 395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 396 ++argIdx) { 397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 398 if (Param->hasUnparsedDefaultArg()) { 399 std::unique_ptr<CachedTokens> Toks = 400 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 401 SourceRange SR; 402 if (Toks->size() > 1) 403 SR = SourceRange((*Toks)[1].getLocation(), 404 Toks->back().getLocation()); 405 else 406 SR = UnparsedDefaultArgLocs[Param]; 407 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 408 << SR; 409 } else if (Param->getDefaultArg()) { 410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 411 << Param->getDefaultArg()->getSourceRange(); 412 Param->setDefaultArg(nullptr); 413 } 414 } 415 } else if (chunk.Kind != DeclaratorChunk::Paren) { 416 MightBeFunction = false; 417 } 418 } 419 } 420 421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 424 if (!PVD->hasDefaultArg()) 425 return false; 426 if (!PVD->hasInheritedDefaultArg()) 427 return true; 428 } 429 return false; 430 } 431 432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 433 /// function, once we already know that they have the same 434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 435 /// error, false otherwise. 436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 437 Scope *S) { 438 bool Invalid = false; 439 440 // The declaration context corresponding to the scope is the semantic 441 // parent, unless this is a local function declaration, in which case 442 // it is that surrounding function. 443 DeclContext *ScopeDC = New->isLocalExternDecl() 444 ? New->getLexicalDeclContext() 445 : New->getDeclContext(); 446 447 // Find the previous declaration for the purpose of default arguments. 448 FunctionDecl *PrevForDefaultArgs = Old; 449 for (/**/; PrevForDefaultArgs; 450 // Don't bother looking back past the latest decl if this is a local 451 // extern declaration; nothing else could work. 452 PrevForDefaultArgs = New->isLocalExternDecl() 453 ? nullptr 454 : PrevForDefaultArgs->getPreviousDecl()) { 455 // Ignore hidden declarations. 456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 457 continue; 458 459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 460 !New->isCXXClassMember()) { 461 // Ignore default arguments of old decl if they are not in 462 // the same scope and this is not an out-of-line definition of 463 // a member function. 464 continue; 465 } 466 467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 468 // If only one of these is a local function declaration, then they are 469 // declared in different scopes, even though isDeclInScope may think 470 // they're in the same scope. (If both are local, the scope check is 471 // sufficient, and if neither is local, then they are in the same scope.) 472 continue; 473 } 474 475 // We found the right previous declaration. 476 break; 477 } 478 479 // C++ [dcl.fct.default]p4: 480 // For non-template functions, default arguments can be added in 481 // later declarations of a function in the same 482 // scope. Declarations in different scopes have completely 483 // distinct sets of default arguments. That is, declarations in 484 // inner scopes do not acquire default arguments from 485 // declarations in outer scopes, and vice versa. In a given 486 // function declaration, all parameters subsequent to a 487 // parameter with a default argument shall have default 488 // arguments supplied in this or previous declarations. A 489 // default argument shall not be redefined by a later 490 // declaration (not even to the same value). 491 // 492 // C++ [dcl.fct.default]p6: 493 // Except for member functions of class templates, the default arguments 494 // in a member function definition that appears outside of the class 495 // definition are added to the set of default arguments provided by the 496 // member function declaration in the class definition. 497 for (unsigned p = 0, NumParams = PrevForDefaultArgs 498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter unless the new 552 // function is a friend declaration in a template class. In the latter 553 // case the default arguments will be inherited when the friend 554 // declaration will be instantiated. 555 if (New->getFriendObjectKind() == Decl::FOK_None || 556 !New->getLexicalDeclContext()->isDependentContext()) { 557 // It's important to use getInit() here; getDefaultArg() 558 // strips off any top-level ExprWithCleanups. 559 NewParam->setHasInheritedDefaultArg(); 560 if (OldParam->hasUnparsedDefaultArg()) 561 NewParam->setUnparsedDefaultArg(); 562 else if (OldParam->hasUninstantiatedDefaultArg()) 563 NewParam->setUninstantiatedDefaultArg( 564 OldParam->getUninstantiatedDefaultArg()); 565 else 566 NewParam->setDefaultArg(OldParam->getInit()); 567 } 568 } else if (NewParamHasDfl) { 569 if (New->getDescribedFunctionTemplate()) { 570 // Paragraph 4, quoted above, only applies to non-template functions. 571 Diag(NewParam->getLocation(), 572 diag::err_param_default_argument_template_redecl) 573 << NewParam->getDefaultArgRange(); 574 Diag(PrevForDefaultArgs->getLocation(), 575 diag::note_template_prev_declaration) 576 << false; 577 } else if (New->getTemplateSpecializationKind() 578 != TSK_ImplicitInstantiation && 579 New->getTemplateSpecializationKind() != TSK_Undeclared) { 580 // C++ [temp.expr.spec]p21: 581 // Default function arguments shall not be specified in a declaration 582 // or a definition for one of the following explicit specializations: 583 // - the explicit specialization of a function template; 584 // - the explicit specialization of a member function template; 585 // - the explicit specialization of a member function of a class 586 // template where the class template specialization to which the 587 // member function specialization belongs is implicitly 588 // instantiated. 589 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 590 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 591 << New->getDeclName() 592 << NewParam->getDefaultArgRange(); 593 } else if (New->getDeclContext()->isDependentContext()) { 594 // C++ [dcl.fct.default]p6 (DR217): 595 // Default arguments for a member function of a class template shall 596 // be specified on the initial declaration of the member function 597 // within the class template. 598 // 599 // Reading the tea leaves a bit in DR217 and its reference to DR205 600 // leads me to the conclusion that one cannot add default function 601 // arguments for an out-of-line definition of a member function of a 602 // dependent type. 603 int WhichKind = 2; 604 if (CXXRecordDecl *Record 605 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 606 if (Record->getDescribedClassTemplate()) 607 WhichKind = 0; 608 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 609 WhichKind = 1; 610 else 611 WhichKind = 2; 612 } 613 614 Diag(NewParam->getLocation(), 615 diag::err_param_default_argument_member_template_redecl) 616 << WhichKind 617 << NewParam->getDefaultArgRange(); 618 } 619 } 620 } 621 622 // DR1344: If a default argument is added outside a class definition and that 623 // default argument makes the function a special member function, the program 624 // is ill-formed. This can only happen for constructors. 625 if (isa<CXXConstructorDecl>(New) && 626 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 627 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 628 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 629 if (NewSM != OldSM) { 630 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 631 assert(NewParam->hasDefaultArg()); 632 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 633 << NewParam->getDefaultArgRange() << NewSM; 634 Diag(Old->getLocation(), diag::note_previous_declaration); 635 } 636 } 637 638 const FunctionDecl *Def; 639 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 640 // template has a constexpr specifier then all its declarations shall 641 // contain the constexpr specifier. 642 if (New->isConstexpr() != Old->isConstexpr()) { 643 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 644 << New << New->isConstexpr(); 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 Invalid = true; 647 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 648 Old->isDefined(Def) && 649 // If a friend function is inlined but does not have 'inline' 650 // specifier, it is a definition. Do not report attribute conflict 651 // in this case, redefinition will be diagnosed later. 652 (New->isInlineSpecified() || 653 New->getFriendObjectKind() == Decl::FOK_None)) { 654 // C++11 [dcl.fcn.spec]p4: 655 // If the definition of a function appears in a translation unit before its 656 // first declaration as inline, the program is ill-formed. 657 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 658 Diag(Def->getLocation(), diag::note_previous_definition); 659 Invalid = true; 660 } 661 662 // FIXME: It's not clear what should happen if multiple declarations of a 663 // deduction guide have different explicitness. For now at least we simply 664 // reject any case where the explicitness changes. 665 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 666 if (NewGuide && NewGuide->isExplicitSpecified() != 667 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 668 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 669 << NewGuide->isExplicitSpecified(); 670 Diag(Old->getLocation(), diag::note_previous_declaration); 671 } 672 673 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 674 // argument expression, that declaration shall be a definition and shall be 675 // the only declaration of the function or function template in the 676 // translation unit. 677 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 678 functionDeclHasDefaultArgument(Old)) { 679 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 680 Diag(Old->getLocation(), diag::note_previous_declaration); 681 Invalid = true; 682 } 683 684 return Invalid; 685 } 686 687 NamedDecl * 688 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 689 MultiTemplateParamsArg TemplateParamLists) { 690 assert(D.isDecompositionDeclarator()); 691 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 692 693 // The syntax only allows a decomposition declarator as a simple-declaration, 694 // a for-range-declaration, or a condition in Clang, but we parse it in more 695 // cases than that. 696 if (!D.mayHaveDecompositionDeclarator()) { 697 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 698 << Decomp.getSourceRange(); 699 return nullptr; 700 } 701 702 if (!TemplateParamLists.empty()) { 703 // FIXME: There's no rule against this, but there are also no rules that 704 // would actually make it usable, so we reject it for now. 705 Diag(TemplateParamLists.front()->getTemplateLoc(), 706 diag::err_decomp_decl_template); 707 return nullptr; 708 } 709 710 Diag(Decomp.getLSquareLoc(), 711 !getLangOpts().CPlusPlus17 712 ? diag::ext_decomp_decl 713 : D.getContext() == DeclaratorContext::ConditionContext 714 ? diag::ext_decomp_decl_cond 715 : diag::warn_cxx14_compat_decomp_decl) 716 << Decomp.getSourceRange(); 717 718 // The semantic context is always just the current context. 719 DeclContext *const DC = CurContext; 720 721 // C++1z [dcl.dcl]/8: 722 // The decl-specifier-seq shall contain only the type-specifier auto 723 // and cv-qualifiers. 724 auto &DS = D.getDeclSpec(); 725 { 726 SmallVector<StringRef, 8> BadSpecifiers; 727 SmallVector<SourceLocation, 8> BadSpecifierLocs; 728 if (auto SCS = DS.getStorageClassSpec()) { 729 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 730 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 731 } 732 if (auto TSCS = DS.getThreadStorageClassSpec()) { 733 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 734 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 735 } 736 if (DS.isConstexprSpecified()) { 737 BadSpecifiers.push_back("constexpr"); 738 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 739 } 740 if (DS.isInlineSpecified()) { 741 BadSpecifiers.push_back("inline"); 742 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 743 } 744 if (!BadSpecifiers.empty()) { 745 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 746 Err << (int)BadSpecifiers.size() 747 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 748 // Don't add FixItHints to remove the specifiers; we do still respect 749 // them when building the underlying variable. 750 for (auto Loc : BadSpecifierLocs) 751 Err << SourceRange(Loc, Loc); 752 } 753 // We can't recover from it being declared as a typedef. 754 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 755 return nullptr; 756 } 757 758 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 759 QualType R = TInfo->getType(); 760 761 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 762 UPPC_DeclarationType)) 763 D.setInvalidType(); 764 765 // The syntax only allows a single ref-qualifier prior to the decomposition 766 // declarator. No other declarator chunks are permitted. Also check the type 767 // specifier here. 768 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 769 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 770 (D.getNumTypeObjects() == 1 && 771 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 772 Diag(Decomp.getLSquareLoc(), 773 (D.hasGroupingParens() || 774 (D.getNumTypeObjects() && 775 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 776 ? diag::err_decomp_decl_parens 777 : diag::err_decomp_decl_type) 778 << R; 779 780 // In most cases, there's no actual problem with an explicitly-specified 781 // type, but a function type won't work here, and ActOnVariableDeclarator 782 // shouldn't be called for such a type. 783 if (R->isFunctionType()) 784 D.setInvalidType(); 785 } 786 787 // Build the BindingDecls. 788 SmallVector<BindingDecl*, 8> Bindings; 789 790 // Build the BindingDecls. 791 for (auto &B : D.getDecompositionDeclarator().bindings()) { 792 // Check for name conflicts. 793 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 794 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 795 ForVisibleRedeclaration); 796 LookupName(Previous, S, 797 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 798 799 // It's not permitted to shadow a template parameter name. 800 if (Previous.isSingleResult() && 801 Previous.getFoundDecl()->isTemplateParameter()) { 802 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 803 Previous.getFoundDecl()); 804 Previous.clear(); 805 } 806 807 bool ConsiderLinkage = DC->isFunctionOrMethod() && 808 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 809 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 810 /*AllowInlineNamespace*/false); 811 if (!Previous.empty()) { 812 auto *Old = Previous.getRepresentativeDecl(); 813 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 814 Diag(Old->getLocation(), diag::note_previous_definition); 815 } 816 817 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 818 PushOnScopeChains(BD, S, true); 819 Bindings.push_back(BD); 820 ParsingInitForAutoVars.insert(BD); 821 } 822 823 // There are no prior lookup results for the variable itself, because it 824 // is unnamed. 825 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 826 Decomp.getLSquareLoc()); 827 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 828 ForVisibleRedeclaration); 829 830 // Build the variable that holds the non-decomposed object. 831 bool AddToScope = true; 832 NamedDecl *New = 833 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 834 MultiTemplateParamsArg(), AddToScope, Bindings); 835 if (AddToScope) { 836 S->AddDecl(New); 837 CurContext->addHiddenDecl(New); 838 } 839 840 if (isInOpenMPDeclareTargetContext()) 841 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 842 843 return New; 844 } 845 846 static bool checkSimpleDecomposition( 847 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 848 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 849 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 850 if ((int64_t)Bindings.size() != NumElems) { 851 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 852 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 853 << (NumElems < Bindings.size()); 854 return true; 855 } 856 857 unsigned I = 0; 858 for (auto *B : Bindings) { 859 SourceLocation Loc = B->getLocation(); 860 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 861 if (E.isInvalid()) 862 return true; 863 E = GetInit(Loc, E.get(), I++); 864 if (E.isInvalid()) 865 return true; 866 B->setBinding(ElemType, E.get()); 867 } 868 869 return false; 870 } 871 872 static bool checkArrayLikeDecomposition(Sema &S, 873 ArrayRef<BindingDecl *> Bindings, 874 ValueDecl *Src, QualType DecompType, 875 const llvm::APSInt &NumElems, 876 QualType ElemType) { 877 return checkSimpleDecomposition( 878 S, Bindings, Src, DecompType, NumElems, ElemType, 879 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 880 ExprResult E = S.ActOnIntegerConstant(Loc, I); 881 if (E.isInvalid()) 882 return ExprError(); 883 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 884 }); 885 } 886 887 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 888 ValueDecl *Src, QualType DecompType, 889 const ConstantArrayType *CAT) { 890 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 891 llvm::APSInt(CAT->getSize()), 892 CAT->getElementType()); 893 } 894 895 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 896 ValueDecl *Src, QualType DecompType, 897 const VectorType *VT) { 898 return checkArrayLikeDecomposition( 899 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 900 S.Context.getQualifiedType(VT->getElementType(), 901 DecompType.getQualifiers())); 902 } 903 904 static bool checkComplexDecomposition(Sema &S, 905 ArrayRef<BindingDecl *> Bindings, 906 ValueDecl *Src, QualType DecompType, 907 const ComplexType *CT) { 908 return checkSimpleDecomposition( 909 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 910 S.Context.getQualifiedType(CT->getElementType(), 911 DecompType.getQualifiers()), 912 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 913 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 914 }); 915 } 916 917 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 918 TemplateArgumentListInfo &Args) { 919 SmallString<128> SS; 920 llvm::raw_svector_ostream OS(SS); 921 bool First = true; 922 for (auto &Arg : Args.arguments()) { 923 if (!First) 924 OS << ", "; 925 Arg.getArgument().print(PrintingPolicy, OS); 926 First = false; 927 } 928 return OS.str(); 929 } 930 931 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 932 SourceLocation Loc, StringRef Trait, 933 TemplateArgumentListInfo &Args, 934 unsigned DiagID) { 935 auto DiagnoseMissing = [&] { 936 if (DiagID) 937 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 938 Args); 939 return true; 940 }; 941 942 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 943 NamespaceDecl *Std = S.getStdNamespace(); 944 if (!Std) 945 return DiagnoseMissing(); 946 947 // Look up the trait itself, within namespace std. We can diagnose various 948 // problems with this lookup even if we've been asked to not diagnose a 949 // missing specialization, because this can only fail if the user has been 950 // declaring their own names in namespace std or we don't support the 951 // standard library implementation in use. 952 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 953 Loc, Sema::LookupOrdinaryName); 954 if (!S.LookupQualifiedName(Result, Std)) 955 return DiagnoseMissing(); 956 if (Result.isAmbiguous()) 957 return true; 958 959 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 960 if (!TraitTD) { 961 Result.suppressDiagnostics(); 962 NamedDecl *Found = *Result.begin(); 963 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 964 S.Diag(Found->getLocation(), diag::note_declared_at); 965 return true; 966 } 967 968 // Build the template-id. 969 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 970 if (TraitTy.isNull()) 971 return true; 972 if (!S.isCompleteType(Loc, TraitTy)) { 973 if (DiagID) 974 S.RequireCompleteType( 975 Loc, TraitTy, DiagID, 976 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 977 return true; 978 } 979 980 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 981 assert(RD && "specialization of class template is not a class?"); 982 983 // Look up the member of the trait type. 984 S.LookupQualifiedName(TraitMemberLookup, RD); 985 return TraitMemberLookup.isAmbiguous(); 986 } 987 988 static TemplateArgumentLoc 989 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 990 uint64_t I) { 991 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 992 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 993 } 994 995 static TemplateArgumentLoc 996 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 997 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 998 } 999 1000 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1001 1002 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1003 llvm::APSInt &Size) { 1004 EnterExpressionEvaluationContext ContextRAII( 1005 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1006 1007 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1008 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1009 1010 // Form template argument list for tuple_size<T>. 1011 TemplateArgumentListInfo Args(Loc, Loc); 1012 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1013 1014 // If there's no tuple_size specialization, it's not tuple-like. 1015 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1016 return IsTupleLike::NotTupleLike; 1017 1018 // If we get this far, we've committed to the tuple interpretation, but 1019 // we can still fail if there actually isn't a usable ::value. 1020 1021 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1022 LookupResult &R; 1023 TemplateArgumentListInfo &Args; 1024 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1025 : R(R), Args(Args) {} 1026 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1027 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1028 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1029 } 1030 } Diagnoser(R, Args); 1031 1032 if (R.empty()) { 1033 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1034 return IsTupleLike::Error; 1035 } 1036 1037 ExprResult E = 1038 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1039 if (E.isInvalid()) 1040 return IsTupleLike::Error; 1041 1042 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1043 if (E.isInvalid()) 1044 return IsTupleLike::Error; 1045 1046 return IsTupleLike::TupleLike; 1047 } 1048 1049 /// \return std::tuple_element<I, T>::type. 1050 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1051 unsigned I, QualType T) { 1052 // Form template argument list for tuple_element<I, T>. 1053 TemplateArgumentListInfo Args(Loc, Loc); 1054 Args.addArgument( 1055 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1056 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1057 1058 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1059 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1060 if (lookupStdTypeTraitMember( 1061 S, R, Loc, "tuple_element", Args, 1062 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1063 return QualType(); 1064 1065 auto *TD = R.getAsSingle<TypeDecl>(); 1066 if (!TD) { 1067 R.suppressDiagnostics(); 1068 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1069 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1070 if (!R.empty()) 1071 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1072 return QualType(); 1073 } 1074 1075 return S.Context.getTypeDeclType(TD); 1076 } 1077 1078 namespace { 1079 struct BindingDiagnosticTrap { 1080 Sema &S; 1081 DiagnosticErrorTrap Trap; 1082 BindingDecl *BD; 1083 1084 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1085 : S(S), Trap(S.Diags), BD(BD) {} 1086 ~BindingDiagnosticTrap() { 1087 if (Trap.hasErrorOccurred()) 1088 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1089 } 1090 }; 1091 } 1092 1093 static bool checkTupleLikeDecomposition(Sema &S, 1094 ArrayRef<BindingDecl *> Bindings, 1095 VarDecl *Src, QualType DecompType, 1096 const llvm::APSInt &TupleSize) { 1097 if ((int64_t)Bindings.size() != TupleSize) { 1098 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1099 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1100 << (TupleSize < Bindings.size()); 1101 return true; 1102 } 1103 1104 if (Bindings.empty()) 1105 return false; 1106 1107 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1108 1109 // [dcl.decomp]p3: 1110 // The unqualified-id get is looked up in the scope of E by class member 1111 // access lookup 1112 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1113 bool UseMemberGet = false; 1114 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1115 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1116 S.LookupQualifiedName(MemberGet, RD); 1117 if (MemberGet.isAmbiguous()) 1118 return true; 1119 UseMemberGet = !MemberGet.empty(); 1120 S.FilterAcceptableTemplateNames(MemberGet); 1121 } 1122 1123 unsigned I = 0; 1124 for (auto *B : Bindings) { 1125 BindingDiagnosticTrap Trap(S, B); 1126 SourceLocation Loc = B->getLocation(); 1127 1128 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1129 if (E.isInvalid()) 1130 return true; 1131 1132 // e is an lvalue if the type of the entity is an lvalue reference and 1133 // an xvalue otherwise 1134 if (!Src->getType()->isLValueReferenceType()) 1135 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1136 E.get(), nullptr, VK_XValue); 1137 1138 TemplateArgumentListInfo Args(Loc, Loc); 1139 Args.addArgument( 1140 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1141 1142 if (UseMemberGet) { 1143 // if [lookup of member get] finds at least one declaration, the 1144 // initializer is e.get<i-1>(). 1145 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1146 CXXScopeSpec(), SourceLocation(), nullptr, 1147 MemberGet, &Args, nullptr); 1148 if (E.isInvalid()) 1149 return true; 1150 1151 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1152 } else { 1153 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1154 // in the associated namespaces. 1155 Expr *Get = UnresolvedLookupExpr::Create( 1156 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1157 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1158 UnresolvedSetIterator(), UnresolvedSetIterator()); 1159 1160 Expr *Arg = E.get(); 1161 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1162 } 1163 if (E.isInvalid()) 1164 return true; 1165 Expr *Init = E.get(); 1166 1167 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1168 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1169 if (T.isNull()) 1170 return true; 1171 1172 // each vi is a variable of type "reference to T" initialized with the 1173 // initializer, where the reference is an lvalue reference if the 1174 // initializer is an lvalue and an rvalue reference otherwise 1175 QualType RefType = 1176 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1177 if (RefType.isNull()) 1178 return true; 1179 auto *RefVD = VarDecl::Create( 1180 S.Context, Src->getDeclContext(), Loc, Loc, 1181 B->getDeclName().getAsIdentifierInfo(), RefType, 1182 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1183 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1184 RefVD->setTSCSpec(Src->getTSCSpec()); 1185 RefVD->setImplicit(); 1186 if (Src->isInlineSpecified()) 1187 RefVD->setInlineSpecified(); 1188 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1189 1190 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1191 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1192 InitializationSequence Seq(S, Entity, Kind, Init); 1193 E = Seq.Perform(S, Entity, Kind, Init); 1194 if (E.isInvalid()) 1195 return true; 1196 E = S.ActOnFinishFullExpr(E.get(), Loc); 1197 if (E.isInvalid()) 1198 return true; 1199 RefVD->setInit(E.get()); 1200 RefVD->checkInitIsICE(); 1201 1202 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1203 DeclarationNameInfo(B->getDeclName(), Loc), 1204 RefVD); 1205 if (E.isInvalid()) 1206 return true; 1207 1208 B->setBinding(T, E.get()); 1209 I++; 1210 } 1211 1212 return false; 1213 } 1214 1215 /// Find the base class to decompose in a built-in decomposition of a class type. 1216 /// This base class search is, unfortunately, not quite like any other that we 1217 /// perform anywhere else in C++. 1218 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1219 SourceLocation Loc, 1220 const CXXRecordDecl *RD, 1221 CXXCastPath &BasePath) { 1222 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1223 CXXBasePath &Path) { 1224 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1225 }; 1226 1227 const CXXRecordDecl *ClassWithFields = nullptr; 1228 if (RD->hasDirectFields()) 1229 // [dcl.decomp]p4: 1230 // Otherwise, all of E's non-static data members shall be public direct 1231 // members of E ... 1232 ClassWithFields = RD; 1233 else { 1234 // ... or of ... 1235 CXXBasePaths Paths; 1236 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1237 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1238 // If no classes have fields, just decompose RD itself. (This will work 1239 // if and only if zero bindings were provided.) 1240 return RD; 1241 } 1242 1243 CXXBasePath *BestPath = nullptr; 1244 for (auto &P : Paths) { 1245 if (!BestPath) 1246 BestPath = &P; 1247 else if (!S.Context.hasSameType(P.back().Base->getType(), 1248 BestPath->back().Base->getType())) { 1249 // ... the same ... 1250 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1251 << false << RD << BestPath->back().Base->getType() 1252 << P.back().Base->getType(); 1253 return nullptr; 1254 } else if (P.Access < BestPath->Access) { 1255 BestPath = &P; 1256 } 1257 } 1258 1259 // ... unambiguous ... 1260 QualType BaseType = BestPath->back().Base->getType(); 1261 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1262 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1263 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1264 return nullptr; 1265 } 1266 1267 // ... public base class of E. 1268 if (BestPath->Access != AS_public) { 1269 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1270 << RD << BaseType; 1271 for (auto &BS : *BestPath) { 1272 if (BS.Base->getAccessSpecifier() != AS_public) { 1273 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1274 << (BS.Base->getAccessSpecifier() == AS_protected) 1275 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1276 break; 1277 } 1278 } 1279 return nullptr; 1280 } 1281 1282 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1283 S.BuildBasePathArray(Paths, BasePath); 1284 } 1285 1286 // The above search did not check whether the selected class itself has base 1287 // classes with fields, so check that now. 1288 CXXBasePaths Paths; 1289 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1290 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1291 << (ClassWithFields == RD) << RD << ClassWithFields 1292 << Paths.front().back().Base->getType(); 1293 return nullptr; 1294 } 1295 1296 return ClassWithFields; 1297 } 1298 1299 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1300 ValueDecl *Src, QualType DecompType, 1301 const CXXRecordDecl *RD) { 1302 CXXCastPath BasePath; 1303 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1304 if (!RD) 1305 return true; 1306 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1307 DecompType.getQualifiers()); 1308 1309 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1310 unsigned NumFields = 1311 std::count_if(RD->field_begin(), RD->field_end(), 1312 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1313 assert(Bindings.size() != NumFields); 1314 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1315 << DecompType << (unsigned)Bindings.size() << NumFields 1316 << (NumFields < Bindings.size()); 1317 return true; 1318 }; 1319 1320 // all of E's non-static data members shall be public [...] members, 1321 // E shall not have an anonymous union member, ... 1322 unsigned I = 0; 1323 for (auto *FD : RD->fields()) { 1324 if (FD->isUnnamedBitfield()) 1325 continue; 1326 1327 if (FD->isAnonymousStructOrUnion()) { 1328 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1329 << DecompType << FD->getType()->isUnionType(); 1330 S.Diag(FD->getLocation(), diag::note_declared_at); 1331 return true; 1332 } 1333 1334 // We have a real field to bind. 1335 if (I >= Bindings.size()) 1336 return DiagnoseBadNumberOfBindings(); 1337 auto *B = Bindings[I++]; 1338 1339 SourceLocation Loc = B->getLocation(); 1340 if (FD->getAccess() != AS_public) { 1341 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1342 1343 // Determine whether the access specifier was explicit. 1344 bool Implicit = true; 1345 for (const auto *D : RD->decls()) { 1346 if (declaresSameEntity(D, FD)) 1347 break; 1348 if (isa<AccessSpecDecl>(D)) { 1349 Implicit = false; 1350 break; 1351 } 1352 } 1353 1354 S.Diag(FD->getLocation(), diag::note_access_natural) 1355 << (FD->getAccess() == AS_protected) << Implicit; 1356 return true; 1357 } 1358 1359 // Initialize the binding to Src.FD. 1360 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1361 if (E.isInvalid()) 1362 return true; 1363 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1364 VK_LValue, &BasePath); 1365 if (E.isInvalid()) 1366 return true; 1367 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1368 CXXScopeSpec(), FD, 1369 DeclAccessPair::make(FD, FD->getAccess()), 1370 DeclarationNameInfo(FD->getDeclName(), Loc)); 1371 if (E.isInvalid()) 1372 return true; 1373 1374 // If the type of the member is T, the referenced type is cv T, where cv is 1375 // the cv-qualification of the decomposition expression. 1376 // 1377 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1378 // 'const' to the type of the field. 1379 Qualifiers Q = DecompType.getQualifiers(); 1380 if (FD->isMutable()) 1381 Q.removeConst(); 1382 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1383 } 1384 1385 if (I != Bindings.size()) 1386 return DiagnoseBadNumberOfBindings(); 1387 1388 return false; 1389 } 1390 1391 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1392 QualType DecompType = DD->getType(); 1393 1394 // If the type of the decomposition is dependent, then so is the type of 1395 // each binding. 1396 if (DecompType->isDependentType()) { 1397 for (auto *B : DD->bindings()) 1398 B->setType(Context.DependentTy); 1399 return; 1400 } 1401 1402 DecompType = DecompType.getNonReferenceType(); 1403 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1404 1405 // C++1z [dcl.decomp]/2: 1406 // If E is an array type [...] 1407 // As an extension, we also support decomposition of built-in complex and 1408 // vector types. 1409 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1410 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1411 DD->setInvalidDecl(); 1412 return; 1413 } 1414 if (auto *VT = DecompType->getAs<VectorType>()) { 1415 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1416 DD->setInvalidDecl(); 1417 return; 1418 } 1419 if (auto *CT = DecompType->getAs<ComplexType>()) { 1420 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1421 DD->setInvalidDecl(); 1422 return; 1423 } 1424 1425 // C++1z [dcl.decomp]/3: 1426 // if the expression std::tuple_size<E>::value is a well-formed integral 1427 // constant expression, [...] 1428 llvm::APSInt TupleSize(32); 1429 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1430 case IsTupleLike::Error: 1431 DD->setInvalidDecl(); 1432 return; 1433 1434 case IsTupleLike::TupleLike: 1435 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1436 DD->setInvalidDecl(); 1437 return; 1438 1439 case IsTupleLike::NotTupleLike: 1440 break; 1441 } 1442 1443 // C++1z [dcl.dcl]/8: 1444 // [E shall be of array or non-union class type] 1445 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1446 if (!RD || RD->isUnion()) { 1447 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1448 << DD << !RD << DecompType; 1449 DD->setInvalidDecl(); 1450 return; 1451 } 1452 1453 // C++1z [dcl.decomp]/4: 1454 // all of E's non-static data members shall be [...] direct members of 1455 // E or of the same unambiguous public base class of E, ... 1456 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1457 DD->setInvalidDecl(); 1458 } 1459 1460 /// Merge the exception specifications of two variable declarations. 1461 /// 1462 /// This is called when there's a redeclaration of a VarDecl. The function 1463 /// checks if the redeclaration might have an exception specification and 1464 /// validates compatibility and merges the specs if necessary. 1465 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1466 // Shortcut if exceptions are disabled. 1467 if (!getLangOpts().CXXExceptions) 1468 return; 1469 1470 assert(Context.hasSameType(New->getType(), Old->getType()) && 1471 "Should only be called if types are otherwise the same."); 1472 1473 QualType NewType = New->getType(); 1474 QualType OldType = Old->getType(); 1475 1476 // We're only interested in pointers and references to functions, as well 1477 // as pointers to member functions. 1478 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1479 NewType = R->getPointeeType(); 1480 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1481 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1482 NewType = P->getPointeeType(); 1483 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1484 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1485 NewType = M->getPointeeType(); 1486 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1487 } 1488 1489 if (!NewType->isFunctionProtoType()) 1490 return; 1491 1492 // There's lots of special cases for functions. For function pointers, system 1493 // libraries are hopefully not as broken so that we don't need these 1494 // workarounds. 1495 if (CheckEquivalentExceptionSpec( 1496 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1497 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1498 New->setInvalidDecl(); 1499 } 1500 } 1501 1502 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1503 /// function declaration are well-formed according to C++ 1504 /// [dcl.fct.default]. 1505 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1506 unsigned NumParams = FD->getNumParams(); 1507 unsigned p; 1508 1509 // Find first parameter with a default argument 1510 for (p = 0; p < NumParams; ++p) { 1511 ParmVarDecl *Param = FD->getParamDecl(p); 1512 if (Param->hasDefaultArg()) 1513 break; 1514 } 1515 1516 // C++11 [dcl.fct.default]p4: 1517 // In a given function declaration, each parameter subsequent to a parameter 1518 // with a default argument shall have a default argument supplied in this or 1519 // a previous declaration or shall be a function parameter pack. A default 1520 // argument shall not be redefined by a later declaration (not even to the 1521 // same value). 1522 unsigned LastMissingDefaultArg = 0; 1523 for (; p < NumParams; ++p) { 1524 ParmVarDecl *Param = FD->getParamDecl(p); 1525 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1526 if (Param->isInvalidDecl()) 1527 /* We already complained about this parameter. */; 1528 else if (Param->getIdentifier()) 1529 Diag(Param->getLocation(), 1530 diag::err_param_default_argument_missing_name) 1531 << Param->getIdentifier(); 1532 else 1533 Diag(Param->getLocation(), 1534 diag::err_param_default_argument_missing); 1535 1536 LastMissingDefaultArg = p; 1537 } 1538 } 1539 1540 if (LastMissingDefaultArg > 0) { 1541 // Some default arguments were missing. Clear out all of the 1542 // default arguments up to (and including) the last missing 1543 // default argument, so that we leave the function parameters 1544 // in a semantically valid state. 1545 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1546 ParmVarDecl *Param = FD->getParamDecl(p); 1547 if (Param->hasDefaultArg()) { 1548 Param->setDefaultArg(nullptr); 1549 } 1550 } 1551 } 1552 } 1553 1554 // CheckConstexprParameterTypes - Check whether a function's parameter types 1555 // are all literal types. If so, return true. If not, produce a suitable 1556 // diagnostic and return false. 1557 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1558 const FunctionDecl *FD) { 1559 unsigned ArgIndex = 0; 1560 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1561 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1562 e = FT->param_type_end(); 1563 i != e; ++i, ++ArgIndex) { 1564 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1565 SourceLocation ParamLoc = PD->getLocation(); 1566 if (!(*i)->isDependentType() && 1567 SemaRef.RequireLiteralType(ParamLoc, *i, 1568 diag::err_constexpr_non_literal_param, 1569 ArgIndex+1, PD->getSourceRange(), 1570 isa<CXXConstructorDecl>(FD))) 1571 return false; 1572 } 1573 return true; 1574 } 1575 1576 /// Get diagnostic %select index for tag kind for 1577 /// record diagnostic message. 1578 /// WARNING: Indexes apply to particular diagnostics only! 1579 /// 1580 /// \returns diagnostic %select index. 1581 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1582 switch (Tag) { 1583 case TTK_Struct: return 0; 1584 case TTK_Interface: return 1; 1585 case TTK_Class: return 2; 1586 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1587 } 1588 } 1589 1590 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1591 // the requirements of a constexpr function definition or a constexpr 1592 // constructor definition. If so, return true. If not, produce appropriate 1593 // diagnostics and return false. 1594 // 1595 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1596 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1597 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1598 if (MD && MD->isInstance()) { 1599 // C++11 [dcl.constexpr]p4: 1600 // The definition of a constexpr constructor shall satisfy the following 1601 // constraints: 1602 // - the class shall not have any virtual base classes; 1603 const CXXRecordDecl *RD = MD->getParent(); 1604 if (RD->getNumVBases()) { 1605 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1606 << isa<CXXConstructorDecl>(NewFD) 1607 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1608 for (const auto &I : RD->vbases()) 1609 Diag(I.getLocStart(), 1610 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1611 return false; 1612 } 1613 } 1614 1615 if (!isa<CXXConstructorDecl>(NewFD)) { 1616 // C++11 [dcl.constexpr]p3: 1617 // The definition of a constexpr function shall satisfy the following 1618 // constraints: 1619 // - it shall not be virtual; 1620 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1621 if (Method && Method->isVirtual()) { 1622 Method = Method->getCanonicalDecl(); 1623 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1624 1625 // If it's not obvious why this function is virtual, find an overridden 1626 // function which uses the 'virtual' keyword. 1627 const CXXMethodDecl *WrittenVirtual = Method; 1628 while (!WrittenVirtual->isVirtualAsWritten()) 1629 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1630 if (WrittenVirtual != Method) 1631 Diag(WrittenVirtual->getLocation(), 1632 diag::note_overridden_virtual_function); 1633 return false; 1634 } 1635 1636 // - its return type shall be a literal type; 1637 QualType RT = NewFD->getReturnType(); 1638 if (!RT->isDependentType() && 1639 RequireLiteralType(NewFD->getLocation(), RT, 1640 diag::err_constexpr_non_literal_return)) 1641 return false; 1642 } 1643 1644 // - each of its parameter types shall be a literal type; 1645 if (!CheckConstexprParameterTypes(*this, NewFD)) 1646 return false; 1647 1648 return true; 1649 } 1650 1651 /// Check the given declaration statement is legal within a constexpr function 1652 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1653 /// 1654 /// \return true if the body is OK (maybe only as an extension), false if we 1655 /// have diagnosed a problem. 1656 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1657 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1658 // C++11 [dcl.constexpr]p3 and p4: 1659 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1660 // contain only 1661 for (const auto *DclIt : DS->decls()) { 1662 switch (DclIt->getKind()) { 1663 case Decl::StaticAssert: 1664 case Decl::Using: 1665 case Decl::UsingShadow: 1666 case Decl::UsingDirective: 1667 case Decl::UnresolvedUsingTypename: 1668 case Decl::UnresolvedUsingValue: 1669 // - static_assert-declarations 1670 // - using-declarations, 1671 // - using-directives, 1672 continue; 1673 1674 case Decl::Typedef: 1675 case Decl::TypeAlias: { 1676 // - typedef declarations and alias-declarations that do not define 1677 // classes or enumerations, 1678 const auto *TN = cast<TypedefNameDecl>(DclIt); 1679 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1680 // Don't allow variably-modified types in constexpr functions. 1681 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1682 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1683 << TL.getSourceRange() << TL.getType() 1684 << isa<CXXConstructorDecl>(Dcl); 1685 return false; 1686 } 1687 continue; 1688 } 1689 1690 case Decl::Enum: 1691 case Decl::CXXRecord: 1692 // C++1y allows types to be defined, not just declared. 1693 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1694 SemaRef.Diag(DS->getLocStart(), 1695 SemaRef.getLangOpts().CPlusPlus14 1696 ? diag::warn_cxx11_compat_constexpr_type_definition 1697 : diag::ext_constexpr_type_definition) 1698 << isa<CXXConstructorDecl>(Dcl); 1699 continue; 1700 1701 case Decl::EnumConstant: 1702 case Decl::IndirectField: 1703 case Decl::ParmVar: 1704 // These can only appear with other declarations which are banned in 1705 // C++11 and permitted in C++1y, so ignore them. 1706 continue; 1707 1708 case Decl::Var: 1709 case Decl::Decomposition: { 1710 // C++1y [dcl.constexpr]p3 allows anything except: 1711 // a definition of a variable of non-literal type or of static or 1712 // thread storage duration or for which no initialization is performed. 1713 const auto *VD = cast<VarDecl>(DclIt); 1714 if (VD->isThisDeclarationADefinition()) { 1715 if (VD->isStaticLocal()) { 1716 SemaRef.Diag(VD->getLocation(), 1717 diag::err_constexpr_local_var_static) 1718 << isa<CXXConstructorDecl>(Dcl) 1719 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1720 return false; 1721 } 1722 if (!VD->getType()->isDependentType() && 1723 SemaRef.RequireLiteralType( 1724 VD->getLocation(), VD->getType(), 1725 diag::err_constexpr_local_var_non_literal_type, 1726 isa<CXXConstructorDecl>(Dcl))) 1727 return false; 1728 if (!VD->getType()->isDependentType() && 1729 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1730 SemaRef.Diag(VD->getLocation(), 1731 diag::err_constexpr_local_var_no_init) 1732 << isa<CXXConstructorDecl>(Dcl); 1733 return false; 1734 } 1735 } 1736 SemaRef.Diag(VD->getLocation(), 1737 SemaRef.getLangOpts().CPlusPlus14 1738 ? diag::warn_cxx11_compat_constexpr_local_var 1739 : diag::ext_constexpr_local_var) 1740 << isa<CXXConstructorDecl>(Dcl); 1741 continue; 1742 } 1743 1744 case Decl::NamespaceAlias: 1745 case Decl::Function: 1746 // These are disallowed in C++11 and permitted in C++1y. Allow them 1747 // everywhere as an extension. 1748 if (!Cxx1yLoc.isValid()) 1749 Cxx1yLoc = DS->getLocStart(); 1750 continue; 1751 1752 default: 1753 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1754 << isa<CXXConstructorDecl>(Dcl); 1755 return false; 1756 } 1757 } 1758 1759 return true; 1760 } 1761 1762 /// Check that the given field is initialized within a constexpr constructor. 1763 /// 1764 /// \param Dcl The constexpr constructor being checked. 1765 /// \param Field The field being checked. This may be a member of an anonymous 1766 /// struct or union nested within the class being checked. 1767 /// \param Inits All declarations, including anonymous struct/union members and 1768 /// indirect members, for which any initialization was provided. 1769 /// \param Diagnosed Set to true if an error is produced. 1770 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1771 const FunctionDecl *Dcl, 1772 FieldDecl *Field, 1773 llvm::SmallSet<Decl*, 16> &Inits, 1774 bool &Diagnosed) { 1775 if (Field->isInvalidDecl()) 1776 return; 1777 1778 if (Field->isUnnamedBitfield()) 1779 return; 1780 1781 // Anonymous unions with no variant members and empty anonymous structs do not 1782 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1783 // indirect fields don't need initializing. 1784 if (Field->isAnonymousStructOrUnion() && 1785 (Field->getType()->isUnionType() 1786 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1787 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1788 return; 1789 1790 if (!Inits.count(Field)) { 1791 if (!Diagnosed) { 1792 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1793 Diagnosed = true; 1794 } 1795 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1796 } else if (Field->isAnonymousStructOrUnion()) { 1797 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1798 for (auto *I : RD->fields()) 1799 // If an anonymous union contains an anonymous struct of which any member 1800 // is initialized, all members must be initialized. 1801 if (!RD->isUnion() || Inits.count(I)) 1802 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1803 } 1804 } 1805 1806 /// Check the provided statement is allowed in a constexpr function 1807 /// definition. 1808 static bool 1809 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1810 SmallVectorImpl<SourceLocation> &ReturnStmts, 1811 SourceLocation &Cxx1yLoc) { 1812 // - its function-body shall be [...] a compound-statement that contains only 1813 switch (S->getStmtClass()) { 1814 case Stmt::NullStmtClass: 1815 // - null statements, 1816 return true; 1817 1818 case Stmt::DeclStmtClass: 1819 // - static_assert-declarations 1820 // - using-declarations, 1821 // - using-directives, 1822 // - typedef declarations and alias-declarations that do not define 1823 // classes or enumerations, 1824 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1825 return false; 1826 return true; 1827 1828 case Stmt::ReturnStmtClass: 1829 // - and exactly one return statement; 1830 if (isa<CXXConstructorDecl>(Dcl)) { 1831 // C++1y allows return statements in constexpr constructors. 1832 if (!Cxx1yLoc.isValid()) 1833 Cxx1yLoc = S->getLocStart(); 1834 return true; 1835 } 1836 1837 ReturnStmts.push_back(S->getLocStart()); 1838 return true; 1839 1840 case Stmt::CompoundStmtClass: { 1841 // C++1y allows compound-statements. 1842 if (!Cxx1yLoc.isValid()) 1843 Cxx1yLoc = S->getLocStart(); 1844 1845 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1846 for (auto *BodyIt : CompStmt->body()) { 1847 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1848 Cxx1yLoc)) 1849 return false; 1850 } 1851 return true; 1852 } 1853 1854 case Stmt::AttributedStmtClass: 1855 if (!Cxx1yLoc.isValid()) 1856 Cxx1yLoc = S->getLocStart(); 1857 return true; 1858 1859 case Stmt::IfStmtClass: { 1860 // C++1y allows if-statements. 1861 if (!Cxx1yLoc.isValid()) 1862 Cxx1yLoc = S->getLocStart(); 1863 1864 IfStmt *If = cast<IfStmt>(S); 1865 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1866 Cxx1yLoc)) 1867 return false; 1868 if (If->getElse() && 1869 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1870 Cxx1yLoc)) 1871 return false; 1872 return true; 1873 } 1874 1875 case Stmt::WhileStmtClass: 1876 case Stmt::DoStmtClass: 1877 case Stmt::ForStmtClass: 1878 case Stmt::CXXForRangeStmtClass: 1879 case Stmt::ContinueStmtClass: 1880 // C++1y allows all of these. We don't allow them as extensions in C++11, 1881 // because they don't make sense without variable mutation. 1882 if (!SemaRef.getLangOpts().CPlusPlus14) 1883 break; 1884 if (!Cxx1yLoc.isValid()) 1885 Cxx1yLoc = S->getLocStart(); 1886 for (Stmt *SubStmt : S->children()) 1887 if (SubStmt && 1888 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1889 Cxx1yLoc)) 1890 return false; 1891 return true; 1892 1893 case Stmt::SwitchStmtClass: 1894 case Stmt::CaseStmtClass: 1895 case Stmt::DefaultStmtClass: 1896 case Stmt::BreakStmtClass: 1897 // C++1y allows switch-statements, and since they don't need variable 1898 // mutation, we can reasonably allow them in C++11 as an extension. 1899 if (!Cxx1yLoc.isValid()) 1900 Cxx1yLoc = S->getLocStart(); 1901 for (Stmt *SubStmt : S->children()) 1902 if (SubStmt && 1903 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1904 Cxx1yLoc)) 1905 return false; 1906 return true; 1907 1908 default: 1909 if (!isa<Expr>(S)) 1910 break; 1911 1912 // C++1y allows expression-statements. 1913 if (!Cxx1yLoc.isValid()) 1914 Cxx1yLoc = S->getLocStart(); 1915 return true; 1916 } 1917 1918 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1919 << isa<CXXConstructorDecl>(Dcl); 1920 return false; 1921 } 1922 1923 /// Check the body for the given constexpr function declaration only contains 1924 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1925 /// 1926 /// \return true if the body is OK, false if we have diagnosed a problem. 1927 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1928 if (isa<CXXTryStmt>(Body)) { 1929 // C++11 [dcl.constexpr]p3: 1930 // The definition of a constexpr function shall satisfy the following 1931 // constraints: [...] 1932 // - its function-body shall be = delete, = default, or a 1933 // compound-statement 1934 // 1935 // C++11 [dcl.constexpr]p4: 1936 // In the definition of a constexpr constructor, [...] 1937 // - its function-body shall not be a function-try-block; 1938 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1939 << isa<CXXConstructorDecl>(Dcl); 1940 return false; 1941 } 1942 1943 SmallVector<SourceLocation, 4> ReturnStmts; 1944 1945 // - its function-body shall be [...] a compound-statement that contains only 1946 // [... list of cases ...] 1947 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1948 SourceLocation Cxx1yLoc; 1949 for (auto *BodyIt : CompBody->body()) { 1950 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1951 return false; 1952 } 1953 1954 if (Cxx1yLoc.isValid()) 1955 Diag(Cxx1yLoc, 1956 getLangOpts().CPlusPlus14 1957 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1958 : diag::ext_constexpr_body_invalid_stmt) 1959 << isa<CXXConstructorDecl>(Dcl); 1960 1961 if (const CXXConstructorDecl *Constructor 1962 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1963 const CXXRecordDecl *RD = Constructor->getParent(); 1964 // DR1359: 1965 // - every non-variant non-static data member and base class sub-object 1966 // shall be initialized; 1967 // DR1460: 1968 // - if the class is a union having variant members, exactly one of them 1969 // shall be initialized; 1970 if (RD->isUnion()) { 1971 if (Constructor->getNumCtorInitializers() == 0 && 1972 RD->hasVariantMembers()) { 1973 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1974 return false; 1975 } 1976 } else if (!Constructor->isDependentContext() && 1977 !Constructor->isDelegatingConstructor()) { 1978 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1979 1980 // Skip detailed checking if we have enough initializers, and we would 1981 // allow at most one initializer per member. 1982 bool AnyAnonStructUnionMembers = false; 1983 unsigned Fields = 0; 1984 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1985 E = RD->field_end(); I != E; ++I, ++Fields) { 1986 if (I->isAnonymousStructOrUnion()) { 1987 AnyAnonStructUnionMembers = true; 1988 break; 1989 } 1990 } 1991 // DR1460: 1992 // - if the class is a union-like class, but is not a union, for each of 1993 // its anonymous union members having variant members, exactly one of 1994 // them shall be initialized; 1995 if (AnyAnonStructUnionMembers || 1996 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1997 // Check initialization of non-static data members. Base classes are 1998 // always initialized so do not need to be checked. Dependent bases 1999 // might not have initializers in the member initializer list. 2000 llvm::SmallSet<Decl*, 16> Inits; 2001 for (const auto *I: Constructor->inits()) { 2002 if (FieldDecl *FD = I->getMember()) 2003 Inits.insert(FD); 2004 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2005 Inits.insert(ID->chain_begin(), ID->chain_end()); 2006 } 2007 2008 bool Diagnosed = false; 2009 for (auto *I : RD->fields()) 2010 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2011 if (Diagnosed) 2012 return false; 2013 } 2014 } 2015 } else { 2016 if (ReturnStmts.empty()) { 2017 // C++1y doesn't require constexpr functions to contain a 'return' 2018 // statement. We still do, unless the return type might be void, because 2019 // otherwise if there's no return statement, the function cannot 2020 // be used in a core constant expression. 2021 bool OK = getLangOpts().CPlusPlus14 && 2022 (Dcl->getReturnType()->isVoidType() || 2023 Dcl->getReturnType()->isDependentType()); 2024 Diag(Dcl->getLocation(), 2025 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2026 : diag::err_constexpr_body_no_return); 2027 if (!OK) 2028 return false; 2029 } else if (ReturnStmts.size() > 1) { 2030 Diag(ReturnStmts.back(), 2031 getLangOpts().CPlusPlus14 2032 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2033 : diag::ext_constexpr_body_multiple_return); 2034 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2035 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2036 } 2037 } 2038 2039 // C++11 [dcl.constexpr]p5: 2040 // if no function argument values exist such that the function invocation 2041 // substitution would produce a constant expression, the program is 2042 // ill-formed; no diagnostic required. 2043 // C++11 [dcl.constexpr]p3: 2044 // - every constructor call and implicit conversion used in initializing the 2045 // return value shall be one of those allowed in a constant expression. 2046 // C++11 [dcl.constexpr]p4: 2047 // - every constructor involved in initializing non-static data members and 2048 // base class sub-objects shall be a constexpr constructor. 2049 SmallVector<PartialDiagnosticAt, 8> Diags; 2050 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2051 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2052 << isa<CXXConstructorDecl>(Dcl); 2053 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2054 Diag(Diags[I].first, Diags[I].second); 2055 // Don't return false here: we allow this for compatibility in 2056 // system headers. 2057 } 2058 2059 return true; 2060 } 2061 2062 /// Get the class that is directly named by the current context. This is the 2063 /// class for which an unqualified-id in this scope could name a constructor 2064 /// or destructor. 2065 /// 2066 /// If the scope specifier denotes a class, this will be that class. 2067 /// If the scope specifier is empty, this will be the class whose 2068 /// member-specification we are currently within. Otherwise, there 2069 /// is no such class. 2070 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2071 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2072 2073 if (SS && SS->isInvalid()) 2074 return nullptr; 2075 2076 if (SS && SS->isNotEmpty()) { 2077 DeclContext *DC = computeDeclContext(*SS, true); 2078 return dyn_cast_or_null<CXXRecordDecl>(DC); 2079 } 2080 2081 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2082 } 2083 2084 /// isCurrentClassName - Determine whether the identifier II is the 2085 /// name of the class type currently being defined. In the case of 2086 /// nested classes, this will only return true if II is the name of 2087 /// the innermost class. 2088 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2089 const CXXScopeSpec *SS) { 2090 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2091 return CurDecl && &II == CurDecl->getIdentifier(); 2092 } 2093 2094 /// Determine whether the identifier II is a typo for the name of 2095 /// the class type currently being defined. If so, update it to the identifier 2096 /// that should have been used. 2097 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2098 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2099 2100 if (!getLangOpts().SpellChecking) 2101 return false; 2102 2103 CXXRecordDecl *CurDecl; 2104 if (SS && SS->isSet() && !SS->isInvalid()) { 2105 DeclContext *DC = computeDeclContext(*SS, true); 2106 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2107 } else 2108 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2109 2110 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2111 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2112 < II->getLength()) { 2113 II = CurDecl->getIdentifier(); 2114 return true; 2115 } 2116 2117 return false; 2118 } 2119 2120 /// Determine whether the given class is a base class of the given 2121 /// class, including looking at dependent bases. 2122 static bool findCircularInheritance(const CXXRecordDecl *Class, 2123 const CXXRecordDecl *Current) { 2124 SmallVector<const CXXRecordDecl*, 8> Queue; 2125 2126 Class = Class->getCanonicalDecl(); 2127 while (true) { 2128 for (const auto &I : Current->bases()) { 2129 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2130 if (!Base) 2131 continue; 2132 2133 Base = Base->getDefinition(); 2134 if (!Base) 2135 continue; 2136 2137 if (Base->getCanonicalDecl() == Class) 2138 return true; 2139 2140 Queue.push_back(Base); 2141 } 2142 2143 if (Queue.empty()) 2144 return false; 2145 2146 Current = Queue.pop_back_val(); 2147 } 2148 2149 return false; 2150 } 2151 2152 /// Check the validity of a C++ base class specifier. 2153 /// 2154 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2155 /// and returns NULL otherwise. 2156 CXXBaseSpecifier * 2157 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2158 SourceRange SpecifierRange, 2159 bool Virtual, AccessSpecifier Access, 2160 TypeSourceInfo *TInfo, 2161 SourceLocation EllipsisLoc) { 2162 QualType BaseType = TInfo->getType(); 2163 2164 // C++ [class.union]p1: 2165 // A union shall not have base classes. 2166 if (Class->isUnion()) { 2167 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2168 << SpecifierRange; 2169 return nullptr; 2170 } 2171 2172 if (EllipsisLoc.isValid() && 2173 !TInfo->getType()->containsUnexpandedParameterPack()) { 2174 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2175 << TInfo->getTypeLoc().getSourceRange(); 2176 EllipsisLoc = SourceLocation(); 2177 } 2178 2179 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2180 2181 if (BaseType->isDependentType()) { 2182 // Make sure that we don't have circular inheritance among our dependent 2183 // bases. For non-dependent bases, the check for completeness below handles 2184 // this. 2185 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2186 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2187 ((BaseDecl = BaseDecl->getDefinition()) && 2188 findCircularInheritance(Class, BaseDecl))) { 2189 Diag(BaseLoc, diag::err_circular_inheritance) 2190 << BaseType << Context.getTypeDeclType(Class); 2191 2192 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2193 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2194 << BaseType; 2195 2196 return nullptr; 2197 } 2198 } 2199 2200 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2201 Class->getTagKind() == TTK_Class, 2202 Access, TInfo, EllipsisLoc); 2203 } 2204 2205 // Base specifiers must be record types. 2206 if (!BaseType->isRecordType()) { 2207 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2208 return nullptr; 2209 } 2210 2211 // C++ [class.union]p1: 2212 // A union shall not be used as a base class. 2213 if (BaseType->isUnionType()) { 2214 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2215 return nullptr; 2216 } 2217 2218 // For the MS ABI, propagate DLL attributes to base class templates. 2219 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2220 if (Attr *ClassAttr = getDLLAttr(Class)) { 2221 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2222 BaseType->getAsCXXRecordDecl())) { 2223 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2224 BaseLoc); 2225 } 2226 } 2227 } 2228 2229 // C++ [class.derived]p2: 2230 // The class-name in a base-specifier shall not be an incompletely 2231 // defined class. 2232 if (RequireCompleteType(BaseLoc, BaseType, 2233 diag::err_incomplete_base_class, SpecifierRange)) { 2234 Class->setInvalidDecl(); 2235 return nullptr; 2236 } 2237 2238 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2239 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2240 assert(BaseDecl && "Record type has no declaration"); 2241 BaseDecl = BaseDecl->getDefinition(); 2242 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2243 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2244 assert(CXXBaseDecl && "Base type is not a C++ type"); 2245 2246 // Microsoft docs say: 2247 // "If a base-class has a code_seg attribute, derived classes must have the 2248 // same attribute." 2249 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2250 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2251 if ((DerivedCSA || BaseCSA) && 2252 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2253 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2254 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2255 << CXXBaseDecl; 2256 return nullptr; 2257 } 2258 2259 // A class which contains a flexible array member is not suitable for use as a 2260 // base class: 2261 // - If the layout determines that a base comes before another base, 2262 // the flexible array member would index into the subsequent base. 2263 // - If the layout determines that base comes before the derived class, 2264 // the flexible array member would index into the derived class. 2265 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2266 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2267 << CXXBaseDecl->getDeclName(); 2268 return nullptr; 2269 } 2270 2271 // C++ [class]p3: 2272 // If a class is marked final and it appears as a base-type-specifier in 2273 // base-clause, the program is ill-formed. 2274 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2275 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2276 << CXXBaseDecl->getDeclName() 2277 << FA->isSpelledAsSealed(); 2278 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2279 << CXXBaseDecl->getDeclName() << FA->getRange(); 2280 return nullptr; 2281 } 2282 2283 if (BaseDecl->isInvalidDecl()) 2284 Class->setInvalidDecl(); 2285 2286 // Create the base specifier. 2287 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2288 Class->getTagKind() == TTK_Class, 2289 Access, TInfo, EllipsisLoc); 2290 } 2291 2292 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2293 /// one entry in the base class list of a class specifier, for 2294 /// example: 2295 /// class foo : public bar, virtual private baz { 2296 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2297 BaseResult 2298 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2299 ParsedAttributes &Attributes, 2300 bool Virtual, AccessSpecifier Access, 2301 ParsedType basetype, SourceLocation BaseLoc, 2302 SourceLocation EllipsisLoc) { 2303 if (!classdecl) 2304 return true; 2305 2306 AdjustDeclIfTemplate(classdecl); 2307 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2308 if (!Class) 2309 return true; 2310 2311 // We haven't yet attached the base specifiers. 2312 Class->setIsParsingBaseSpecifiers(); 2313 2314 // We do not support any C++11 attributes on base-specifiers yet. 2315 // Diagnose any attributes we see. 2316 for (const ParsedAttr &AL : Attributes) { 2317 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2318 continue; 2319 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2320 ? diag::warn_unknown_attribute_ignored 2321 : diag::err_base_specifier_attribute) 2322 << AL.getName(); 2323 } 2324 2325 TypeSourceInfo *TInfo = nullptr; 2326 GetTypeFromParser(basetype, &TInfo); 2327 2328 if (EllipsisLoc.isInvalid() && 2329 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2330 UPPC_BaseType)) 2331 return true; 2332 2333 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2334 Virtual, Access, TInfo, 2335 EllipsisLoc)) 2336 return BaseSpec; 2337 else 2338 Class->setInvalidDecl(); 2339 2340 return true; 2341 } 2342 2343 /// Use small set to collect indirect bases. As this is only used 2344 /// locally, there's no need to abstract the small size parameter. 2345 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2346 2347 /// Recursively add the bases of Type. Don't add Type itself. 2348 static void 2349 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2350 const QualType &Type) 2351 { 2352 // Even though the incoming type is a base, it might not be 2353 // a class -- it could be a template parm, for instance. 2354 if (auto Rec = Type->getAs<RecordType>()) { 2355 auto Decl = Rec->getAsCXXRecordDecl(); 2356 2357 // Iterate over its bases. 2358 for (const auto &BaseSpec : Decl->bases()) { 2359 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2360 .getUnqualifiedType(); 2361 if (Set.insert(Base).second) 2362 // If we've not already seen it, recurse. 2363 NoteIndirectBases(Context, Set, Base); 2364 } 2365 } 2366 } 2367 2368 /// Performs the actual work of attaching the given base class 2369 /// specifiers to a C++ class. 2370 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2371 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2372 if (Bases.empty()) 2373 return false; 2374 2375 // Used to keep track of which base types we have already seen, so 2376 // that we can properly diagnose redundant direct base types. Note 2377 // that the key is always the unqualified canonical type of the base 2378 // class. 2379 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2380 2381 // Used to track indirect bases so we can see if a direct base is 2382 // ambiguous. 2383 IndirectBaseSet IndirectBaseTypes; 2384 2385 // Copy non-redundant base specifiers into permanent storage. 2386 unsigned NumGoodBases = 0; 2387 bool Invalid = false; 2388 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2389 QualType NewBaseType 2390 = Context.getCanonicalType(Bases[idx]->getType()); 2391 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2392 2393 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2394 if (KnownBase) { 2395 // C++ [class.mi]p3: 2396 // A class shall not be specified as a direct base class of a 2397 // derived class more than once. 2398 Diag(Bases[idx]->getLocStart(), 2399 diag::err_duplicate_base_class) 2400 << KnownBase->getType() 2401 << Bases[idx]->getSourceRange(); 2402 2403 // Delete the duplicate base class specifier; we're going to 2404 // overwrite its pointer later. 2405 Context.Deallocate(Bases[idx]); 2406 2407 Invalid = true; 2408 } else { 2409 // Okay, add this new base class. 2410 KnownBase = Bases[idx]; 2411 Bases[NumGoodBases++] = Bases[idx]; 2412 2413 // Note this base's direct & indirect bases, if there could be ambiguity. 2414 if (Bases.size() > 1) 2415 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2416 2417 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2418 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2419 if (Class->isInterface() && 2420 (!RD->isInterfaceLike() || 2421 KnownBase->getAccessSpecifier() != AS_public)) { 2422 // The Microsoft extension __interface does not permit bases that 2423 // are not themselves public interfaces. 2424 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2425 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2426 << RD->getSourceRange(); 2427 Invalid = true; 2428 } 2429 if (RD->hasAttr<WeakAttr>()) 2430 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2431 } 2432 } 2433 } 2434 2435 // Attach the remaining base class specifiers to the derived class. 2436 Class->setBases(Bases.data(), NumGoodBases); 2437 2438 // Check that the only base classes that are duplicate are virtual. 2439 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2440 // Check whether this direct base is inaccessible due to ambiguity. 2441 QualType BaseType = Bases[idx]->getType(); 2442 2443 // Skip all dependent types in templates being used as base specifiers. 2444 // Checks below assume that the base specifier is a CXXRecord. 2445 if (BaseType->isDependentType()) 2446 continue; 2447 2448 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2449 .getUnqualifiedType(); 2450 2451 if (IndirectBaseTypes.count(CanonicalBase)) { 2452 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2453 /*DetectVirtual=*/true); 2454 bool found 2455 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2456 assert(found); 2457 (void)found; 2458 2459 if (Paths.isAmbiguous(CanonicalBase)) 2460 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2461 << BaseType << getAmbiguousPathsDisplayString(Paths) 2462 << Bases[idx]->getSourceRange(); 2463 else 2464 assert(Bases[idx]->isVirtual()); 2465 } 2466 2467 // Delete the base class specifier, since its data has been copied 2468 // into the CXXRecordDecl. 2469 Context.Deallocate(Bases[idx]); 2470 } 2471 2472 return Invalid; 2473 } 2474 2475 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2476 /// class, after checking whether there are any duplicate base 2477 /// classes. 2478 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2479 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2480 if (!ClassDecl || Bases.empty()) 2481 return; 2482 2483 AdjustDeclIfTemplate(ClassDecl); 2484 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2485 } 2486 2487 /// Determine whether the type \p Derived is a C++ class that is 2488 /// derived from the type \p Base. 2489 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2490 if (!getLangOpts().CPlusPlus) 2491 return false; 2492 2493 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2494 if (!DerivedRD) 2495 return false; 2496 2497 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2498 if (!BaseRD) 2499 return false; 2500 2501 // If either the base or the derived type is invalid, don't try to 2502 // check whether one is derived from the other. 2503 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2504 return false; 2505 2506 // FIXME: In a modules build, do we need the entire path to be visible for us 2507 // to be able to use the inheritance relationship? 2508 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2509 return false; 2510 2511 return DerivedRD->isDerivedFrom(BaseRD); 2512 } 2513 2514 /// Determine whether the type \p Derived is a C++ class that is 2515 /// derived from the type \p Base. 2516 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2517 CXXBasePaths &Paths) { 2518 if (!getLangOpts().CPlusPlus) 2519 return false; 2520 2521 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2522 if (!DerivedRD) 2523 return false; 2524 2525 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2526 if (!BaseRD) 2527 return false; 2528 2529 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2530 return false; 2531 2532 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2533 } 2534 2535 static void BuildBasePathArray(const CXXBasePath &Path, 2536 CXXCastPath &BasePathArray) { 2537 // We first go backward and check if we have a virtual base. 2538 // FIXME: It would be better if CXXBasePath had the base specifier for 2539 // the nearest virtual base. 2540 unsigned Start = 0; 2541 for (unsigned I = Path.size(); I != 0; --I) { 2542 if (Path[I - 1].Base->isVirtual()) { 2543 Start = I - 1; 2544 break; 2545 } 2546 } 2547 2548 // Now add all bases. 2549 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2550 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2551 } 2552 2553 2554 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2555 CXXCastPath &BasePathArray) { 2556 assert(BasePathArray.empty() && "Base path array must be empty!"); 2557 assert(Paths.isRecordingPaths() && "Must record paths!"); 2558 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2559 } 2560 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2561 /// conversion (where Derived and Base are class types) is 2562 /// well-formed, meaning that the conversion is unambiguous (and 2563 /// that all of the base classes are accessible). Returns true 2564 /// and emits a diagnostic if the code is ill-formed, returns false 2565 /// otherwise. Loc is the location where this routine should point to 2566 /// if there is an error, and Range is the source range to highlight 2567 /// if there is an error. 2568 /// 2569 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2570 /// diagnostic for the respective type of error will be suppressed, but the 2571 /// check for ill-formed code will still be performed. 2572 bool 2573 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2574 unsigned InaccessibleBaseID, 2575 unsigned AmbigiousBaseConvID, 2576 SourceLocation Loc, SourceRange Range, 2577 DeclarationName Name, 2578 CXXCastPath *BasePath, 2579 bool IgnoreAccess) { 2580 // First, determine whether the path from Derived to Base is 2581 // ambiguous. This is slightly more expensive than checking whether 2582 // the Derived to Base conversion exists, because here we need to 2583 // explore multiple paths to determine if there is an ambiguity. 2584 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2585 /*DetectVirtual=*/false); 2586 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2587 if (!DerivationOkay) 2588 return true; 2589 2590 const CXXBasePath *Path = nullptr; 2591 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2592 Path = &Paths.front(); 2593 2594 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2595 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2596 // user to access such bases. 2597 if (!Path && getLangOpts().MSVCCompat) { 2598 for (const CXXBasePath &PossiblePath : Paths) { 2599 if (PossiblePath.size() == 1) { 2600 Path = &PossiblePath; 2601 if (AmbigiousBaseConvID) 2602 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2603 << Base << Derived << Range; 2604 break; 2605 } 2606 } 2607 } 2608 2609 if (Path) { 2610 if (!IgnoreAccess) { 2611 // Check that the base class can be accessed. 2612 switch ( 2613 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2614 case AR_inaccessible: 2615 return true; 2616 case AR_accessible: 2617 case AR_dependent: 2618 case AR_delayed: 2619 break; 2620 } 2621 } 2622 2623 // Build a base path if necessary. 2624 if (BasePath) 2625 ::BuildBasePathArray(*Path, *BasePath); 2626 return false; 2627 } 2628 2629 if (AmbigiousBaseConvID) { 2630 // We know that the derived-to-base conversion is ambiguous, and 2631 // we're going to produce a diagnostic. Perform the derived-to-base 2632 // search just one more time to compute all of the possible paths so 2633 // that we can print them out. This is more expensive than any of 2634 // the previous derived-to-base checks we've done, but at this point 2635 // performance isn't as much of an issue. 2636 Paths.clear(); 2637 Paths.setRecordingPaths(true); 2638 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2639 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2640 (void)StillOkay; 2641 2642 // Build up a textual representation of the ambiguous paths, e.g., 2643 // D -> B -> A, that will be used to illustrate the ambiguous 2644 // conversions in the diagnostic. We only print one of the paths 2645 // to each base class subobject. 2646 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2647 2648 Diag(Loc, AmbigiousBaseConvID) 2649 << Derived << Base << PathDisplayStr << Range << Name; 2650 } 2651 return true; 2652 } 2653 2654 bool 2655 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2656 SourceLocation Loc, SourceRange Range, 2657 CXXCastPath *BasePath, 2658 bool IgnoreAccess) { 2659 return CheckDerivedToBaseConversion( 2660 Derived, Base, diag::err_upcast_to_inaccessible_base, 2661 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2662 BasePath, IgnoreAccess); 2663 } 2664 2665 2666 /// Builds a string representing ambiguous paths from a 2667 /// specific derived class to different subobjects of the same base 2668 /// class. 2669 /// 2670 /// This function builds a string that can be used in error messages 2671 /// to show the different paths that one can take through the 2672 /// inheritance hierarchy to go from the derived class to different 2673 /// subobjects of a base class. The result looks something like this: 2674 /// @code 2675 /// struct D -> struct B -> struct A 2676 /// struct D -> struct C -> struct A 2677 /// @endcode 2678 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2679 std::string PathDisplayStr; 2680 std::set<unsigned> DisplayedPaths; 2681 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2682 Path != Paths.end(); ++Path) { 2683 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2684 // We haven't displayed a path to this particular base 2685 // class subobject yet. 2686 PathDisplayStr += "\n "; 2687 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2688 for (CXXBasePath::const_iterator Element = Path->begin(); 2689 Element != Path->end(); ++Element) 2690 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2691 } 2692 } 2693 2694 return PathDisplayStr; 2695 } 2696 2697 //===----------------------------------------------------------------------===// 2698 // C++ class member Handling 2699 //===----------------------------------------------------------------------===// 2700 2701 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2702 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2703 SourceLocation ColonLoc, 2704 const ParsedAttributesView &Attrs) { 2705 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2706 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2707 ASLoc, ColonLoc); 2708 CurContext->addHiddenDecl(ASDecl); 2709 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2710 } 2711 2712 /// CheckOverrideControl - Check C++11 override control semantics. 2713 void Sema::CheckOverrideControl(NamedDecl *D) { 2714 if (D->isInvalidDecl()) 2715 return; 2716 2717 // We only care about "override" and "final" declarations. 2718 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2719 return; 2720 2721 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2722 2723 // We can't check dependent instance methods. 2724 if (MD && MD->isInstance() && 2725 (MD->getParent()->hasAnyDependentBases() || 2726 MD->getType()->isDependentType())) 2727 return; 2728 2729 if (MD && !MD->isVirtual()) { 2730 // If we have a non-virtual method, check if if hides a virtual method. 2731 // (In that case, it's most likely the method has the wrong type.) 2732 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2733 FindHiddenVirtualMethods(MD, OverloadedMethods); 2734 2735 if (!OverloadedMethods.empty()) { 2736 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2737 Diag(OA->getLocation(), 2738 diag::override_keyword_hides_virtual_member_function) 2739 << "override" << (OverloadedMethods.size() > 1); 2740 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2741 Diag(FA->getLocation(), 2742 diag::override_keyword_hides_virtual_member_function) 2743 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2744 << (OverloadedMethods.size() > 1); 2745 } 2746 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2747 MD->setInvalidDecl(); 2748 return; 2749 } 2750 // Fall through into the general case diagnostic. 2751 // FIXME: We might want to attempt typo correction here. 2752 } 2753 2754 if (!MD || !MD->isVirtual()) { 2755 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2756 Diag(OA->getLocation(), 2757 diag::override_keyword_only_allowed_on_virtual_member_functions) 2758 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2759 D->dropAttr<OverrideAttr>(); 2760 } 2761 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2762 Diag(FA->getLocation(), 2763 diag::override_keyword_only_allowed_on_virtual_member_functions) 2764 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2765 << FixItHint::CreateRemoval(FA->getLocation()); 2766 D->dropAttr<FinalAttr>(); 2767 } 2768 return; 2769 } 2770 2771 // C++11 [class.virtual]p5: 2772 // If a function is marked with the virt-specifier override and 2773 // does not override a member function of a base class, the program is 2774 // ill-formed. 2775 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2776 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2777 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2778 << MD->getDeclName(); 2779 } 2780 2781 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2782 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2783 return; 2784 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2785 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2786 return; 2787 2788 SourceLocation Loc = MD->getLocation(); 2789 SourceLocation SpellingLoc = Loc; 2790 if (getSourceManager().isMacroArgExpansion(Loc)) 2791 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2792 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2793 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2794 return; 2795 2796 if (MD->size_overridden_methods() > 0) { 2797 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2798 ? diag::warn_destructor_marked_not_override_overriding 2799 : diag::warn_function_marked_not_override_overriding; 2800 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2801 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2802 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2803 } 2804 } 2805 2806 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2807 /// function overrides a virtual member function marked 'final', according to 2808 /// C++11 [class.virtual]p4. 2809 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2810 const CXXMethodDecl *Old) { 2811 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2812 if (!FA) 2813 return false; 2814 2815 Diag(New->getLocation(), diag::err_final_function_overridden) 2816 << New->getDeclName() 2817 << FA->isSpelledAsSealed(); 2818 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2819 return true; 2820 } 2821 2822 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2823 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2824 // FIXME: Destruction of ObjC lifetime types has side-effects. 2825 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2826 return !RD->isCompleteDefinition() || 2827 !RD->hasTrivialDefaultConstructor() || 2828 !RD->hasTrivialDestructor(); 2829 return false; 2830 } 2831 2832 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 2833 ParsedAttributesView::const_iterator Itr = 2834 llvm::find_if(list, [](const ParsedAttr &AL) { 2835 return AL.isDeclspecPropertyAttribute(); 2836 }); 2837 if (Itr != list.end()) 2838 return &*Itr; 2839 return nullptr; 2840 } 2841 2842 // Check if there is a field shadowing. 2843 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2844 DeclarationName FieldName, 2845 const CXXRecordDecl *RD) { 2846 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2847 return; 2848 2849 // To record a shadowed field in a base 2850 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2851 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2852 CXXBasePath &Path) { 2853 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2854 // Record an ambiguous path directly 2855 if (Bases.find(Base) != Bases.end()) 2856 return true; 2857 for (const auto Field : Base->lookup(FieldName)) { 2858 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2859 Field->getAccess() != AS_private) { 2860 assert(Field->getAccess() != AS_none); 2861 assert(Bases.find(Base) == Bases.end()); 2862 Bases[Base] = Field; 2863 return true; 2864 } 2865 } 2866 return false; 2867 }; 2868 2869 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2870 /*DetectVirtual=*/true); 2871 if (!RD->lookupInBases(FieldShadowed, Paths)) 2872 return; 2873 2874 for (const auto &P : Paths) { 2875 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2876 auto It = Bases.find(Base); 2877 // Skip duplicated bases 2878 if (It == Bases.end()) 2879 continue; 2880 auto BaseField = It->second; 2881 assert(BaseField->getAccess() != AS_private); 2882 if (AS_none != 2883 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2884 Diag(Loc, diag::warn_shadow_field) 2885 << FieldName << RD << Base; 2886 Diag(BaseField->getLocation(), diag::note_shadow_field); 2887 Bases.erase(It); 2888 } 2889 } 2890 } 2891 2892 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2893 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2894 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2895 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2896 /// present (but parsing it has been deferred). 2897 NamedDecl * 2898 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2899 MultiTemplateParamsArg TemplateParameterLists, 2900 Expr *BW, const VirtSpecifiers &VS, 2901 InClassInitStyle InitStyle) { 2902 const DeclSpec &DS = D.getDeclSpec(); 2903 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2904 DeclarationName Name = NameInfo.getName(); 2905 SourceLocation Loc = NameInfo.getLoc(); 2906 2907 // For anonymous bitfields, the location should point to the type. 2908 if (Loc.isInvalid()) 2909 Loc = D.getLocStart(); 2910 2911 Expr *BitWidth = static_cast<Expr*>(BW); 2912 2913 assert(isa<CXXRecordDecl>(CurContext)); 2914 assert(!DS.isFriendSpecified()); 2915 2916 bool isFunc = D.isDeclarationOfFunction(); 2917 const ParsedAttr *MSPropertyAttr = 2918 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 2919 2920 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2921 // The Microsoft extension __interface only permits public member functions 2922 // and prohibits constructors, destructors, operators, non-public member 2923 // functions, static methods and data members. 2924 unsigned InvalidDecl; 2925 bool ShowDeclName = true; 2926 if (!isFunc && 2927 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2928 InvalidDecl = 0; 2929 else if (!isFunc) 2930 InvalidDecl = 1; 2931 else if (AS != AS_public) 2932 InvalidDecl = 2; 2933 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2934 InvalidDecl = 3; 2935 else switch (Name.getNameKind()) { 2936 case DeclarationName::CXXConstructorName: 2937 InvalidDecl = 4; 2938 ShowDeclName = false; 2939 break; 2940 2941 case DeclarationName::CXXDestructorName: 2942 InvalidDecl = 5; 2943 ShowDeclName = false; 2944 break; 2945 2946 case DeclarationName::CXXOperatorName: 2947 case DeclarationName::CXXConversionFunctionName: 2948 InvalidDecl = 6; 2949 break; 2950 2951 default: 2952 InvalidDecl = 0; 2953 break; 2954 } 2955 2956 if (InvalidDecl) { 2957 if (ShowDeclName) 2958 Diag(Loc, diag::err_invalid_member_in_interface) 2959 << (InvalidDecl-1) << Name; 2960 else 2961 Diag(Loc, diag::err_invalid_member_in_interface) 2962 << (InvalidDecl-1) << ""; 2963 return nullptr; 2964 } 2965 } 2966 2967 // C++ 9.2p6: A member shall not be declared to have automatic storage 2968 // duration (auto, register) or with the extern storage-class-specifier. 2969 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2970 // data members and cannot be applied to names declared const or static, 2971 // and cannot be applied to reference members. 2972 switch (DS.getStorageClassSpec()) { 2973 case DeclSpec::SCS_unspecified: 2974 case DeclSpec::SCS_typedef: 2975 case DeclSpec::SCS_static: 2976 break; 2977 case DeclSpec::SCS_mutable: 2978 if (isFunc) { 2979 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2980 2981 // FIXME: It would be nicer if the keyword was ignored only for this 2982 // declarator. Otherwise we could get follow-up errors. 2983 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2984 } 2985 break; 2986 default: 2987 Diag(DS.getStorageClassSpecLoc(), 2988 diag::err_storageclass_invalid_for_member); 2989 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2990 break; 2991 } 2992 2993 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2994 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2995 !isFunc); 2996 2997 if (DS.isConstexprSpecified() && isInstField) { 2998 SemaDiagnosticBuilder B = 2999 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3000 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3001 if (InitStyle == ICIS_NoInit) { 3002 B << 0 << 0; 3003 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3004 B << FixItHint::CreateRemoval(ConstexprLoc); 3005 else { 3006 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3007 D.getMutableDeclSpec().ClearConstexprSpec(); 3008 const char *PrevSpec; 3009 unsigned DiagID; 3010 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3011 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3012 (void)Failed; 3013 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3014 } 3015 } else { 3016 B << 1; 3017 const char *PrevSpec; 3018 unsigned DiagID; 3019 if (D.getMutableDeclSpec().SetStorageClassSpec( 3020 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3021 Context.getPrintingPolicy())) { 3022 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3023 "This is the only DeclSpec that should fail to be applied"); 3024 B << 1; 3025 } else { 3026 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3027 isInstField = false; 3028 } 3029 } 3030 } 3031 3032 NamedDecl *Member; 3033 if (isInstField) { 3034 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3035 3036 // Data members must have identifiers for names. 3037 if (!Name.isIdentifier()) { 3038 Diag(Loc, diag::err_bad_variable_name) 3039 << Name; 3040 return nullptr; 3041 } 3042 3043 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3044 3045 // Member field could not be with "template" keyword. 3046 // So TemplateParameterLists should be empty in this case. 3047 if (TemplateParameterLists.size()) { 3048 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3049 if (TemplateParams->size()) { 3050 // There is no such thing as a member field template. 3051 Diag(D.getIdentifierLoc(), diag::err_template_member) 3052 << II 3053 << SourceRange(TemplateParams->getTemplateLoc(), 3054 TemplateParams->getRAngleLoc()); 3055 } else { 3056 // There is an extraneous 'template<>' for this member. 3057 Diag(TemplateParams->getTemplateLoc(), 3058 diag::err_template_member_noparams) 3059 << II 3060 << SourceRange(TemplateParams->getTemplateLoc(), 3061 TemplateParams->getRAngleLoc()); 3062 } 3063 return nullptr; 3064 } 3065 3066 if (SS.isSet() && !SS.isInvalid()) { 3067 // The user provided a superfluous scope specifier inside a class 3068 // definition: 3069 // 3070 // class X { 3071 // int X::member; 3072 // }; 3073 if (DeclContext *DC = computeDeclContext(SS, false)) 3074 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3075 D.getName().getKind() == 3076 UnqualifiedIdKind::IK_TemplateId); 3077 else 3078 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3079 << Name << SS.getRange(); 3080 3081 SS.clear(); 3082 } 3083 3084 if (MSPropertyAttr) { 3085 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3086 BitWidth, InitStyle, AS, *MSPropertyAttr); 3087 if (!Member) 3088 return nullptr; 3089 isInstField = false; 3090 } else { 3091 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3092 BitWidth, InitStyle, AS); 3093 if (!Member) 3094 return nullptr; 3095 } 3096 3097 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3098 } else { 3099 Member = HandleDeclarator(S, D, TemplateParameterLists); 3100 if (!Member) 3101 return nullptr; 3102 3103 // Non-instance-fields can't have a bitfield. 3104 if (BitWidth) { 3105 if (Member->isInvalidDecl()) { 3106 // don't emit another diagnostic. 3107 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3108 // C++ 9.6p3: A bit-field shall not be a static member. 3109 // "static member 'A' cannot be a bit-field" 3110 Diag(Loc, diag::err_static_not_bitfield) 3111 << Name << BitWidth->getSourceRange(); 3112 } else if (isa<TypedefDecl>(Member)) { 3113 // "typedef member 'x' cannot be a bit-field" 3114 Diag(Loc, diag::err_typedef_not_bitfield) 3115 << Name << BitWidth->getSourceRange(); 3116 } else { 3117 // A function typedef ("typedef int f(); f a;"). 3118 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3119 Diag(Loc, diag::err_not_integral_type_bitfield) 3120 << Name << cast<ValueDecl>(Member)->getType() 3121 << BitWidth->getSourceRange(); 3122 } 3123 3124 BitWidth = nullptr; 3125 Member->setInvalidDecl(); 3126 } 3127 3128 NamedDecl *NonTemplateMember = Member; 3129 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3130 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3131 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3132 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3133 3134 Member->setAccess(AS); 3135 3136 // If we have declared a member function template or static data member 3137 // template, set the access of the templated declaration as well. 3138 if (NonTemplateMember != Member) 3139 NonTemplateMember->setAccess(AS); 3140 3141 // C++ [temp.deduct.guide]p3: 3142 // A deduction guide [...] for a member class template [shall be 3143 // declared] with the same access [as the template]. 3144 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3145 auto *TD = DG->getDeducedTemplate(); 3146 if (AS != TD->getAccess()) { 3147 Diag(DG->getLocStart(), diag::err_deduction_guide_wrong_access); 3148 Diag(TD->getLocStart(), diag::note_deduction_guide_template_access) 3149 << TD->getAccess(); 3150 const AccessSpecDecl *LastAccessSpec = nullptr; 3151 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3152 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3153 LastAccessSpec = AccessSpec; 3154 } 3155 assert(LastAccessSpec && "differing access with no access specifier"); 3156 Diag(LastAccessSpec->getLocStart(), diag::note_deduction_guide_access) 3157 << AS; 3158 } 3159 } 3160 } 3161 3162 if (VS.isOverrideSpecified()) 3163 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3164 if (VS.isFinalSpecified()) 3165 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3166 VS.isFinalSpelledSealed())); 3167 3168 if (VS.getLastLocation().isValid()) { 3169 // Update the end location of a method that has a virt-specifiers. 3170 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3171 MD->setRangeEnd(VS.getLastLocation()); 3172 } 3173 3174 CheckOverrideControl(Member); 3175 3176 assert((Name || isInstField) && "No identifier for non-field ?"); 3177 3178 if (isInstField) { 3179 FieldDecl *FD = cast<FieldDecl>(Member); 3180 FieldCollector->Add(FD); 3181 3182 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3183 // Remember all explicit private FieldDecls that have a name, no side 3184 // effects and are not part of a dependent type declaration. 3185 if (!FD->isImplicit() && FD->getDeclName() && 3186 FD->getAccess() == AS_private && 3187 !FD->hasAttr<UnusedAttr>() && 3188 !FD->getParent()->isDependentContext() && 3189 !InitializationHasSideEffects(*FD)) 3190 UnusedPrivateFields.insert(FD); 3191 } 3192 } 3193 3194 return Member; 3195 } 3196 3197 namespace { 3198 class UninitializedFieldVisitor 3199 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3200 Sema &S; 3201 // List of Decls to generate a warning on. Also remove Decls that become 3202 // initialized. 3203 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3204 // List of base classes of the record. Classes are removed after their 3205 // initializers. 3206 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3207 // Vector of decls to be removed from the Decl set prior to visiting the 3208 // nodes. These Decls may have been initialized in the prior initializer. 3209 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3210 // If non-null, add a note to the warning pointing back to the constructor. 3211 const CXXConstructorDecl *Constructor; 3212 // Variables to hold state when processing an initializer list. When 3213 // InitList is true, special case initialization of FieldDecls matching 3214 // InitListFieldDecl. 3215 bool InitList; 3216 FieldDecl *InitListFieldDecl; 3217 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3218 3219 public: 3220 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3221 UninitializedFieldVisitor(Sema &S, 3222 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3223 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3224 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3225 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3226 3227 // Returns true if the use of ME is not an uninitialized use. 3228 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3229 bool CheckReferenceOnly) { 3230 llvm::SmallVector<FieldDecl*, 4> Fields; 3231 bool ReferenceField = false; 3232 while (ME) { 3233 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3234 if (!FD) 3235 return false; 3236 Fields.push_back(FD); 3237 if (FD->getType()->isReferenceType()) 3238 ReferenceField = true; 3239 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3240 } 3241 3242 // Binding a reference to an unintialized field is not an 3243 // uninitialized use. 3244 if (CheckReferenceOnly && !ReferenceField) 3245 return true; 3246 3247 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3248 // Discard the first field since it is the field decl that is being 3249 // initialized. 3250 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3251 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3252 } 3253 3254 for (auto UsedIter = UsedFieldIndex.begin(), 3255 UsedEnd = UsedFieldIndex.end(), 3256 OrigIter = InitFieldIndex.begin(), 3257 OrigEnd = InitFieldIndex.end(); 3258 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3259 if (*UsedIter < *OrigIter) 3260 return true; 3261 if (*UsedIter > *OrigIter) 3262 break; 3263 } 3264 3265 return false; 3266 } 3267 3268 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3269 bool AddressOf) { 3270 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3271 return; 3272 3273 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3274 // or union. 3275 MemberExpr *FieldME = ME; 3276 3277 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3278 3279 Expr *Base = ME; 3280 while (MemberExpr *SubME = 3281 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3282 3283 if (isa<VarDecl>(SubME->getMemberDecl())) 3284 return; 3285 3286 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3287 if (!FD->isAnonymousStructOrUnion()) 3288 FieldME = SubME; 3289 3290 if (!FieldME->getType().isPODType(S.Context)) 3291 AllPODFields = false; 3292 3293 Base = SubME->getBase(); 3294 } 3295 3296 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3297 return; 3298 3299 if (AddressOf && AllPODFields) 3300 return; 3301 3302 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3303 3304 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3305 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3306 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3307 } 3308 3309 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3310 QualType T = BaseCast->getType(); 3311 if (T->isPointerType() && 3312 BaseClasses.count(T->getPointeeType())) { 3313 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3314 << T->getPointeeType() << FoundVD; 3315 } 3316 } 3317 } 3318 3319 if (!Decls.count(FoundVD)) 3320 return; 3321 3322 const bool IsReference = FoundVD->getType()->isReferenceType(); 3323 3324 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3325 // Special checking for initializer lists. 3326 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3327 return; 3328 } 3329 } else { 3330 // Prevent double warnings on use of unbounded references. 3331 if (CheckReferenceOnly && !IsReference) 3332 return; 3333 } 3334 3335 unsigned diag = IsReference 3336 ? diag::warn_reference_field_is_uninit 3337 : diag::warn_field_is_uninit; 3338 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3339 if (Constructor) 3340 S.Diag(Constructor->getLocation(), 3341 diag::note_uninit_in_this_constructor) 3342 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3343 3344 } 3345 3346 void HandleValue(Expr *E, bool AddressOf) { 3347 E = E->IgnoreParens(); 3348 3349 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3350 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3351 AddressOf /*AddressOf*/); 3352 return; 3353 } 3354 3355 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3356 Visit(CO->getCond()); 3357 HandleValue(CO->getTrueExpr(), AddressOf); 3358 HandleValue(CO->getFalseExpr(), AddressOf); 3359 return; 3360 } 3361 3362 if (BinaryConditionalOperator *BCO = 3363 dyn_cast<BinaryConditionalOperator>(E)) { 3364 Visit(BCO->getCond()); 3365 HandleValue(BCO->getFalseExpr(), AddressOf); 3366 return; 3367 } 3368 3369 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3370 HandleValue(OVE->getSourceExpr(), AddressOf); 3371 return; 3372 } 3373 3374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3375 switch (BO->getOpcode()) { 3376 default: 3377 break; 3378 case(BO_PtrMemD): 3379 case(BO_PtrMemI): 3380 HandleValue(BO->getLHS(), AddressOf); 3381 Visit(BO->getRHS()); 3382 return; 3383 case(BO_Comma): 3384 Visit(BO->getLHS()); 3385 HandleValue(BO->getRHS(), AddressOf); 3386 return; 3387 } 3388 } 3389 3390 Visit(E); 3391 } 3392 3393 void CheckInitListExpr(InitListExpr *ILE) { 3394 InitFieldIndex.push_back(0); 3395 for (auto Child : ILE->children()) { 3396 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3397 CheckInitListExpr(SubList); 3398 } else { 3399 Visit(Child); 3400 } 3401 ++InitFieldIndex.back(); 3402 } 3403 InitFieldIndex.pop_back(); 3404 } 3405 3406 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3407 FieldDecl *Field, const Type *BaseClass) { 3408 // Remove Decls that may have been initialized in the previous 3409 // initializer. 3410 for (ValueDecl* VD : DeclsToRemove) 3411 Decls.erase(VD); 3412 DeclsToRemove.clear(); 3413 3414 Constructor = FieldConstructor; 3415 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3416 3417 if (ILE && Field) { 3418 InitList = true; 3419 InitListFieldDecl = Field; 3420 InitFieldIndex.clear(); 3421 CheckInitListExpr(ILE); 3422 } else { 3423 InitList = false; 3424 Visit(E); 3425 } 3426 3427 if (Field) 3428 Decls.erase(Field); 3429 if (BaseClass) 3430 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3431 } 3432 3433 void VisitMemberExpr(MemberExpr *ME) { 3434 // All uses of unbounded reference fields will warn. 3435 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3436 } 3437 3438 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3439 if (E->getCastKind() == CK_LValueToRValue) { 3440 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3441 return; 3442 } 3443 3444 Inherited::VisitImplicitCastExpr(E); 3445 } 3446 3447 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3448 if (E->getConstructor()->isCopyConstructor()) { 3449 Expr *ArgExpr = E->getArg(0); 3450 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3451 if (ILE->getNumInits() == 1) 3452 ArgExpr = ILE->getInit(0); 3453 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3454 if (ICE->getCastKind() == CK_NoOp) 3455 ArgExpr = ICE->getSubExpr(); 3456 HandleValue(ArgExpr, false /*AddressOf*/); 3457 return; 3458 } 3459 Inherited::VisitCXXConstructExpr(E); 3460 } 3461 3462 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3463 Expr *Callee = E->getCallee(); 3464 if (isa<MemberExpr>(Callee)) { 3465 HandleValue(Callee, false /*AddressOf*/); 3466 for (auto Arg : E->arguments()) 3467 Visit(Arg); 3468 return; 3469 } 3470 3471 Inherited::VisitCXXMemberCallExpr(E); 3472 } 3473 3474 void VisitCallExpr(CallExpr *E) { 3475 // Treat std::move as a use. 3476 if (E->isCallToStdMove()) { 3477 HandleValue(E->getArg(0), /*AddressOf=*/false); 3478 return; 3479 } 3480 3481 Inherited::VisitCallExpr(E); 3482 } 3483 3484 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3485 Expr *Callee = E->getCallee(); 3486 3487 if (isa<UnresolvedLookupExpr>(Callee)) 3488 return Inherited::VisitCXXOperatorCallExpr(E); 3489 3490 Visit(Callee); 3491 for (auto Arg : E->arguments()) 3492 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3493 } 3494 3495 void VisitBinaryOperator(BinaryOperator *E) { 3496 // If a field assignment is detected, remove the field from the 3497 // uninitiailized field set. 3498 if (E->getOpcode() == BO_Assign) 3499 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3500 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3501 if (!FD->getType()->isReferenceType()) 3502 DeclsToRemove.push_back(FD); 3503 3504 if (E->isCompoundAssignmentOp()) { 3505 HandleValue(E->getLHS(), false /*AddressOf*/); 3506 Visit(E->getRHS()); 3507 return; 3508 } 3509 3510 Inherited::VisitBinaryOperator(E); 3511 } 3512 3513 void VisitUnaryOperator(UnaryOperator *E) { 3514 if (E->isIncrementDecrementOp()) { 3515 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3516 return; 3517 } 3518 if (E->getOpcode() == UO_AddrOf) { 3519 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3520 HandleValue(ME->getBase(), true /*AddressOf*/); 3521 return; 3522 } 3523 } 3524 3525 Inherited::VisitUnaryOperator(E); 3526 } 3527 }; 3528 3529 // Diagnose value-uses of fields to initialize themselves, e.g. 3530 // foo(foo) 3531 // where foo is not also a parameter to the constructor. 3532 // Also diagnose across field uninitialized use such as 3533 // x(y), y(x) 3534 // TODO: implement -Wuninitialized and fold this into that framework. 3535 static void DiagnoseUninitializedFields( 3536 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3537 3538 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3539 Constructor->getLocation())) { 3540 return; 3541 } 3542 3543 if (Constructor->isInvalidDecl()) 3544 return; 3545 3546 const CXXRecordDecl *RD = Constructor->getParent(); 3547 3548 if (RD->getDescribedClassTemplate()) 3549 return; 3550 3551 // Holds fields that are uninitialized. 3552 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3553 3554 // At the beginning, all fields are uninitialized. 3555 for (auto *I : RD->decls()) { 3556 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3557 UninitializedFields.insert(FD); 3558 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3559 UninitializedFields.insert(IFD->getAnonField()); 3560 } 3561 } 3562 3563 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3564 for (auto I : RD->bases()) 3565 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3566 3567 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3568 return; 3569 3570 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3571 UninitializedFields, 3572 UninitializedBaseClasses); 3573 3574 for (const auto *FieldInit : Constructor->inits()) { 3575 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3576 break; 3577 3578 Expr *InitExpr = FieldInit->getInit(); 3579 if (!InitExpr) 3580 continue; 3581 3582 if (CXXDefaultInitExpr *Default = 3583 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3584 InitExpr = Default->getExpr(); 3585 if (!InitExpr) 3586 continue; 3587 // In class initializers will point to the constructor. 3588 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3589 FieldInit->getAnyMember(), 3590 FieldInit->getBaseClass()); 3591 } else { 3592 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3593 FieldInit->getAnyMember(), 3594 FieldInit->getBaseClass()); 3595 } 3596 } 3597 } 3598 } // namespace 3599 3600 /// Enter a new C++ default initializer scope. After calling this, the 3601 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3602 /// parsing or instantiating the initializer failed. 3603 void Sema::ActOnStartCXXInClassMemberInitializer() { 3604 // Create a synthetic function scope to represent the call to the constructor 3605 // that notionally surrounds a use of this initializer. 3606 PushFunctionScope(); 3607 } 3608 3609 /// This is invoked after parsing an in-class initializer for a 3610 /// non-static C++ class member, and after instantiating an in-class initializer 3611 /// in a class template. Such actions are deferred until the class is complete. 3612 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3613 SourceLocation InitLoc, 3614 Expr *InitExpr) { 3615 // Pop the notional constructor scope we created earlier. 3616 PopFunctionScopeInfo(nullptr, D); 3617 3618 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3619 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3620 "must set init style when field is created"); 3621 3622 if (!InitExpr) { 3623 D->setInvalidDecl(); 3624 if (FD) 3625 FD->removeInClassInitializer(); 3626 return; 3627 } 3628 3629 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3630 FD->setInvalidDecl(); 3631 FD->removeInClassInitializer(); 3632 return; 3633 } 3634 3635 ExprResult Init = InitExpr; 3636 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3637 InitializedEntity Entity = 3638 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3639 InitializationKind Kind = 3640 FD->getInClassInitStyle() == ICIS_ListInit 3641 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(), 3642 InitExpr->getLocStart(), 3643 InitExpr->getLocEnd()) 3644 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3645 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3646 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3647 if (Init.isInvalid()) { 3648 FD->setInvalidDecl(); 3649 return; 3650 } 3651 } 3652 3653 // C++11 [class.base.init]p7: 3654 // The initialization of each base and member constitutes a 3655 // full-expression. 3656 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3657 if (Init.isInvalid()) { 3658 FD->setInvalidDecl(); 3659 return; 3660 } 3661 3662 InitExpr = Init.get(); 3663 3664 FD->setInClassInitializer(InitExpr); 3665 } 3666 3667 /// Find the direct and/or virtual base specifiers that 3668 /// correspond to the given base type, for use in base initialization 3669 /// within a constructor. 3670 static bool FindBaseInitializer(Sema &SemaRef, 3671 CXXRecordDecl *ClassDecl, 3672 QualType BaseType, 3673 const CXXBaseSpecifier *&DirectBaseSpec, 3674 const CXXBaseSpecifier *&VirtualBaseSpec) { 3675 // First, check for a direct base class. 3676 DirectBaseSpec = nullptr; 3677 for (const auto &Base : ClassDecl->bases()) { 3678 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3679 // We found a direct base of this type. That's what we're 3680 // initializing. 3681 DirectBaseSpec = &Base; 3682 break; 3683 } 3684 } 3685 3686 // Check for a virtual base class. 3687 // FIXME: We might be able to short-circuit this if we know in advance that 3688 // there are no virtual bases. 3689 VirtualBaseSpec = nullptr; 3690 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3691 // We haven't found a base yet; search the class hierarchy for a 3692 // virtual base class. 3693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3694 /*DetectVirtual=*/false); 3695 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3696 SemaRef.Context.getTypeDeclType(ClassDecl), 3697 BaseType, Paths)) { 3698 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3699 Path != Paths.end(); ++Path) { 3700 if (Path->back().Base->isVirtual()) { 3701 VirtualBaseSpec = Path->back().Base; 3702 break; 3703 } 3704 } 3705 } 3706 } 3707 3708 return DirectBaseSpec || VirtualBaseSpec; 3709 } 3710 3711 /// Handle a C++ member initializer using braced-init-list syntax. 3712 MemInitResult 3713 Sema::ActOnMemInitializer(Decl *ConstructorD, 3714 Scope *S, 3715 CXXScopeSpec &SS, 3716 IdentifierInfo *MemberOrBase, 3717 ParsedType TemplateTypeTy, 3718 const DeclSpec &DS, 3719 SourceLocation IdLoc, 3720 Expr *InitList, 3721 SourceLocation EllipsisLoc) { 3722 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3723 DS, IdLoc, InitList, 3724 EllipsisLoc); 3725 } 3726 3727 /// Handle a C++ member initializer using parentheses syntax. 3728 MemInitResult 3729 Sema::ActOnMemInitializer(Decl *ConstructorD, 3730 Scope *S, 3731 CXXScopeSpec &SS, 3732 IdentifierInfo *MemberOrBase, 3733 ParsedType TemplateTypeTy, 3734 const DeclSpec &DS, 3735 SourceLocation IdLoc, 3736 SourceLocation LParenLoc, 3737 ArrayRef<Expr *> Args, 3738 SourceLocation RParenLoc, 3739 SourceLocation EllipsisLoc) { 3740 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3741 Args, RParenLoc); 3742 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3743 DS, IdLoc, List, EllipsisLoc); 3744 } 3745 3746 namespace { 3747 3748 // Callback to only accept typo corrections that can be a valid C++ member 3749 // intializer: either a non-static field member or a base class. 3750 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3751 public: 3752 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3753 : ClassDecl(ClassDecl) {} 3754 3755 bool ValidateCandidate(const TypoCorrection &candidate) override { 3756 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3757 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3758 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3759 return isa<TypeDecl>(ND); 3760 } 3761 return false; 3762 } 3763 3764 private: 3765 CXXRecordDecl *ClassDecl; 3766 }; 3767 3768 } 3769 3770 /// Handle a C++ member initializer. 3771 MemInitResult 3772 Sema::BuildMemInitializer(Decl *ConstructorD, 3773 Scope *S, 3774 CXXScopeSpec &SS, 3775 IdentifierInfo *MemberOrBase, 3776 ParsedType TemplateTypeTy, 3777 const DeclSpec &DS, 3778 SourceLocation IdLoc, 3779 Expr *Init, 3780 SourceLocation EllipsisLoc) { 3781 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3782 if (!Res.isUsable()) 3783 return true; 3784 Init = Res.get(); 3785 3786 if (!ConstructorD) 3787 return true; 3788 3789 AdjustDeclIfTemplate(ConstructorD); 3790 3791 CXXConstructorDecl *Constructor 3792 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3793 if (!Constructor) { 3794 // The user wrote a constructor initializer on a function that is 3795 // not a C++ constructor. Ignore the error for now, because we may 3796 // have more member initializers coming; we'll diagnose it just 3797 // once in ActOnMemInitializers. 3798 return true; 3799 } 3800 3801 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3802 3803 // C++ [class.base.init]p2: 3804 // Names in a mem-initializer-id are looked up in the scope of the 3805 // constructor's class and, if not found in that scope, are looked 3806 // up in the scope containing the constructor's definition. 3807 // [Note: if the constructor's class contains a member with the 3808 // same name as a direct or virtual base class of the class, a 3809 // mem-initializer-id naming the member or base class and composed 3810 // of a single identifier refers to the class member. A 3811 // mem-initializer-id for the hidden base class may be specified 3812 // using a qualified name. ] 3813 if (!SS.getScopeRep() && !TemplateTypeTy) { 3814 // Look for a member, first. 3815 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3816 if (!Result.empty()) { 3817 ValueDecl *Member; 3818 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3819 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3820 if (EllipsisLoc.isValid()) 3821 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3822 << MemberOrBase 3823 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3824 3825 return BuildMemberInitializer(Member, Init, IdLoc); 3826 } 3827 } 3828 } 3829 // It didn't name a member, so see if it names a class. 3830 QualType BaseType; 3831 TypeSourceInfo *TInfo = nullptr; 3832 3833 if (TemplateTypeTy) { 3834 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3835 } else if (DS.getTypeSpecType() == TST_decltype) { 3836 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3837 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3838 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3839 return true; 3840 } else { 3841 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3842 LookupParsedName(R, S, &SS); 3843 3844 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3845 if (!TyD) { 3846 if (R.isAmbiguous()) return true; 3847 3848 // We don't want access-control diagnostics here. 3849 R.suppressDiagnostics(); 3850 3851 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3852 bool NotUnknownSpecialization = false; 3853 DeclContext *DC = computeDeclContext(SS, false); 3854 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3855 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3856 3857 if (!NotUnknownSpecialization) { 3858 // When the scope specifier can refer to a member of an unknown 3859 // specialization, we take it as a type name. 3860 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3861 SS.getWithLocInContext(Context), 3862 *MemberOrBase, IdLoc); 3863 if (BaseType.isNull()) 3864 return true; 3865 3866 TInfo = Context.CreateTypeSourceInfo(BaseType); 3867 DependentNameTypeLoc TL = 3868 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3869 if (!TL.isNull()) { 3870 TL.setNameLoc(IdLoc); 3871 TL.setElaboratedKeywordLoc(SourceLocation()); 3872 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3873 } 3874 3875 R.clear(); 3876 R.setLookupName(MemberOrBase); 3877 } 3878 } 3879 3880 // If no results were found, try to correct typos. 3881 TypoCorrection Corr; 3882 if (R.empty() && BaseType.isNull() && 3883 (Corr = CorrectTypo( 3884 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3885 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3886 CTK_ErrorRecovery, ClassDecl))) { 3887 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3888 // We have found a non-static data member with a similar 3889 // name to what was typed; complain and initialize that 3890 // member. 3891 diagnoseTypo(Corr, 3892 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3893 << MemberOrBase << true); 3894 return BuildMemberInitializer(Member, Init, IdLoc); 3895 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3896 const CXXBaseSpecifier *DirectBaseSpec; 3897 const CXXBaseSpecifier *VirtualBaseSpec; 3898 if (FindBaseInitializer(*this, ClassDecl, 3899 Context.getTypeDeclType(Type), 3900 DirectBaseSpec, VirtualBaseSpec)) { 3901 // We have found a direct or virtual base class with a 3902 // similar name to what was typed; complain and initialize 3903 // that base class. 3904 diagnoseTypo(Corr, 3905 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3906 << MemberOrBase << false, 3907 PDiag() /*Suppress note, we provide our own.*/); 3908 3909 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3910 : VirtualBaseSpec; 3911 Diag(BaseSpec->getLocStart(), 3912 diag::note_base_class_specified_here) 3913 << BaseSpec->getType() 3914 << BaseSpec->getSourceRange(); 3915 3916 TyD = Type; 3917 } 3918 } 3919 } 3920 3921 if (!TyD && BaseType.isNull()) { 3922 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3923 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3924 return true; 3925 } 3926 } 3927 3928 if (BaseType.isNull()) { 3929 BaseType = Context.getTypeDeclType(TyD); 3930 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3931 if (SS.isSet()) { 3932 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3933 BaseType); 3934 TInfo = Context.CreateTypeSourceInfo(BaseType); 3935 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3936 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3937 TL.setElaboratedKeywordLoc(SourceLocation()); 3938 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3939 } 3940 } 3941 } 3942 3943 if (!TInfo) 3944 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3945 3946 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 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 // C++11 [class.base.init]p7: 4004 // The initialization of each base and member constitutes a 4005 // full-expression. 4006 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 4007 if (MemberInit.isInvalid()) 4008 return true; 4009 4010 Init = MemberInit.get(); 4011 } 4012 4013 if (DirectMember) { 4014 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4015 InitRange.getBegin(), Init, 4016 InitRange.getEnd()); 4017 } else { 4018 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4019 InitRange.getBegin(), Init, 4020 InitRange.getEnd()); 4021 } 4022 } 4023 4024 MemInitResult 4025 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4026 CXXRecordDecl *ClassDecl) { 4027 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4028 if (!LangOpts.CPlusPlus11) 4029 return Diag(NameLoc, diag::err_delegating_ctor) 4030 << TInfo->getTypeLoc().getLocalSourceRange(); 4031 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4032 4033 bool InitList = true; 4034 MultiExprArg Args = Init; 4035 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4036 InitList = false; 4037 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4038 } 4039 4040 SourceRange InitRange = Init->getSourceRange(); 4041 // Initialize the object. 4042 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4043 QualType(ClassDecl->getTypeForDecl(), 0)); 4044 InitializationKind Kind = 4045 InitList ? InitializationKind::CreateDirectList( 4046 NameLoc, Init->getLocStart(), Init->getLocEnd()) 4047 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4048 InitRange.getEnd()); 4049 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4050 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4051 Args, nullptr); 4052 if (DelegationInit.isInvalid()) 4053 return true; 4054 4055 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4056 "Delegating constructor with no target?"); 4057 4058 // C++11 [class.base.init]p7: 4059 // The initialization of each base and member constitutes a 4060 // full-expression. 4061 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4062 InitRange.getBegin()); 4063 if (DelegationInit.isInvalid()) 4064 return true; 4065 4066 // If we are in a dependent context, template instantiation will 4067 // perform this type-checking again. Just save the arguments that we 4068 // received in a ParenListExpr. 4069 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4070 // of the information that we have about the base 4071 // initializer. However, deconstructing the ASTs is a dicey process, 4072 // and this approach is far more likely to get the corner cases right. 4073 if (CurContext->isDependentContext()) 4074 DelegationInit = Init; 4075 4076 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4077 DelegationInit.getAs<Expr>(), 4078 InitRange.getEnd()); 4079 } 4080 4081 MemInitResult 4082 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4083 Expr *Init, CXXRecordDecl *ClassDecl, 4084 SourceLocation EllipsisLoc) { 4085 SourceLocation BaseLoc 4086 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4087 4088 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4089 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4090 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4091 4092 // C++ [class.base.init]p2: 4093 // [...] Unless the mem-initializer-id names a nonstatic data 4094 // member of the constructor's class or a direct or virtual base 4095 // of that class, the mem-initializer is ill-formed. A 4096 // mem-initializer-list can initialize a base class using any 4097 // name that denotes that base class type. 4098 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4099 4100 SourceRange InitRange = Init->getSourceRange(); 4101 if (EllipsisLoc.isValid()) { 4102 // This is a pack expansion. 4103 if (!BaseType->containsUnexpandedParameterPack()) { 4104 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4105 << SourceRange(BaseLoc, InitRange.getEnd()); 4106 4107 EllipsisLoc = SourceLocation(); 4108 } 4109 } else { 4110 // Check for any unexpanded parameter packs. 4111 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4112 return true; 4113 4114 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4115 return true; 4116 } 4117 4118 // Check for direct and virtual base classes. 4119 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4120 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4121 if (!Dependent) { 4122 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4123 BaseType)) 4124 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4125 4126 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4127 VirtualBaseSpec); 4128 4129 // C++ [base.class.init]p2: 4130 // Unless the mem-initializer-id names a nonstatic data member of the 4131 // constructor's class or a direct or virtual base of that class, the 4132 // mem-initializer is ill-formed. 4133 if (!DirectBaseSpec && !VirtualBaseSpec) { 4134 // If the class has any dependent bases, then it's possible that 4135 // one of those types will resolve to the same type as 4136 // BaseType. Therefore, just treat this as a dependent base 4137 // class initialization. FIXME: Should we try to check the 4138 // initialization anyway? It seems odd. 4139 if (ClassDecl->hasAnyDependentBases()) 4140 Dependent = true; 4141 else 4142 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4143 << BaseType << Context.getTypeDeclType(ClassDecl) 4144 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4145 } 4146 } 4147 4148 if (Dependent) { 4149 DiscardCleanupsInEvaluationContext(); 4150 4151 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4152 /*IsVirtual=*/false, 4153 InitRange.getBegin(), Init, 4154 InitRange.getEnd(), EllipsisLoc); 4155 } 4156 4157 // C++ [base.class.init]p2: 4158 // If a mem-initializer-id is ambiguous because it designates both 4159 // a direct non-virtual base class and an inherited virtual base 4160 // class, the mem-initializer is ill-formed. 4161 if (DirectBaseSpec && VirtualBaseSpec) 4162 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4163 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4164 4165 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4166 if (!BaseSpec) 4167 BaseSpec = VirtualBaseSpec; 4168 4169 // Initialize the base. 4170 bool InitList = true; 4171 MultiExprArg Args = Init; 4172 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4173 InitList = false; 4174 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4175 } 4176 4177 InitializedEntity BaseEntity = 4178 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4179 InitializationKind Kind = 4180 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4181 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4182 InitRange.getEnd()); 4183 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4184 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4185 if (BaseInit.isInvalid()) 4186 return true; 4187 4188 // C++11 [class.base.init]p7: 4189 // The initialization of each base and member constitutes a 4190 // full-expression. 4191 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4192 if (BaseInit.isInvalid()) 4193 return true; 4194 4195 // If we are in a dependent context, template instantiation will 4196 // perform this type-checking again. Just save the arguments that we 4197 // received in a ParenListExpr. 4198 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4199 // of the information that we have about the base 4200 // initializer. However, deconstructing the ASTs is a dicey process, 4201 // and this approach is far more likely to get the corner cases right. 4202 if (CurContext->isDependentContext()) 4203 BaseInit = Init; 4204 4205 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4206 BaseSpec->isVirtual(), 4207 InitRange.getBegin(), 4208 BaseInit.getAs<Expr>(), 4209 InitRange.getEnd(), EllipsisLoc); 4210 } 4211 4212 // Create a static_cast\<T&&>(expr). 4213 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4214 if (T.isNull()) T = E->getType(); 4215 QualType TargetType = SemaRef.BuildReferenceType( 4216 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4217 SourceLocation ExprLoc = E->getLocStart(); 4218 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4219 TargetType, ExprLoc); 4220 4221 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4222 SourceRange(ExprLoc, ExprLoc), 4223 E->getSourceRange()).get(); 4224 } 4225 4226 /// ImplicitInitializerKind - How an implicit base or member initializer should 4227 /// initialize its base or member. 4228 enum ImplicitInitializerKind { 4229 IIK_Default, 4230 IIK_Copy, 4231 IIK_Move, 4232 IIK_Inherit 4233 }; 4234 4235 static bool 4236 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4237 ImplicitInitializerKind ImplicitInitKind, 4238 CXXBaseSpecifier *BaseSpec, 4239 bool IsInheritedVirtualBase, 4240 CXXCtorInitializer *&CXXBaseInit) { 4241 InitializedEntity InitEntity 4242 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4243 IsInheritedVirtualBase); 4244 4245 ExprResult BaseInit; 4246 4247 switch (ImplicitInitKind) { 4248 case IIK_Inherit: 4249 case IIK_Default: { 4250 InitializationKind InitKind 4251 = InitializationKind::CreateDefault(Constructor->getLocation()); 4252 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4253 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4254 break; 4255 } 4256 4257 case IIK_Move: 4258 case IIK_Copy: { 4259 bool Moving = ImplicitInitKind == IIK_Move; 4260 ParmVarDecl *Param = Constructor->getParamDecl(0); 4261 QualType ParamType = Param->getType().getNonReferenceType(); 4262 4263 Expr *CopyCtorArg = 4264 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4265 SourceLocation(), Param, false, 4266 Constructor->getLocation(), ParamType, 4267 VK_LValue, nullptr); 4268 4269 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4270 4271 // Cast to the base class to avoid ambiguities. 4272 QualType ArgTy = 4273 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4274 ParamType.getQualifiers()); 4275 4276 if (Moving) { 4277 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4278 } 4279 4280 CXXCastPath BasePath; 4281 BasePath.push_back(BaseSpec); 4282 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4283 CK_UncheckedDerivedToBase, 4284 Moving ? VK_XValue : VK_LValue, 4285 &BasePath).get(); 4286 4287 InitializationKind InitKind 4288 = InitializationKind::CreateDirect(Constructor->getLocation(), 4289 SourceLocation(), SourceLocation()); 4290 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4291 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4292 break; 4293 } 4294 } 4295 4296 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4297 if (BaseInit.isInvalid()) 4298 return true; 4299 4300 CXXBaseInit = 4301 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4302 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4303 SourceLocation()), 4304 BaseSpec->isVirtual(), 4305 SourceLocation(), 4306 BaseInit.getAs<Expr>(), 4307 SourceLocation(), 4308 SourceLocation()); 4309 4310 return false; 4311 } 4312 4313 static bool RefersToRValueRef(Expr *MemRef) { 4314 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4315 return Referenced->getType()->isRValueReferenceType(); 4316 } 4317 4318 static bool 4319 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4320 ImplicitInitializerKind ImplicitInitKind, 4321 FieldDecl *Field, IndirectFieldDecl *Indirect, 4322 CXXCtorInitializer *&CXXMemberInit) { 4323 if (Field->isInvalidDecl()) 4324 return true; 4325 4326 SourceLocation Loc = Constructor->getLocation(); 4327 4328 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4329 bool Moving = ImplicitInitKind == IIK_Move; 4330 ParmVarDecl *Param = Constructor->getParamDecl(0); 4331 QualType ParamType = Param->getType().getNonReferenceType(); 4332 4333 // Suppress copying zero-width bitfields. 4334 if (Field->isZeroLengthBitField(SemaRef.Context)) 4335 return false; 4336 4337 Expr *MemberExprBase = 4338 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4339 SourceLocation(), Param, false, 4340 Loc, ParamType, VK_LValue, nullptr); 4341 4342 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4343 4344 if (Moving) { 4345 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4346 } 4347 4348 // Build a reference to this field within the parameter. 4349 CXXScopeSpec SS; 4350 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4351 Sema::LookupMemberName); 4352 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4353 : cast<ValueDecl>(Field), AS_public); 4354 MemberLookup.resolveKind(); 4355 ExprResult CtorArg 4356 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4357 ParamType, Loc, 4358 /*IsArrow=*/false, 4359 SS, 4360 /*TemplateKWLoc=*/SourceLocation(), 4361 /*FirstQualifierInScope=*/nullptr, 4362 MemberLookup, 4363 /*TemplateArgs=*/nullptr, 4364 /*S*/nullptr); 4365 if (CtorArg.isInvalid()) 4366 return true; 4367 4368 // C++11 [class.copy]p15: 4369 // - if a member m has rvalue reference type T&&, it is direct-initialized 4370 // with static_cast<T&&>(x.m); 4371 if (RefersToRValueRef(CtorArg.get())) { 4372 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4373 } 4374 4375 InitializedEntity Entity = 4376 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4377 /*Implicit*/ true) 4378 : InitializedEntity::InitializeMember(Field, nullptr, 4379 /*Implicit*/ true); 4380 4381 // Direct-initialize to use the copy constructor. 4382 InitializationKind InitKind = 4383 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4384 4385 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4386 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4387 ExprResult MemberInit = 4388 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4389 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4390 if (MemberInit.isInvalid()) 4391 return true; 4392 4393 if (Indirect) 4394 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4395 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4396 else 4397 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4398 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4399 return false; 4400 } 4401 4402 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4403 "Unhandled implicit init kind!"); 4404 4405 QualType FieldBaseElementType = 4406 SemaRef.Context.getBaseElementType(Field->getType()); 4407 4408 if (FieldBaseElementType->isRecordType()) { 4409 InitializedEntity InitEntity = 4410 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4411 /*Implicit*/ true) 4412 : InitializedEntity::InitializeMember(Field, nullptr, 4413 /*Implicit*/ true); 4414 InitializationKind InitKind = 4415 InitializationKind::CreateDefault(Loc); 4416 4417 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4418 ExprResult MemberInit = 4419 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4420 4421 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4422 if (MemberInit.isInvalid()) 4423 return true; 4424 4425 if (Indirect) 4426 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4427 Indirect, Loc, 4428 Loc, 4429 MemberInit.get(), 4430 Loc); 4431 else 4432 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4433 Field, Loc, Loc, 4434 MemberInit.get(), 4435 Loc); 4436 return false; 4437 } 4438 4439 if (!Field->getParent()->isUnion()) { 4440 if (FieldBaseElementType->isReferenceType()) { 4441 SemaRef.Diag(Constructor->getLocation(), 4442 diag::err_uninitialized_member_in_ctor) 4443 << (int)Constructor->isImplicit() 4444 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4445 << 0 << Field->getDeclName(); 4446 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4447 return true; 4448 } 4449 4450 if (FieldBaseElementType.isConstQualified()) { 4451 SemaRef.Diag(Constructor->getLocation(), 4452 diag::err_uninitialized_member_in_ctor) 4453 << (int)Constructor->isImplicit() 4454 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4455 << 1 << Field->getDeclName(); 4456 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4457 return true; 4458 } 4459 } 4460 4461 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4462 // ARC and Weak: 4463 // Default-initialize Objective-C pointers to NULL. 4464 CXXMemberInit 4465 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4466 Loc, Loc, 4467 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4468 Loc); 4469 return false; 4470 } 4471 4472 // Nothing to initialize. 4473 CXXMemberInit = nullptr; 4474 return false; 4475 } 4476 4477 namespace { 4478 struct BaseAndFieldInfo { 4479 Sema &S; 4480 CXXConstructorDecl *Ctor; 4481 bool AnyErrorsInInits; 4482 ImplicitInitializerKind IIK; 4483 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4484 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4485 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4486 4487 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4488 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4489 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4490 if (Ctor->getInheritedConstructor()) 4491 IIK = IIK_Inherit; 4492 else if (Generated && Ctor->isCopyConstructor()) 4493 IIK = IIK_Copy; 4494 else if (Generated && Ctor->isMoveConstructor()) 4495 IIK = IIK_Move; 4496 else 4497 IIK = IIK_Default; 4498 } 4499 4500 bool isImplicitCopyOrMove() const { 4501 switch (IIK) { 4502 case IIK_Copy: 4503 case IIK_Move: 4504 return true; 4505 4506 case IIK_Default: 4507 case IIK_Inherit: 4508 return false; 4509 } 4510 4511 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4512 } 4513 4514 bool addFieldInitializer(CXXCtorInitializer *Init) { 4515 AllToInit.push_back(Init); 4516 4517 // Check whether this initializer makes the field "used". 4518 if (Init->getInit()->HasSideEffects(S.Context)) 4519 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4520 4521 return false; 4522 } 4523 4524 bool isInactiveUnionMember(FieldDecl *Field) { 4525 RecordDecl *Record = Field->getParent(); 4526 if (!Record->isUnion()) 4527 return false; 4528 4529 if (FieldDecl *Active = 4530 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4531 return Active != Field->getCanonicalDecl(); 4532 4533 // In an implicit copy or move constructor, ignore any in-class initializer. 4534 if (isImplicitCopyOrMove()) 4535 return true; 4536 4537 // If there's no explicit initialization, the field is active only if it 4538 // has an in-class initializer... 4539 if (Field->hasInClassInitializer()) 4540 return false; 4541 // ... or it's an anonymous struct or union whose class has an in-class 4542 // initializer. 4543 if (!Field->isAnonymousStructOrUnion()) 4544 return true; 4545 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4546 return !FieldRD->hasInClassInitializer(); 4547 } 4548 4549 /// Determine whether the given field is, or is within, a union member 4550 /// that is inactive (because there was an initializer given for a different 4551 /// member of the union, or because the union was not initialized at all). 4552 bool isWithinInactiveUnionMember(FieldDecl *Field, 4553 IndirectFieldDecl *Indirect) { 4554 if (!Indirect) 4555 return isInactiveUnionMember(Field); 4556 4557 for (auto *C : Indirect->chain()) { 4558 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4559 if (Field && isInactiveUnionMember(Field)) 4560 return true; 4561 } 4562 return false; 4563 } 4564 }; 4565 } 4566 4567 /// Determine whether the given type is an incomplete or zero-lenfgth 4568 /// array type. 4569 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4570 if (T->isIncompleteArrayType()) 4571 return true; 4572 4573 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4574 if (!ArrayT->getSize()) 4575 return true; 4576 4577 T = ArrayT->getElementType(); 4578 } 4579 4580 return false; 4581 } 4582 4583 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4584 FieldDecl *Field, 4585 IndirectFieldDecl *Indirect = nullptr) { 4586 if (Field->isInvalidDecl()) 4587 return false; 4588 4589 // Overwhelmingly common case: we have a direct initializer for this field. 4590 if (CXXCtorInitializer *Init = 4591 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4592 return Info.addFieldInitializer(Init); 4593 4594 // C++11 [class.base.init]p8: 4595 // if the entity is a non-static data member that has a 4596 // brace-or-equal-initializer and either 4597 // -- the constructor's class is a union and no other variant member of that 4598 // union is designated by a mem-initializer-id or 4599 // -- the constructor's class is not a union, and, if the entity is a member 4600 // of an anonymous union, no other member of that union is designated by 4601 // a mem-initializer-id, 4602 // the entity is initialized as specified in [dcl.init]. 4603 // 4604 // We also apply the same rules to handle anonymous structs within anonymous 4605 // unions. 4606 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4607 return false; 4608 4609 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4610 ExprResult DIE = 4611 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4612 if (DIE.isInvalid()) 4613 return true; 4614 4615 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4616 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4617 4618 CXXCtorInitializer *Init; 4619 if (Indirect) 4620 Init = new (SemaRef.Context) 4621 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4622 SourceLocation(), DIE.get(), SourceLocation()); 4623 else 4624 Init = new (SemaRef.Context) 4625 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4626 SourceLocation(), DIE.get(), SourceLocation()); 4627 return Info.addFieldInitializer(Init); 4628 } 4629 4630 // Don't initialize incomplete or zero-length arrays. 4631 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4632 return false; 4633 4634 // Don't try to build an implicit initializer if there were semantic 4635 // errors in any of the initializers (and therefore we might be 4636 // missing some that the user actually wrote). 4637 if (Info.AnyErrorsInInits) 4638 return false; 4639 4640 CXXCtorInitializer *Init = nullptr; 4641 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4642 Indirect, Init)) 4643 return true; 4644 4645 if (!Init) 4646 return false; 4647 4648 return Info.addFieldInitializer(Init); 4649 } 4650 4651 bool 4652 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4653 CXXCtorInitializer *Initializer) { 4654 assert(Initializer->isDelegatingInitializer()); 4655 Constructor->setNumCtorInitializers(1); 4656 CXXCtorInitializer **initializer = 4657 new (Context) CXXCtorInitializer*[1]; 4658 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4659 Constructor->setCtorInitializers(initializer); 4660 4661 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4662 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4663 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4664 } 4665 4666 DelegatingCtorDecls.push_back(Constructor); 4667 4668 DiagnoseUninitializedFields(*this, Constructor); 4669 4670 return false; 4671 } 4672 4673 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4674 ArrayRef<CXXCtorInitializer *> Initializers) { 4675 if (Constructor->isDependentContext()) { 4676 // Just store the initializers as written, they will be checked during 4677 // instantiation. 4678 if (!Initializers.empty()) { 4679 Constructor->setNumCtorInitializers(Initializers.size()); 4680 CXXCtorInitializer **baseOrMemberInitializers = 4681 new (Context) CXXCtorInitializer*[Initializers.size()]; 4682 memcpy(baseOrMemberInitializers, Initializers.data(), 4683 Initializers.size() * sizeof(CXXCtorInitializer*)); 4684 Constructor->setCtorInitializers(baseOrMemberInitializers); 4685 } 4686 4687 // Let template instantiation know whether we had errors. 4688 if (AnyErrors) 4689 Constructor->setInvalidDecl(); 4690 4691 return false; 4692 } 4693 4694 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4695 4696 // We need to build the initializer AST according to order of construction 4697 // and not what user specified in the Initializers list. 4698 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4699 if (!ClassDecl) 4700 return true; 4701 4702 bool HadError = false; 4703 4704 for (unsigned i = 0; i < Initializers.size(); i++) { 4705 CXXCtorInitializer *Member = Initializers[i]; 4706 4707 if (Member->isBaseInitializer()) 4708 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4709 else { 4710 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4711 4712 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4713 for (auto *C : F->chain()) { 4714 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4715 if (FD && FD->getParent()->isUnion()) 4716 Info.ActiveUnionMember.insert(std::make_pair( 4717 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4718 } 4719 } else if (FieldDecl *FD = Member->getMember()) { 4720 if (FD->getParent()->isUnion()) 4721 Info.ActiveUnionMember.insert(std::make_pair( 4722 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4723 } 4724 } 4725 } 4726 4727 // Keep track of the direct virtual bases. 4728 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4729 for (auto &I : ClassDecl->bases()) { 4730 if (I.isVirtual()) 4731 DirectVBases.insert(&I); 4732 } 4733 4734 // Push virtual bases before others. 4735 for (auto &VBase : ClassDecl->vbases()) { 4736 if (CXXCtorInitializer *Value 4737 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4738 // [class.base.init]p7, per DR257: 4739 // A mem-initializer where the mem-initializer-id names a virtual base 4740 // class is ignored during execution of a constructor of any class that 4741 // is not the most derived class. 4742 if (ClassDecl->isAbstract()) { 4743 // FIXME: Provide a fixit to remove the base specifier. This requires 4744 // tracking the location of the associated comma for a base specifier. 4745 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4746 << VBase.getType() << ClassDecl; 4747 DiagnoseAbstractType(ClassDecl); 4748 } 4749 4750 Info.AllToInit.push_back(Value); 4751 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4752 // [class.base.init]p8, per DR257: 4753 // If a given [...] base class is not named by a mem-initializer-id 4754 // [...] and the entity is not a virtual base class of an abstract 4755 // class, then [...] the entity is default-initialized. 4756 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4757 CXXCtorInitializer *CXXBaseInit; 4758 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4759 &VBase, IsInheritedVirtualBase, 4760 CXXBaseInit)) { 4761 HadError = true; 4762 continue; 4763 } 4764 4765 Info.AllToInit.push_back(CXXBaseInit); 4766 } 4767 } 4768 4769 // Non-virtual bases. 4770 for (auto &Base : ClassDecl->bases()) { 4771 // Virtuals are in the virtual base list and already constructed. 4772 if (Base.isVirtual()) 4773 continue; 4774 4775 if (CXXCtorInitializer *Value 4776 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4777 Info.AllToInit.push_back(Value); 4778 } else if (!AnyErrors) { 4779 CXXCtorInitializer *CXXBaseInit; 4780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4781 &Base, /*IsInheritedVirtualBase=*/false, 4782 CXXBaseInit)) { 4783 HadError = true; 4784 continue; 4785 } 4786 4787 Info.AllToInit.push_back(CXXBaseInit); 4788 } 4789 } 4790 4791 // Fields. 4792 for (auto *Mem : ClassDecl->decls()) { 4793 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4794 // C++ [class.bit]p2: 4795 // A declaration for a bit-field that omits the identifier declares an 4796 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4797 // initialized. 4798 if (F->isUnnamedBitfield()) 4799 continue; 4800 4801 // If we're not generating the implicit copy/move constructor, then we'll 4802 // handle anonymous struct/union fields based on their individual 4803 // indirect fields. 4804 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4805 continue; 4806 4807 if (CollectFieldInitializer(*this, Info, F)) 4808 HadError = true; 4809 continue; 4810 } 4811 4812 // Beyond this point, we only consider default initialization. 4813 if (Info.isImplicitCopyOrMove()) 4814 continue; 4815 4816 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4817 if (F->getType()->isIncompleteArrayType()) { 4818 assert(ClassDecl->hasFlexibleArrayMember() && 4819 "Incomplete array type is not valid"); 4820 continue; 4821 } 4822 4823 // Initialize each field of an anonymous struct individually. 4824 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4825 HadError = true; 4826 4827 continue; 4828 } 4829 } 4830 4831 unsigned NumInitializers = Info.AllToInit.size(); 4832 if (NumInitializers > 0) { 4833 Constructor->setNumCtorInitializers(NumInitializers); 4834 CXXCtorInitializer **baseOrMemberInitializers = 4835 new (Context) CXXCtorInitializer*[NumInitializers]; 4836 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4837 NumInitializers * sizeof(CXXCtorInitializer*)); 4838 Constructor->setCtorInitializers(baseOrMemberInitializers); 4839 4840 // Constructors implicitly reference the base and member 4841 // destructors. 4842 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4843 Constructor->getParent()); 4844 } 4845 4846 return HadError; 4847 } 4848 4849 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4850 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4851 const RecordDecl *RD = RT->getDecl(); 4852 if (RD->isAnonymousStructOrUnion()) { 4853 for (auto *Field : RD->fields()) 4854 PopulateKeysForFields(Field, IdealInits); 4855 return; 4856 } 4857 } 4858 IdealInits.push_back(Field->getCanonicalDecl()); 4859 } 4860 4861 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4862 return Context.getCanonicalType(BaseType).getTypePtr(); 4863 } 4864 4865 static const void *GetKeyForMember(ASTContext &Context, 4866 CXXCtorInitializer *Member) { 4867 if (!Member->isAnyMemberInitializer()) 4868 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4869 4870 return Member->getAnyMember()->getCanonicalDecl(); 4871 } 4872 4873 static void DiagnoseBaseOrMemInitializerOrder( 4874 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4875 ArrayRef<CXXCtorInitializer *> Inits) { 4876 if (Constructor->getDeclContext()->isDependentContext()) 4877 return; 4878 4879 // Don't check initializers order unless the warning is enabled at the 4880 // location of at least one initializer. 4881 bool ShouldCheckOrder = false; 4882 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4883 CXXCtorInitializer *Init = Inits[InitIndex]; 4884 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4885 Init->getSourceLocation())) { 4886 ShouldCheckOrder = true; 4887 break; 4888 } 4889 } 4890 if (!ShouldCheckOrder) 4891 return; 4892 4893 // Build the list of bases and members in the order that they'll 4894 // actually be initialized. The explicit initializers should be in 4895 // this same order but may be missing things. 4896 SmallVector<const void*, 32> IdealInitKeys; 4897 4898 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4899 4900 // 1. Virtual bases. 4901 for (const auto &VBase : ClassDecl->vbases()) 4902 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4903 4904 // 2. Non-virtual bases. 4905 for (const auto &Base : ClassDecl->bases()) { 4906 if (Base.isVirtual()) 4907 continue; 4908 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4909 } 4910 4911 // 3. Direct fields. 4912 for (auto *Field : ClassDecl->fields()) { 4913 if (Field->isUnnamedBitfield()) 4914 continue; 4915 4916 PopulateKeysForFields(Field, IdealInitKeys); 4917 } 4918 4919 unsigned NumIdealInits = IdealInitKeys.size(); 4920 unsigned IdealIndex = 0; 4921 4922 CXXCtorInitializer *PrevInit = nullptr; 4923 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4924 CXXCtorInitializer *Init = Inits[InitIndex]; 4925 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4926 4927 // Scan forward to try to find this initializer in the idealized 4928 // initializers list. 4929 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4930 if (InitKey == IdealInitKeys[IdealIndex]) 4931 break; 4932 4933 // If we didn't find this initializer, it must be because we 4934 // scanned past it on a previous iteration. That can only 4935 // happen if we're out of order; emit a warning. 4936 if (IdealIndex == NumIdealInits && PrevInit) { 4937 Sema::SemaDiagnosticBuilder D = 4938 SemaRef.Diag(PrevInit->getSourceLocation(), 4939 diag::warn_initializer_out_of_order); 4940 4941 if (PrevInit->isAnyMemberInitializer()) 4942 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4943 else 4944 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4945 4946 if (Init->isAnyMemberInitializer()) 4947 D << 0 << Init->getAnyMember()->getDeclName(); 4948 else 4949 D << 1 << Init->getTypeSourceInfo()->getType(); 4950 4951 // Move back to the initializer's location in the ideal list. 4952 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4953 if (InitKey == IdealInitKeys[IdealIndex]) 4954 break; 4955 4956 assert(IdealIndex < NumIdealInits && 4957 "initializer not found in initializer list"); 4958 } 4959 4960 PrevInit = Init; 4961 } 4962 } 4963 4964 namespace { 4965 bool CheckRedundantInit(Sema &S, 4966 CXXCtorInitializer *Init, 4967 CXXCtorInitializer *&PrevInit) { 4968 if (!PrevInit) { 4969 PrevInit = Init; 4970 return false; 4971 } 4972 4973 if (FieldDecl *Field = Init->getAnyMember()) 4974 S.Diag(Init->getSourceLocation(), 4975 diag::err_multiple_mem_initialization) 4976 << Field->getDeclName() 4977 << Init->getSourceRange(); 4978 else { 4979 const Type *BaseClass = Init->getBaseClass(); 4980 assert(BaseClass && "neither field nor base"); 4981 S.Diag(Init->getSourceLocation(), 4982 diag::err_multiple_base_initialization) 4983 << QualType(BaseClass, 0) 4984 << Init->getSourceRange(); 4985 } 4986 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4987 << 0 << PrevInit->getSourceRange(); 4988 4989 return true; 4990 } 4991 4992 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4993 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4994 4995 bool CheckRedundantUnionInit(Sema &S, 4996 CXXCtorInitializer *Init, 4997 RedundantUnionMap &Unions) { 4998 FieldDecl *Field = Init->getAnyMember(); 4999 RecordDecl *Parent = Field->getParent(); 5000 NamedDecl *Child = Field; 5001 5002 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5003 if (Parent->isUnion()) { 5004 UnionEntry &En = Unions[Parent]; 5005 if (En.first && En.first != Child) { 5006 S.Diag(Init->getSourceLocation(), 5007 diag::err_multiple_mem_union_initialization) 5008 << Field->getDeclName() 5009 << Init->getSourceRange(); 5010 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5011 << 0 << En.second->getSourceRange(); 5012 return true; 5013 } 5014 if (!En.first) { 5015 En.first = Child; 5016 En.second = Init; 5017 } 5018 if (!Parent->isAnonymousStructOrUnion()) 5019 return false; 5020 } 5021 5022 Child = Parent; 5023 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5024 } 5025 5026 return false; 5027 } 5028 } 5029 5030 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5031 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5032 SourceLocation ColonLoc, 5033 ArrayRef<CXXCtorInitializer*> MemInits, 5034 bool AnyErrors) { 5035 if (!ConstructorDecl) 5036 return; 5037 5038 AdjustDeclIfTemplate(ConstructorDecl); 5039 5040 CXXConstructorDecl *Constructor 5041 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5042 5043 if (!Constructor) { 5044 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5045 return; 5046 } 5047 5048 // Mapping for the duplicate initializers check. 5049 // For member initializers, this is keyed with a FieldDecl*. 5050 // For base initializers, this is keyed with a Type*. 5051 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5052 5053 // Mapping for the inconsistent anonymous-union initializers check. 5054 RedundantUnionMap MemberUnions; 5055 5056 bool HadError = false; 5057 for (unsigned i = 0; i < MemInits.size(); i++) { 5058 CXXCtorInitializer *Init = MemInits[i]; 5059 5060 // Set the source order index. 5061 Init->setSourceOrder(i); 5062 5063 if (Init->isAnyMemberInitializer()) { 5064 const void *Key = GetKeyForMember(Context, Init); 5065 if (CheckRedundantInit(*this, Init, Members[Key]) || 5066 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5067 HadError = true; 5068 } else if (Init->isBaseInitializer()) { 5069 const void *Key = GetKeyForMember(Context, Init); 5070 if (CheckRedundantInit(*this, Init, Members[Key])) 5071 HadError = true; 5072 } else { 5073 assert(Init->isDelegatingInitializer()); 5074 // This must be the only initializer 5075 if (MemInits.size() != 1) { 5076 Diag(Init->getSourceLocation(), 5077 diag::err_delegating_initializer_alone) 5078 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5079 // We will treat this as being the only initializer. 5080 } 5081 SetDelegatingInitializer(Constructor, MemInits[i]); 5082 // Return immediately as the initializer is set. 5083 return; 5084 } 5085 } 5086 5087 if (HadError) 5088 return; 5089 5090 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5091 5092 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5093 5094 DiagnoseUninitializedFields(*this, Constructor); 5095 } 5096 5097 void 5098 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5099 CXXRecordDecl *ClassDecl) { 5100 // Ignore dependent contexts. Also ignore unions, since their members never 5101 // have destructors implicitly called. 5102 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5103 return; 5104 5105 // FIXME: all the access-control diagnostics are positioned on the 5106 // field/base declaration. That's probably good; that said, the 5107 // user might reasonably want to know why the destructor is being 5108 // emitted, and we currently don't say. 5109 5110 // Non-static data members. 5111 for (auto *Field : ClassDecl->fields()) { 5112 if (Field->isInvalidDecl()) 5113 continue; 5114 5115 // Don't destroy incomplete or zero-length arrays. 5116 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5117 continue; 5118 5119 QualType FieldType = Context.getBaseElementType(Field->getType()); 5120 5121 const RecordType* RT = FieldType->getAs<RecordType>(); 5122 if (!RT) 5123 continue; 5124 5125 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5126 if (FieldClassDecl->isInvalidDecl()) 5127 continue; 5128 if (FieldClassDecl->hasIrrelevantDestructor()) 5129 continue; 5130 // The destructor for an implicit anonymous union member is never invoked. 5131 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5132 continue; 5133 5134 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5135 assert(Dtor && "No dtor found for FieldClassDecl!"); 5136 CheckDestructorAccess(Field->getLocation(), Dtor, 5137 PDiag(diag::err_access_dtor_field) 5138 << Field->getDeclName() 5139 << FieldType); 5140 5141 MarkFunctionReferenced(Location, Dtor); 5142 DiagnoseUseOfDecl(Dtor, Location); 5143 } 5144 5145 // We only potentially invoke the destructors of potentially constructed 5146 // subobjects. 5147 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5148 5149 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5150 5151 // Bases. 5152 for (const auto &Base : ClassDecl->bases()) { 5153 // Bases are always records in a well-formed non-dependent class. 5154 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5155 5156 // Remember direct virtual bases. 5157 if (Base.isVirtual()) { 5158 if (!VisitVirtualBases) 5159 continue; 5160 DirectVirtualBases.insert(RT); 5161 } 5162 5163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5164 // If our base class is invalid, we probably can't get its dtor anyway. 5165 if (BaseClassDecl->isInvalidDecl()) 5166 continue; 5167 if (BaseClassDecl->hasIrrelevantDestructor()) 5168 continue; 5169 5170 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5171 assert(Dtor && "No dtor found for BaseClassDecl!"); 5172 5173 // FIXME: caret should be on the start of the class name 5174 CheckDestructorAccess(Base.getLocStart(), Dtor, 5175 PDiag(diag::err_access_dtor_base) 5176 << Base.getType() 5177 << Base.getSourceRange(), 5178 Context.getTypeDeclType(ClassDecl)); 5179 5180 MarkFunctionReferenced(Location, Dtor); 5181 DiagnoseUseOfDecl(Dtor, Location); 5182 } 5183 5184 if (!VisitVirtualBases) 5185 return; 5186 5187 // Virtual bases. 5188 for (const auto &VBase : ClassDecl->vbases()) { 5189 // Bases are always records in a well-formed non-dependent class. 5190 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5191 5192 // Ignore direct virtual bases. 5193 if (DirectVirtualBases.count(RT)) 5194 continue; 5195 5196 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5197 // If our base class is invalid, we probably can't get its dtor anyway. 5198 if (BaseClassDecl->isInvalidDecl()) 5199 continue; 5200 if (BaseClassDecl->hasIrrelevantDestructor()) 5201 continue; 5202 5203 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5204 assert(Dtor && "No dtor found for BaseClassDecl!"); 5205 if (CheckDestructorAccess( 5206 ClassDecl->getLocation(), Dtor, 5207 PDiag(diag::err_access_dtor_vbase) 5208 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5209 Context.getTypeDeclType(ClassDecl)) == 5210 AR_accessible) { 5211 CheckDerivedToBaseConversion( 5212 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5213 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5214 SourceRange(), DeclarationName(), nullptr); 5215 } 5216 5217 MarkFunctionReferenced(Location, Dtor); 5218 DiagnoseUseOfDecl(Dtor, Location); 5219 } 5220 } 5221 5222 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5223 if (!CDtorDecl) 5224 return; 5225 5226 if (CXXConstructorDecl *Constructor 5227 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5228 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5229 DiagnoseUninitializedFields(*this, Constructor); 5230 } 5231 } 5232 5233 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5234 if (!getLangOpts().CPlusPlus) 5235 return false; 5236 5237 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5238 if (!RD) 5239 return false; 5240 5241 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5242 // class template specialization here, but doing so breaks a lot of code. 5243 5244 // We can't answer whether something is abstract until it has a 5245 // definition. If it's currently being defined, we'll walk back 5246 // over all the declarations when we have a full definition. 5247 const CXXRecordDecl *Def = RD->getDefinition(); 5248 if (!Def || Def->isBeingDefined()) 5249 return false; 5250 5251 return RD->isAbstract(); 5252 } 5253 5254 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5255 TypeDiagnoser &Diagnoser) { 5256 if (!isAbstractType(Loc, T)) 5257 return false; 5258 5259 T = Context.getBaseElementType(T); 5260 Diagnoser.diagnose(*this, Loc, T); 5261 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5262 return true; 5263 } 5264 5265 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5266 // Check if we've already emitted the list of pure virtual functions 5267 // for this class. 5268 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5269 return; 5270 5271 // If the diagnostic is suppressed, don't emit the notes. We're only 5272 // going to emit them once, so try to attach them to a diagnostic we're 5273 // actually going to show. 5274 if (Diags.isLastDiagnosticIgnored()) 5275 return; 5276 5277 CXXFinalOverriderMap FinalOverriders; 5278 RD->getFinalOverriders(FinalOverriders); 5279 5280 // Keep a set of seen pure methods so we won't diagnose the same method 5281 // more than once. 5282 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5283 5284 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5285 MEnd = FinalOverriders.end(); 5286 M != MEnd; 5287 ++M) { 5288 for (OverridingMethods::iterator SO = M->second.begin(), 5289 SOEnd = M->second.end(); 5290 SO != SOEnd; ++SO) { 5291 // C++ [class.abstract]p4: 5292 // A class is abstract if it contains or inherits at least one 5293 // pure virtual function for which the final overrider is pure 5294 // virtual. 5295 5296 // 5297 if (SO->second.size() != 1) 5298 continue; 5299 5300 if (!SO->second.front().Method->isPure()) 5301 continue; 5302 5303 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5304 continue; 5305 5306 Diag(SO->second.front().Method->getLocation(), 5307 diag::note_pure_virtual_function) 5308 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5309 } 5310 } 5311 5312 if (!PureVirtualClassDiagSet) 5313 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5314 PureVirtualClassDiagSet->insert(RD); 5315 } 5316 5317 namespace { 5318 struct AbstractUsageInfo { 5319 Sema &S; 5320 CXXRecordDecl *Record; 5321 CanQualType AbstractType; 5322 bool Invalid; 5323 5324 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5325 : S(S), Record(Record), 5326 AbstractType(S.Context.getCanonicalType( 5327 S.Context.getTypeDeclType(Record))), 5328 Invalid(false) {} 5329 5330 void DiagnoseAbstractType() { 5331 if (Invalid) return; 5332 S.DiagnoseAbstractType(Record); 5333 Invalid = true; 5334 } 5335 5336 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5337 }; 5338 5339 struct CheckAbstractUsage { 5340 AbstractUsageInfo &Info; 5341 const NamedDecl *Ctx; 5342 5343 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5344 : Info(Info), Ctx(Ctx) {} 5345 5346 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5347 switch (TL.getTypeLocClass()) { 5348 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5349 #define TYPELOC(CLASS, PARENT) \ 5350 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5351 #include "clang/AST/TypeLocNodes.def" 5352 } 5353 } 5354 5355 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5356 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5357 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5358 if (!TL.getParam(I)) 5359 continue; 5360 5361 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5362 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5363 } 5364 } 5365 5366 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5367 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5368 } 5369 5370 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5371 // Visit the type parameters from a permissive context. 5372 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5373 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5374 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5375 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5376 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5377 // TODO: other template argument types? 5378 } 5379 } 5380 5381 // Visit pointee types from a permissive context. 5382 #define CheckPolymorphic(Type) \ 5383 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5384 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5385 } 5386 CheckPolymorphic(PointerTypeLoc) 5387 CheckPolymorphic(ReferenceTypeLoc) 5388 CheckPolymorphic(MemberPointerTypeLoc) 5389 CheckPolymorphic(BlockPointerTypeLoc) 5390 CheckPolymorphic(AtomicTypeLoc) 5391 5392 /// Handle all the types we haven't given a more specific 5393 /// implementation for above. 5394 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5395 // Every other kind of type that we haven't called out already 5396 // that has an inner type is either (1) sugar or (2) contains that 5397 // inner type in some way as a subobject. 5398 if (TypeLoc Next = TL.getNextTypeLoc()) 5399 return Visit(Next, Sel); 5400 5401 // If there's no inner type and we're in a permissive context, 5402 // don't diagnose. 5403 if (Sel == Sema::AbstractNone) return; 5404 5405 // Check whether the type matches the abstract type. 5406 QualType T = TL.getType(); 5407 if (T->isArrayType()) { 5408 Sel = Sema::AbstractArrayType; 5409 T = Info.S.Context.getBaseElementType(T); 5410 } 5411 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5412 if (CT != Info.AbstractType) return; 5413 5414 // It matched; do some magic. 5415 if (Sel == Sema::AbstractArrayType) { 5416 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5417 << T << TL.getSourceRange(); 5418 } else { 5419 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5420 << Sel << T << TL.getSourceRange(); 5421 } 5422 Info.DiagnoseAbstractType(); 5423 } 5424 }; 5425 5426 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5427 Sema::AbstractDiagSelID Sel) { 5428 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5429 } 5430 5431 } 5432 5433 /// Check for invalid uses of an abstract type in a method declaration. 5434 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5435 CXXMethodDecl *MD) { 5436 // No need to do the check on definitions, which require that 5437 // the return/param types be complete. 5438 if (MD->doesThisDeclarationHaveABody()) 5439 return; 5440 5441 // For safety's sake, just ignore it if we don't have type source 5442 // information. This should never happen for non-implicit methods, 5443 // but... 5444 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5445 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5446 } 5447 5448 /// Check for invalid uses of an abstract type within a class definition. 5449 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5450 CXXRecordDecl *RD) { 5451 for (auto *D : RD->decls()) { 5452 if (D->isImplicit()) continue; 5453 5454 // Methods and method templates. 5455 if (isa<CXXMethodDecl>(D)) { 5456 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5457 } else if (isa<FunctionTemplateDecl>(D)) { 5458 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5459 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5460 5461 // Fields and static variables. 5462 } else if (isa<FieldDecl>(D)) { 5463 FieldDecl *FD = cast<FieldDecl>(D); 5464 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5465 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5466 } else if (isa<VarDecl>(D)) { 5467 VarDecl *VD = cast<VarDecl>(D); 5468 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5469 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5470 5471 // Nested classes and class templates. 5472 } else if (isa<CXXRecordDecl>(D)) { 5473 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5474 } else if (isa<ClassTemplateDecl>(D)) { 5475 CheckAbstractClassUsage(Info, 5476 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5477 } 5478 } 5479 } 5480 5481 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5482 Attr *ClassAttr = getDLLAttr(Class); 5483 if (!ClassAttr) 5484 return; 5485 5486 assert(ClassAttr->getKind() == attr::DLLExport); 5487 5488 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5489 5490 if (TSK == TSK_ExplicitInstantiationDeclaration) 5491 // Don't go any further if this is just an explicit instantiation 5492 // declaration. 5493 return; 5494 5495 for (Decl *Member : Class->decls()) { 5496 // Defined static variables that are members of an exported base 5497 // class must be marked export too. 5498 auto *VD = dyn_cast<VarDecl>(Member); 5499 if (VD && Member->getAttr<DLLExportAttr>() && 5500 VD->getStorageClass() == SC_Static && 5501 TSK == TSK_ImplicitInstantiation) 5502 S.MarkVariableReferenced(VD->getLocation(), VD); 5503 5504 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5505 if (!MD) 5506 continue; 5507 5508 if (Member->getAttr<DLLExportAttr>()) { 5509 if (MD->isUserProvided()) { 5510 // Instantiate non-default class member functions ... 5511 5512 // .. except for certain kinds of template specializations. 5513 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5514 continue; 5515 5516 S.MarkFunctionReferenced(Class->getLocation(), MD); 5517 5518 // The function will be passed to the consumer when its definition is 5519 // encountered. 5520 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5521 MD->isCopyAssignmentOperator() || 5522 MD->isMoveAssignmentOperator()) { 5523 // Synthesize and instantiate non-trivial implicit methods, explicitly 5524 // defaulted methods, and the copy and move assignment operators. The 5525 // latter are exported even if they are trivial, because the address of 5526 // an operator can be taken and should compare equal across libraries. 5527 DiagnosticErrorTrap Trap(S.Diags); 5528 S.MarkFunctionReferenced(Class->getLocation(), MD); 5529 if (Trap.hasErrorOccurred()) { 5530 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5531 << Class << !S.getLangOpts().CPlusPlus11; 5532 break; 5533 } 5534 5535 // There is no later point when we will see the definition of this 5536 // function, so pass it to the consumer now. 5537 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5538 } 5539 } 5540 } 5541 } 5542 5543 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5544 CXXRecordDecl *Class) { 5545 // Only the MS ABI has default constructor closures, so we don't need to do 5546 // this semantic checking anywhere else. 5547 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5548 return; 5549 5550 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5551 for (Decl *Member : Class->decls()) { 5552 // Look for exported default constructors. 5553 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5554 if (!CD || !CD->isDefaultConstructor()) 5555 continue; 5556 auto *Attr = CD->getAttr<DLLExportAttr>(); 5557 if (!Attr) 5558 continue; 5559 5560 // If the class is non-dependent, mark the default arguments as ODR-used so 5561 // that we can properly codegen the constructor closure. 5562 if (!Class->isDependentContext()) { 5563 for (ParmVarDecl *PD : CD->parameters()) { 5564 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5565 S.DiscardCleanupsInEvaluationContext(); 5566 } 5567 } 5568 5569 if (LastExportedDefaultCtor) { 5570 S.Diag(LastExportedDefaultCtor->getLocation(), 5571 diag::err_attribute_dll_ambiguous_default_ctor) 5572 << Class; 5573 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5574 << CD->getDeclName(); 5575 return; 5576 } 5577 LastExportedDefaultCtor = CD; 5578 } 5579 } 5580 5581 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5582 // Mark any compiler-generated routines with the implicit code_seg attribute. 5583 for (auto *Method : Class->methods()) { 5584 if (Method->isUserProvided()) 5585 continue; 5586 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5587 Method->addAttr(A); 5588 } 5589 } 5590 5591 /// Check class-level dllimport/dllexport attribute. 5592 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5593 Attr *ClassAttr = getDLLAttr(Class); 5594 5595 // MSVC inherits DLL attributes to partial class template specializations. 5596 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5597 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5598 if (Attr *TemplateAttr = 5599 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5600 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5601 A->setInherited(true); 5602 ClassAttr = A; 5603 } 5604 } 5605 } 5606 5607 if (!ClassAttr) 5608 return; 5609 5610 if (!Class->isExternallyVisible()) { 5611 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5612 << Class << ClassAttr; 5613 return; 5614 } 5615 5616 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5617 !ClassAttr->isInherited()) { 5618 // Diagnose dll attributes on members of class with dll attribute. 5619 for (Decl *Member : Class->decls()) { 5620 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5621 continue; 5622 InheritableAttr *MemberAttr = getDLLAttr(Member); 5623 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5624 continue; 5625 5626 Diag(MemberAttr->getLocation(), 5627 diag::err_attribute_dll_member_of_dll_class) 5628 << MemberAttr << ClassAttr; 5629 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5630 Member->setInvalidDecl(); 5631 } 5632 } 5633 5634 if (Class->getDescribedClassTemplate()) 5635 // Don't inherit dll attribute until the template is instantiated. 5636 return; 5637 5638 // The class is either imported or exported. 5639 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5640 5641 // Check if this was a dllimport attribute propagated from a derived class to 5642 // a base class template specialization. We don't apply these attributes to 5643 // static data members. 5644 const bool PropagatedImport = 5645 !ClassExported && 5646 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5647 5648 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5649 5650 // Ignore explicit dllexport on explicit class template instantiation declarations. 5651 if (ClassExported && !ClassAttr->isInherited() && 5652 TSK == TSK_ExplicitInstantiationDeclaration) { 5653 Class->dropAttr<DLLExportAttr>(); 5654 return; 5655 } 5656 5657 // Force declaration of implicit members so they can inherit the attribute. 5658 ForceDeclarationOfImplicitMembers(Class); 5659 5660 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5661 // seem to be true in practice? 5662 5663 for (Decl *Member : Class->decls()) { 5664 VarDecl *VD = dyn_cast<VarDecl>(Member); 5665 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5666 5667 // Only methods and static fields inherit the attributes. 5668 if (!VD && !MD) 5669 continue; 5670 5671 if (MD) { 5672 // Don't process deleted methods. 5673 if (MD->isDeleted()) 5674 continue; 5675 5676 if (MD->isInlined()) { 5677 // MinGW does not import or export inline methods. 5678 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5679 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5680 continue; 5681 5682 // MSVC versions before 2015 don't export the move assignment operators 5683 // and move constructor, so don't attempt to import/export them if 5684 // we have a definition. 5685 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5686 if ((MD->isMoveAssignmentOperator() || 5687 (Ctor && Ctor->isMoveConstructor())) && 5688 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5689 continue; 5690 5691 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5692 // operator is exported anyway. 5693 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5694 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5695 continue; 5696 } 5697 } 5698 5699 // Don't apply dllimport attributes to static data members of class template 5700 // instantiations when the attribute is propagated from a derived class. 5701 if (VD && PropagatedImport) 5702 continue; 5703 5704 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5705 continue; 5706 5707 if (!getDLLAttr(Member)) { 5708 auto *NewAttr = 5709 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5710 NewAttr->setInherited(true); 5711 Member->addAttr(NewAttr); 5712 5713 if (MD) { 5714 // Propagate DLLAttr to friend re-declarations of MD that have already 5715 // been constructed. 5716 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5717 FD = FD->getPreviousDecl()) { 5718 if (FD->getFriendObjectKind() == Decl::FOK_None) 5719 continue; 5720 assert(!getDLLAttr(FD) && 5721 "friend re-decl should not already have a DLLAttr"); 5722 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5723 NewAttr->setInherited(true); 5724 FD->addAttr(NewAttr); 5725 } 5726 } 5727 } 5728 } 5729 5730 if (ClassExported) 5731 DelayedDllExportClasses.push_back(Class); 5732 } 5733 5734 /// Perform propagation of DLL attributes from a derived class to a 5735 /// templated base class for MS compatibility. 5736 void Sema::propagateDLLAttrToBaseClassTemplate( 5737 CXXRecordDecl *Class, Attr *ClassAttr, 5738 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5739 if (getDLLAttr( 5740 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5741 // If the base class template has a DLL attribute, don't try to change it. 5742 return; 5743 } 5744 5745 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5746 if (!getDLLAttr(BaseTemplateSpec) && 5747 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5748 TSK == TSK_ImplicitInstantiation)) { 5749 // The template hasn't been instantiated yet (or it has, but only as an 5750 // explicit instantiation declaration or implicit instantiation, which means 5751 // we haven't codegenned any members yet), so propagate the attribute. 5752 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5753 NewAttr->setInherited(true); 5754 BaseTemplateSpec->addAttr(NewAttr); 5755 5756 // If this was an import, mark that we propagated it from a derived class to 5757 // a base class template specialization. 5758 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5759 ImportAttr->setPropagatedToBaseTemplate(); 5760 5761 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5762 // needs to be run again to work see the new attribute. Otherwise this will 5763 // get run whenever the template is instantiated. 5764 if (TSK != TSK_Undeclared) 5765 checkClassLevelDLLAttribute(BaseTemplateSpec); 5766 5767 return; 5768 } 5769 5770 if (getDLLAttr(BaseTemplateSpec)) { 5771 // The template has already been specialized or instantiated with an 5772 // attribute, explicitly or through propagation. We should not try to change 5773 // it. 5774 return; 5775 } 5776 5777 // The template was previously instantiated or explicitly specialized without 5778 // a dll attribute, It's too late for us to add an attribute, so warn that 5779 // this is unsupported. 5780 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5781 << BaseTemplateSpec->isExplicitSpecialization(); 5782 Diag(ClassAttr->getLocation(), diag::note_attribute); 5783 if (BaseTemplateSpec->isExplicitSpecialization()) { 5784 Diag(BaseTemplateSpec->getLocation(), 5785 diag::note_template_class_explicit_specialization_was_here) 5786 << BaseTemplateSpec; 5787 } else { 5788 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5789 diag::note_template_class_instantiation_was_here) 5790 << BaseTemplateSpec; 5791 } 5792 } 5793 5794 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5795 SourceLocation DefaultLoc) { 5796 switch (S.getSpecialMember(MD)) { 5797 case Sema::CXXDefaultConstructor: 5798 S.DefineImplicitDefaultConstructor(DefaultLoc, 5799 cast<CXXConstructorDecl>(MD)); 5800 break; 5801 case Sema::CXXCopyConstructor: 5802 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5803 break; 5804 case Sema::CXXCopyAssignment: 5805 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5806 break; 5807 case Sema::CXXDestructor: 5808 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5809 break; 5810 case Sema::CXXMoveConstructor: 5811 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5812 break; 5813 case Sema::CXXMoveAssignment: 5814 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5815 break; 5816 case Sema::CXXInvalid: 5817 llvm_unreachable("Invalid special member."); 5818 } 5819 } 5820 5821 /// Determine whether a type is permitted to be passed or returned in 5822 /// registers, per C++ [class.temporary]p3. 5823 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 5824 TargetInfo::CallingConvKind CCK) { 5825 if (D->isDependentType() || D->isInvalidDecl()) 5826 return false; 5827 5828 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5829 // The PS4 platform ABI follows the behavior of Clang 3.2. 5830 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5831 return !D->hasNonTrivialDestructorForCall() && 5832 !D->hasNonTrivialCopyConstructorForCall(); 5833 5834 if (CCK == TargetInfo::CCK_MicrosoftX86_64) { 5835 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5836 bool DtorIsTrivialForCall = false; 5837 5838 // If a class has at least one non-deleted, trivial copy constructor, it 5839 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5840 // 5841 // Note: This permits classes with non-trivial copy or move ctors to be 5842 // passed in registers, so long as they *also* have a trivial copy ctor, 5843 // which is non-conforming. 5844 if (D->needsImplicitCopyConstructor()) { 5845 if (!D->defaultedCopyConstructorIsDeleted()) { 5846 if (D->hasTrivialCopyConstructor()) 5847 CopyCtorIsTrivial = true; 5848 if (D->hasTrivialCopyConstructorForCall()) 5849 CopyCtorIsTrivialForCall = true; 5850 } 5851 } else { 5852 for (const CXXConstructorDecl *CD : D->ctors()) { 5853 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5854 if (CD->isTrivial()) 5855 CopyCtorIsTrivial = true; 5856 if (CD->isTrivialForCall()) 5857 CopyCtorIsTrivialForCall = true; 5858 } 5859 } 5860 } 5861 5862 if (D->needsImplicitDestructor()) { 5863 if (!D->defaultedDestructorIsDeleted() && 5864 D->hasTrivialDestructorForCall()) 5865 DtorIsTrivialForCall = true; 5866 } else if (const auto *DD = D->getDestructor()) { 5867 if (!DD->isDeleted() && DD->isTrivialForCall()) 5868 DtorIsTrivialForCall = true; 5869 } 5870 5871 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5872 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5873 return true; 5874 5875 // If a class has a destructor, we'd really like to pass it indirectly 5876 // because it allows us to elide copies. Unfortunately, MSVC makes that 5877 // impossible for small types, which it will pass in a single register or 5878 // stack slot. Most objects with dtors are large-ish, so handle that early. 5879 // We can't call out all large objects as being indirect because there are 5880 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5881 // how we pass large POD types. 5882 5883 // Note: This permits small classes with nontrivial destructors to be 5884 // passed in registers, which is non-conforming. 5885 if (CopyCtorIsTrivial && 5886 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64) 5887 return true; 5888 return false; 5889 } 5890 5891 // Per C++ [class.temporary]p3, the relevant condition is: 5892 // each copy constructor, move constructor, and destructor of X is 5893 // either trivial or deleted, and X has at least one non-deleted copy 5894 // or move constructor 5895 bool HasNonDeletedCopyOrMove = false; 5896 5897 if (D->needsImplicitCopyConstructor() && 5898 !D->defaultedCopyConstructorIsDeleted()) { 5899 if (!D->hasTrivialCopyConstructorForCall()) 5900 return false; 5901 HasNonDeletedCopyOrMove = true; 5902 } 5903 5904 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5905 !D->defaultedMoveConstructorIsDeleted()) { 5906 if (!D->hasTrivialMoveConstructorForCall()) 5907 return false; 5908 HasNonDeletedCopyOrMove = true; 5909 } 5910 5911 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5912 !D->hasTrivialDestructorForCall()) 5913 return false; 5914 5915 for (const CXXMethodDecl *MD : D->methods()) { 5916 if (MD->isDeleted()) 5917 continue; 5918 5919 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5920 if (CD && CD->isCopyOrMoveConstructor()) 5921 HasNonDeletedCopyOrMove = true; 5922 else if (!isa<CXXDestructorDecl>(MD)) 5923 continue; 5924 5925 if (!MD->isTrivialForCall()) 5926 return false; 5927 } 5928 5929 return HasNonDeletedCopyOrMove; 5930 } 5931 5932 /// Perform semantic checks on a class definition that has been 5933 /// completing, introducing implicitly-declared members, checking for 5934 /// abstract types, etc. 5935 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5936 if (!Record) 5937 return; 5938 5939 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5940 AbstractUsageInfo Info(*this, Record); 5941 CheckAbstractClassUsage(Info, Record); 5942 } 5943 5944 // If this is not an aggregate type and has no user-declared constructor, 5945 // complain about any non-static data members of reference or const scalar 5946 // type, since they will never get initializers. 5947 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5948 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5949 !Record->isLambda()) { 5950 bool Complained = false; 5951 for (const auto *F : Record->fields()) { 5952 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5953 continue; 5954 5955 if (F->getType()->isReferenceType() || 5956 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5957 if (!Complained) { 5958 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5959 << Record->getTagKind() << Record; 5960 Complained = true; 5961 } 5962 5963 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5964 << F->getType()->isReferenceType() 5965 << F->getDeclName(); 5966 } 5967 } 5968 } 5969 5970 if (Record->getIdentifier()) { 5971 // C++ [class.mem]p13: 5972 // If T is the name of a class, then each of the following shall have a 5973 // name different from T: 5974 // - every member of every anonymous union that is a member of class T. 5975 // 5976 // C++ [class.mem]p14: 5977 // In addition, if class T has a user-declared constructor (12.1), every 5978 // non-static data member of class T shall have a name different from T. 5979 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5980 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5981 ++I) { 5982 NamedDecl *D = (*I)->getUnderlyingDecl(); 5983 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 5984 Record->hasUserDeclaredConstructor()) || 5985 isa<IndirectFieldDecl>(D)) { 5986 Diag((*I)->getLocation(), diag::err_member_name_of_class) 5987 << D->getDeclName(); 5988 break; 5989 } 5990 } 5991 } 5992 5993 // Warn if the class has virtual methods but non-virtual public destructor. 5994 if (Record->isPolymorphic() && !Record->isDependentType()) { 5995 CXXDestructorDecl *dtor = Record->getDestructor(); 5996 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5997 !Record->hasAttr<FinalAttr>()) 5998 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5999 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6000 } 6001 6002 if (Record->isAbstract()) { 6003 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6004 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6005 << FA->isSpelledAsSealed(); 6006 DiagnoseAbstractType(Record); 6007 } 6008 } 6009 6010 // See if trivial_abi has to be dropped. 6011 if (Record->hasAttr<TrivialABIAttr>()) 6012 checkIllFormedTrivialABIStruct(*Record); 6013 6014 // Set HasTrivialSpecialMemberForCall if the record has attribute 6015 // "trivial_abi". 6016 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6017 6018 if (HasTrivialABI) 6019 Record->setHasTrivialSpecialMemberForCall(); 6020 6021 bool HasMethodWithOverrideControl = false, 6022 HasOverridingMethodWithoutOverrideControl = false; 6023 if (!Record->isDependentType()) { 6024 for (auto *M : Record->methods()) { 6025 // See if a method overloads virtual methods in a base 6026 // class without overriding any. 6027 if (!M->isStatic()) 6028 DiagnoseHiddenVirtualMethods(M); 6029 if (M->hasAttr<OverrideAttr>()) 6030 HasMethodWithOverrideControl = true; 6031 else if (M->size_overridden_methods() > 0) 6032 HasOverridingMethodWithoutOverrideControl = true; 6033 // Check whether the explicitly-defaulted special members are valid. 6034 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6035 CheckExplicitlyDefaultedSpecialMember(M); 6036 6037 // For an explicitly defaulted or deleted special member, we defer 6038 // determining triviality until the class is complete. That time is now! 6039 CXXSpecialMember CSM = getSpecialMember(M); 6040 if (!M->isImplicit() && !M->isUserProvided()) { 6041 if (CSM != CXXInvalid) { 6042 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6043 // Inform the class that we've finished declaring this member. 6044 Record->finishedDefaultedOrDeletedMember(M); 6045 M->setTrivialForCall( 6046 HasTrivialABI || 6047 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6048 Record->setTrivialForCallFlags(M); 6049 } 6050 } 6051 6052 // Set triviality for the purpose of calls if this is a user-provided 6053 // copy/move constructor or destructor. 6054 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6055 CSM == CXXDestructor) && M->isUserProvided()) { 6056 M->setTrivialForCall(HasTrivialABI); 6057 Record->setTrivialForCallFlags(M); 6058 } 6059 6060 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6061 M->hasAttr<DLLExportAttr>()) { 6062 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6063 M->isTrivial() && 6064 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6065 CSM == CXXDestructor)) 6066 M->dropAttr<DLLExportAttr>(); 6067 6068 if (M->hasAttr<DLLExportAttr>()) { 6069 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6070 ActOnFinishInlineFunctionDef(M); 6071 } 6072 } 6073 } 6074 } 6075 6076 if (HasMethodWithOverrideControl && 6077 HasOverridingMethodWithoutOverrideControl) { 6078 // At least one method has the 'override' control declared. 6079 // Diagnose all other overridden methods which do not have 'override' specified on them. 6080 for (auto *M : Record->methods()) 6081 DiagnoseAbsenceOfOverrideControl(M); 6082 } 6083 6084 // ms_struct is a request to use the same ABI rules as MSVC. Check 6085 // whether this class uses any C++ features that are implemented 6086 // completely differently in MSVC, and if so, emit a diagnostic. 6087 // That diagnostic defaults to an error, but we allow projects to 6088 // map it down to a warning (or ignore it). It's a fairly common 6089 // practice among users of the ms_struct pragma to mass-annotate 6090 // headers, sweeping up a bunch of types that the project doesn't 6091 // really rely on MSVC-compatible layout for. We must therefore 6092 // support "ms_struct except for C++ stuff" as a secondary ABI. 6093 if (Record->isMsStruct(Context) && 6094 (Record->isPolymorphic() || Record->getNumBases())) { 6095 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6096 } 6097 6098 checkClassLevelDLLAttribute(Record); 6099 checkClassLevelCodeSegAttribute(Record); 6100 6101 bool ClangABICompat4 = 6102 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6103 TargetInfo::CallingConvKind CCK = 6104 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6105 bool CanPass = canPassInRegisters(*this, Record, CCK); 6106 6107 // Do not change ArgPassingRestrictions if it has already been set to 6108 // APK_CanNeverPassInRegs. 6109 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6110 Record->setArgPassingRestrictions(CanPass 6111 ? RecordDecl::APK_CanPassInRegs 6112 : RecordDecl::APK_CannotPassInRegs); 6113 6114 // If canPassInRegisters returns true despite the record having a non-trivial 6115 // destructor, the record is destructed in the callee. This happens only when 6116 // the record or one of its subobjects has a field annotated with trivial_abi 6117 // or a field qualified with ObjC __strong/__weak. 6118 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6119 Record->setParamDestroyedInCallee(true); 6120 else if (Record->hasNonTrivialDestructor()) 6121 Record->setParamDestroyedInCallee(CanPass); 6122 6123 if (getLangOpts().ForceEmitVTables) { 6124 // If we want to emit all the vtables, we need to mark it as used. This 6125 // is especially required for cases like vtable assumption loads. 6126 MarkVTableUsed(Record->getInnerLocStart(), Record); 6127 } 6128 } 6129 6130 /// Look up the special member function that would be called by a special 6131 /// member function for a subobject of class type. 6132 /// 6133 /// \param Class The class type of the subobject. 6134 /// \param CSM The kind of special member function. 6135 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6136 /// \param ConstRHS True if this is a copy operation with a const object 6137 /// on its RHS, that is, if the argument to the outer special member 6138 /// function is 'const' and this is not a field marked 'mutable'. 6139 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6140 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6141 unsigned FieldQuals, bool ConstRHS) { 6142 unsigned LHSQuals = 0; 6143 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6144 LHSQuals = FieldQuals; 6145 6146 unsigned RHSQuals = FieldQuals; 6147 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6148 RHSQuals = 0; 6149 else if (ConstRHS) 6150 RHSQuals |= Qualifiers::Const; 6151 6152 return S.LookupSpecialMember(Class, CSM, 6153 RHSQuals & Qualifiers::Const, 6154 RHSQuals & Qualifiers::Volatile, 6155 false, 6156 LHSQuals & Qualifiers::Const, 6157 LHSQuals & Qualifiers::Volatile); 6158 } 6159 6160 class Sema::InheritedConstructorInfo { 6161 Sema &S; 6162 SourceLocation UseLoc; 6163 6164 /// A mapping from the base classes through which the constructor was 6165 /// inherited to the using shadow declaration in that base class (or a null 6166 /// pointer if the constructor was declared in that base class). 6167 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6168 InheritedFromBases; 6169 6170 public: 6171 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6172 ConstructorUsingShadowDecl *Shadow) 6173 : S(S), UseLoc(UseLoc) { 6174 bool DiagnosedMultipleConstructedBases = false; 6175 CXXRecordDecl *ConstructedBase = nullptr; 6176 UsingDecl *ConstructedBaseUsing = nullptr; 6177 6178 // Find the set of such base class subobjects and check that there's a 6179 // unique constructed subobject. 6180 for (auto *D : Shadow->redecls()) { 6181 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6182 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6183 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6184 6185 InheritedFromBases.insert( 6186 std::make_pair(DNominatedBase->getCanonicalDecl(), 6187 DShadow->getNominatedBaseClassShadowDecl())); 6188 if (DShadow->constructsVirtualBase()) 6189 InheritedFromBases.insert( 6190 std::make_pair(DConstructedBase->getCanonicalDecl(), 6191 DShadow->getConstructedBaseClassShadowDecl())); 6192 else 6193 assert(DNominatedBase == DConstructedBase); 6194 6195 // [class.inhctor.init]p2: 6196 // If the constructor was inherited from multiple base class subobjects 6197 // of type B, the program is ill-formed. 6198 if (!ConstructedBase) { 6199 ConstructedBase = DConstructedBase; 6200 ConstructedBaseUsing = D->getUsingDecl(); 6201 } else if (ConstructedBase != DConstructedBase && 6202 !Shadow->isInvalidDecl()) { 6203 if (!DiagnosedMultipleConstructedBases) { 6204 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6205 << Shadow->getTargetDecl(); 6206 S.Diag(ConstructedBaseUsing->getLocation(), 6207 diag::note_ambiguous_inherited_constructor_using) 6208 << ConstructedBase; 6209 DiagnosedMultipleConstructedBases = true; 6210 } 6211 S.Diag(D->getUsingDecl()->getLocation(), 6212 diag::note_ambiguous_inherited_constructor_using) 6213 << DConstructedBase; 6214 } 6215 } 6216 6217 if (DiagnosedMultipleConstructedBases) 6218 Shadow->setInvalidDecl(); 6219 } 6220 6221 /// Find the constructor to use for inherited construction of a base class, 6222 /// and whether that base class constructor inherits the constructor from a 6223 /// virtual base class (in which case it won't actually invoke it). 6224 std::pair<CXXConstructorDecl *, bool> 6225 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6226 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6227 if (It == InheritedFromBases.end()) 6228 return std::make_pair(nullptr, false); 6229 6230 // This is an intermediary class. 6231 if (It->second) 6232 return std::make_pair( 6233 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6234 It->second->constructsVirtualBase()); 6235 6236 // This is the base class from which the constructor was inherited. 6237 return std::make_pair(Ctor, false); 6238 } 6239 }; 6240 6241 /// Is the special member function which would be selected to perform the 6242 /// specified operation on the specified class type a constexpr constructor? 6243 static bool 6244 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6245 Sema::CXXSpecialMember CSM, unsigned Quals, 6246 bool ConstRHS, 6247 CXXConstructorDecl *InheritedCtor = nullptr, 6248 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6249 // If we're inheriting a constructor, see if we need to call it for this base 6250 // class. 6251 if (InheritedCtor) { 6252 assert(CSM == Sema::CXXDefaultConstructor); 6253 auto BaseCtor = 6254 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6255 if (BaseCtor) 6256 return BaseCtor->isConstexpr(); 6257 } 6258 6259 if (CSM == Sema::CXXDefaultConstructor) 6260 return ClassDecl->hasConstexprDefaultConstructor(); 6261 6262 Sema::SpecialMemberOverloadResult SMOR = 6263 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6264 if (!SMOR.getMethod()) 6265 // A constructor we wouldn't select can't be "involved in initializing" 6266 // anything. 6267 return true; 6268 return SMOR.getMethod()->isConstexpr(); 6269 } 6270 6271 /// Determine whether the specified special member function would be constexpr 6272 /// if it were implicitly defined. 6273 static bool defaultedSpecialMemberIsConstexpr( 6274 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6275 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6276 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6277 if (!S.getLangOpts().CPlusPlus11) 6278 return false; 6279 6280 // C++11 [dcl.constexpr]p4: 6281 // In the definition of a constexpr constructor [...] 6282 bool Ctor = true; 6283 switch (CSM) { 6284 case Sema::CXXDefaultConstructor: 6285 if (Inherited) 6286 break; 6287 // Since default constructor lookup is essentially trivial (and cannot 6288 // involve, for instance, template instantiation), we compute whether a 6289 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6290 // 6291 // This is important for performance; we need to know whether the default 6292 // constructor is constexpr to determine whether the type is a literal type. 6293 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6294 6295 case Sema::CXXCopyConstructor: 6296 case Sema::CXXMoveConstructor: 6297 // For copy or move constructors, we need to perform overload resolution. 6298 break; 6299 6300 case Sema::CXXCopyAssignment: 6301 case Sema::CXXMoveAssignment: 6302 if (!S.getLangOpts().CPlusPlus14) 6303 return false; 6304 // In C++1y, we need to perform overload resolution. 6305 Ctor = false; 6306 break; 6307 6308 case Sema::CXXDestructor: 6309 case Sema::CXXInvalid: 6310 return false; 6311 } 6312 6313 // -- if the class is a non-empty union, or for each non-empty anonymous 6314 // union member of a non-union class, exactly one non-static data member 6315 // shall be initialized; [DR1359] 6316 // 6317 // If we squint, this is guaranteed, since exactly one non-static data member 6318 // will be initialized (if the constructor isn't deleted), we just don't know 6319 // which one. 6320 if (Ctor && ClassDecl->isUnion()) 6321 return CSM == Sema::CXXDefaultConstructor 6322 ? ClassDecl->hasInClassInitializer() || 6323 !ClassDecl->hasVariantMembers() 6324 : true; 6325 6326 // -- the class shall not have any virtual base classes; 6327 if (Ctor && ClassDecl->getNumVBases()) 6328 return false; 6329 6330 // C++1y [class.copy]p26: 6331 // -- [the class] is a literal type, and 6332 if (!Ctor && !ClassDecl->isLiteral()) 6333 return false; 6334 6335 // -- every constructor involved in initializing [...] base class 6336 // sub-objects shall be a constexpr constructor; 6337 // -- the assignment operator selected to copy/move each direct base 6338 // class is a constexpr function, and 6339 for (const auto &B : ClassDecl->bases()) { 6340 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6341 if (!BaseType) continue; 6342 6343 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6344 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6345 InheritedCtor, Inherited)) 6346 return false; 6347 } 6348 6349 // -- every constructor involved in initializing non-static data members 6350 // [...] shall be a constexpr constructor; 6351 // -- every non-static data member and base class sub-object shall be 6352 // initialized 6353 // -- for each non-static data member of X that is of class type (or array 6354 // thereof), the assignment operator selected to copy/move that member is 6355 // a constexpr function 6356 for (const auto *F : ClassDecl->fields()) { 6357 if (F->isInvalidDecl()) 6358 continue; 6359 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6360 continue; 6361 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6362 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6363 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6364 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6365 BaseType.getCVRQualifiers(), 6366 ConstArg && !F->isMutable())) 6367 return false; 6368 } else if (CSM == Sema::CXXDefaultConstructor) { 6369 return false; 6370 } 6371 } 6372 6373 // All OK, it's constexpr! 6374 return true; 6375 } 6376 6377 static Sema::ImplicitExceptionSpecification 6378 ComputeDefaultedSpecialMemberExceptionSpec( 6379 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6380 Sema::InheritedConstructorInfo *ICI); 6381 6382 static Sema::ImplicitExceptionSpecification 6383 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6384 auto CSM = S.getSpecialMember(MD); 6385 if (CSM != Sema::CXXInvalid) 6386 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6387 6388 auto *CD = cast<CXXConstructorDecl>(MD); 6389 assert(CD->getInheritedConstructor() && 6390 "only special members have implicit exception specs"); 6391 Sema::InheritedConstructorInfo ICI( 6392 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6393 return ComputeDefaultedSpecialMemberExceptionSpec( 6394 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6395 } 6396 6397 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6398 CXXMethodDecl *MD) { 6399 FunctionProtoType::ExtProtoInfo EPI; 6400 6401 // Build an exception specification pointing back at this member. 6402 EPI.ExceptionSpec.Type = EST_Unevaluated; 6403 EPI.ExceptionSpec.SourceDecl = MD; 6404 6405 // Set the calling convention to the default for C++ instance methods. 6406 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6407 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6408 /*IsCXXMethod=*/true)); 6409 return EPI; 6410 } 6411 6412 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6413 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6414 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6415 return; 6416 6417 // Evaluate the exception specification. 6418 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6419 auto ESI = IES.getExceptionSpec(); 6420 6421 // Update the type of the special member to use it. 6422 UpdateExceptionSpec(MD, ESI); 6423 6424 // A user-provided destructor can be defined outside the class. When that 6425 // happens, be sure to update the exception specification on both 6426 // declarations. 6427 const FunctionProtoType *CanonicalFPT = 6428 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6429 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6430 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6431 } 6432 6433 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6434 CXXRecordDecl *RD = MD->getParent(); 6435 CXXSpecialMember CSM = getSpecialMember(MD); 6436 6437 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6438 "not an explicitly-defaulted special member"); 6439 6440 // Whether this was the first-declared instance of the constructor. 6441 // This affects whether we implicitly add an exception spec and constexpr. 6442 bool First = MD == MD->getCanonicalDecl(); 6443 6444 bool HadError = false; 6445 6446 // C++11 [dcl.fct.def.default]p1: 6447 // A function that is explicitly defaulted shall 6448 // -- be a special member function (checked elsewhere), 6449 // -- have the same type (except for ref-qualifiers, and except that a 6450 // copy operation can take a non-const reference) as an implicit 6451 // declaration, and 6452 // -- not have default arguments. 6453 unsigned ExpectedParams = 1; 6454 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6455 ExpectedParams = 0; 6456 if (MD->getNumParams() != ExpectedParams) { 6457 // This also checks for default arguments: a copy or move constructor with a 6458 // default argument is classified as a default constructor, and assignment 6459 // operations and destructors can't have default arguments. 6460 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6461 << CSM << MD->getSourceRange(); 6462 HadError = true; 6463 } else if (MD->isVariadic()) { 6464 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6465 << CSM << MD->getSourceRange(); 6466 HadError = true; 6467 } 6468 6469 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6470 6471 bool CanHaveConstParam = false; 6472 if (CSM == CXXCopyConstructor) 6473 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6474 else if (CSM == CXXCopyAssignment) 6475 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6476 6477 QualType ReturnType = Context.VoidTy; 6478 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6479 // Check for return type matching. 6480 ReturnType = Type->getReturnType(); 6481 QualType ExpectedReturnType = 6482 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6483 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6484 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6485 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6486 HadError = true; 6487 } 6488 6489 // A defaulted special member cannot have cv-qualifiers. 6490 if (Type->getTypeQuals()) { 6491 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6492 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6493 HadError = true; 6494 } 6495 } 6496 6497 // Check for parameter type matching. 6498 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6499 bool HasConstParam = false; 6500 if (ExpectedParams && ArgType->isReferenceType()) { 6501 // Argument must be reference to possibly-const T. 6502 QualType ReferentType = ArgType->getPointeeType(); 6503 HasConstParam = ReferentType.isConstQualified(); 6504 6505 if (ReferentType.isVolatileQualified()) { 6506 Diag(MD->getLocation(), 6507 diag::err_defaulted_special_member_volatile_param) << CSM; 6508 HadError = true; 6509 } 6510 6511 if (HasConstParam && !CanHaveConstParam) { 6512 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6513 Diag(MD->getLocation(), 6514 diag::err_defaulted_special_member_copy_const_param) 6515 << (CSM == CXXCopyAssignment); 6516 // FIXME: Explain why this special member can't be const. 6517 } else { 6518 Diag(MD->getLocation(), 6519 diag::err_defaulted_special_member_move_const_param) 6520 << (CSM == CXXMoveAssignment); 6521 } 6522 HadError = true; 6523 } 6524 } else if (ExpectedParams) { 6525 // A copy assignment operator can take its argument by value, but a 6526 // defaulted one cannot. 6527 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6528 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6529 HadError = true; 6530 } 6531 6532 // C++11 [dcl.fct.def.default]p2: 6533 // An explicitly-defaulted function may be declared constexpr only if it 6534 // would have been implicitly declared as constexpr, 6535 // Do not apply this rule to members of class templates, since core issue 1358 6536 // makes such functions always instantiate to constexpr functions. For 6537 // functions which cannot be constexpr (for non-constructors in C++11 and for 6538 // destructors in C++1y), this is checked elsewhere. 6539 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6540 HasConstParam); 6541 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6542 : isa<CXXConstructorDecl>(MD)) && 6543 MD->isConstexpr() && !Constexpr && 6544 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6545 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6546 // FIXME: Explain why the special member can't be constexpr. 6547 HadError = true; 6548 } 6549 6550 // and may have an explicit exception-specification only if it is compatible 6551 // with the exception-specification on the implicit declaration. 6552 if (Type->hasExceptionSpec()) { 6553 // Delay the check if this is the first declaration of the special member, 6554 // since we may not have parsed some necessary in-class initializers yet. 6555 if (First) { 6556 // If the exception specification needs to be instantiated, do so now, 6557 // before we clobber it with an EST_Unevaluated specification below. 6558 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6559 InstantiateExceptionSpec(MD->getLocStart(), MD); 6560 Type = MD->getType()->getAs<FunctionProtoType>(); 6561 } 6562 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6563 } else 6564 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6565 } 6566 6567 // If a function is explicitly defaulted on its first declaration, 6568 if (First) { 6569 // -- it is implicitly considered to be constexpr if the implicit 6570 // definition would be, 6571 MD->setConstexpr(Constexpr); 6572 6573 // -- it is implicitly considered to have the same exception-specification 6574 // as if it had been implicitly declared, 6575 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6576 EPI.ExceptionSpec.Type = EST_Unevaluated; 6577 EPI.ExceptionSpec.SourceDecl = MD; 6578 MD->setType(Context.getFunctionType(ReturnType, 6579 llvm::makeArrayRef(&ArgType, 6580 ExpectedParams), 6581 EPI)); 6582 } 6583 6584 if (ShouldDeleteSpecialMember(MD, CSM)) { 6585 if (First) { 6586 SetDeclDeleted(MD, MD->getLocation()); 6587 } else { 6588 // C++11 [dcl.fct.def.default]p4: 6589 // [For a] user-provided explicitly-defaulted function [...] if such a 6590 // function is implicitly defined as deleted, the program is ill-formed. 6591 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6592 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6593 HadError = true; 6594 } 6595 } 6596 6597 if (HadError) 6598 MD->setInvalidDecl(); 6599 } 6600 6601 /// Check whether the exception specification provided for an 6602 /// explicitly-defaulted special member matches the exception specification 6603 /// that would have been generated for an implicit special member, per 6604 /// C++11 [dcl.fct.def.default]p2. 6605 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6606 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6607 // If the exception specification was explicitly specified but hadn't been 6608 // parsed when the method was defaulted, grab it now. 6609 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6610 SpecifiedType = 6611 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6612 6613 // Compute the implicit exception specification. 6614 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6615 /*IsCXXMethod=*/true); 6616 FunctionProtoType::ExtProtoInfo EPI(CC); 6617 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6618 EPI.ExceptionSpec = IES.getExceptionSpec(); 6619 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6620 Context.getFunctionType(Context.VoidTy, None, EPI)); 6621 6622 // Ensure that it matches. 6623 CheckEquivalentExceptionSpec( 6624 PDiag(diag::err_incorrect_defaulted_exception_spec) 6625 << getSpecialMember(MD), PDiag(), 6626 ImplicitType, SourceLocation(), 6627 SpecifiedType, MD->getLocation()); 6628 } 6629 6630 void Sema::CheckDelayedMemberExceptionSpecs() { 6631 decltype(DelayedExceptionSpecChecks) Checks; 6632 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6633 6634 std::swap(Checks, DelayedExceptionSpecChecks); 6635 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6636 6637 // Perform any deferred checking of exception specifications for virtual 6638 // destructors. 6639 for (auto &Check : Checks) 6640 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6641 6642 // Check that any explicitly-defaulted methods have exception specifications 6643 // compatible with their implicit exception specifications. 6644 for (auto &Spec : Specs) 6645 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6646 } 6647 6648 namespace { 6649 /// CRTP base class for visiting operations performed by a special member 6650 /// function (or inherited constructor). 6651 template<typename Derived> 6652 struct SpecialMemberVisitor { 6653 Sema &S; 6654 CXXMethodDecl *MD; 6655 Sema::CXXSpecialMember CSM; 6656 Sema::InheritedConstructorInfo *ICI; 6657 6658 // Properties of the special member, computed for convenience. 6659 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6660 6661 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6662 Sema::InheritedConstructorInfo *ICI) 6663 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6664 switch (CSM) { 6665 case Sema::CXXDefaultConstructor: 6666 case Sema::CXXCopyConstructor: 6667 case Sema::CXXMoveConstructor: 6668 IsConstructor = true; 6669 break; 6670 case Sema::CXXCopyAssignment: 6671 case Sema::CXXMoveAssignment: 6672 IsAssignment = true; 6673 break; 6674 case Sema::CXXDestructor: 6675 break; 6676 case Sema::CXXInvalid: 6677 llvm_unreachable("invalid special member kind"); 6678 } 6679 6680 if (MD->getNumParams()) { 6681 if (const ReferenceType *RT = 6682 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6683 ConstArg = RT->getPointeeType().isConstQualified(); 6684 } 6685 } 6686 6687 Derived &getDerived() { return static_cast<Derived&>(*this); } 6688 6689 /// Is this a "move" special member? 6690 bool isMove() const { 6691 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6692 } 6693 6694 /// Look up the corresponding special member in the given class. 6695 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6696 unsigned Quals, bool IsMutable) { 6697 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6698 ConstArg && !IsMutable); 6699 } 6700 6701 /// Look up the constructor for the specified base class to see if it's 6702 /// overridden due to this being an inherited constructor. 6703 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6704 if (!ICI) 6705 return {}; 6706 assert(CSM == Sema::CXXDefaultConstructor); 6707 auto *BaseCtor = 6708 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6709 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6710 return MD; 6711 return {}; 6712 } 6713 6714 /// A base or member subobject. 6715 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6716 6717 /// Get the location to use for a subobject in diagnostics. 6718 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6719 // FIXME: For an indirect virtual base, the direct base leading to 6720 // the indirect virtual base would be a more useful choice. 6721 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6722 return B->getBaseTypeLoc(); 6723 else 6724 return Subobj.get<FieldDecl*>()->getLocation(); 6725 } 6726 6727 enum BasesToVisit { 6728 /// Visit all non-virtual (direct) bases. 6729 VisitNonVirtualBases, 6730 /// Visit all direct bases, virtual or not. 6731 VisitDirectBases, 6732 /// Visit all non-virtual bases, and all virtual bases if the class 6733 /// is not abstract. 6734 VisitPotentiallyConstructedBases, 6735 /// Visit all direct or virtual bases. 6736 VisitAllBases 6737 }; 6738 6739 // Visit the bases and members of the class. 6740 bool visit(BasesToVisit Bases) { 6741 CXXRecordDecl *RD = MD->getParent(); 6742 6743 if (Bases == VisitPotentiallyConstructedBases) 6744 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6745 6746 for (auto &B : RD->bases()) 6747 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6748 getDerived().visitBase(&B)) 6749 return true; 6750 6751 if (Bases == VisitAllBases) 6752 for (auto &B : RD->vbases()) 6753 if (getDerived().visitBase(&B)) 6754 return true; 6755 6756 for (auto *F : RD->fields()) 6757 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6758 getDerived().visitField(F)) 6759 return true; 6760 6761 return false; 6762 } 6763 }; 6764 } 6765 6766 namespace { 6767 struct SpecialMemberDeletionInfo 6768 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6769 bool Diagnose; 6770 6771 SourceLocation Loc; 6772 6773 bool AllFieldsAreConst; 6774 6775 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6776 Sema::CXXSpecialMember CSM, 6777 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6778 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6779 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6780 6781 bool inUnion() const { return MD->getParent()->isUnion(); } 6782 6783 Sema::CXXSpecialMember getEffectiveCSM() { 6784 return ICI ? Sema::CXXInvalid : CSM; 6785 } 6786 6787 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6788 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6789 6790 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6791 bool shouldDeleteForField(FieldDecl *FD); 6792 bool shouldDeleteForAllConstMembers(); 6793 6794 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6795 unsigned Quals); 6796 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6797 Sema::SpecialMemberOverloadResult SMOR, 6798 bool IsDtorCallInCtor); 6799 6800 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6801 }; 6802 } 6803 6804 /// Is the given special member inaccessible when used on the given 6805 /// sub-object. 6806 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6807 CXXMethodDecl *target) { 6808 /// If we're operating on a base class, the object type is the 6809 /// type of this special member. 6810 QualType objectTy; 6811 AccessSpecifier access = target->getAccess(); 6812 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6813 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6814 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6815 6816 // If we're operating on a field, the object type is the type of the field. 6817 } else { 6818 objectTy = S.Context.getTypeDeclType(target->getParent()); 6819 } 6820 6821 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6822 } 6823 6824 /// Check whether we should delete a special member due to the implicit 6825 /// definition containing a call to a special member of a subobject. 6826 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6827 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6828 bool IsDtorCallInCtor) { 6829 CXXMethodDecl *Decl = SMOR.getMethod(); 6830 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6831 6832 int DiagKind = -1; 6833 6834 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6835 DiagKind = !Decl ? 0 : 1; 6836 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6837 DiagKind = 2; 6838 else if (!isAccessible(Subobj, Decl)) 6839 DiagKind = 3; 6840 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6841 !Decl->isTrivial()) { 6842 // A member of a union must have a trivial corresponding special member. 6843 // As a weird special case, a destructor call from a union's constructor 6844 // must be accessible and non-deleted, but need not be trivial. Such a 6845 // destructor is never actually called, but is semantically checked as 6846 // if it were. 6847 DiagKind = 4; 6848 } 6849 6850 if (DiagKind == -1) 6851 return false; 6852 6853 if (Diagnose) { 6854 if (Field) { 6855 S.Diag(Field->getLocation(), 6856 diag::note_deleted_special_member_class_subobject) 6857 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6858 << Field << DiagKind << IsDtorCallInCtor; 6859 } else { 6860 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6861 S.Diag(Base->getLocStart(), 6862 diag::note_deleted_special_member_class_subobject) 6863 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6864 << Base->getType() << DiagKind << IsDtorCallInCtor; 6865 } 6866 6867 if (DiagKind == 1) 6868 S.NoteDeletedFunction(Decl); 6869 // FIXME: Explain inaccessibility if DiagKind == 3. 6870 } 6871 6872 return true; 6873 } 6874 6875 /// Check whether we should delete a special member function due to having a 6876 /// direct or virtual base class or non-static data member of class type M. 6877 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6878 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6879 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6880 bool IsMutable = Field && Field->isMutable(); 6881 6882 // C++11 [class.ctor]p5: 6883 // -- any direct or virtual base class, or non-static data member with no 6884 // brace-or-equal-initializer, has class type M (or array thereof) and 6885 // either M has no default constructor or overload resolution as applied 6886 // to M's default constructor results in an ambiguity or in a function 6887 // that is deleted or inaccessible 6888 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6889 // -- a direct or virtual base class B that cannot be copied/moved because 6890 // overload resolution, as applied to B's corresponding special member, 6891 // results in an ambiguity or a function that is deleted or inaccessible 6892 // from the defaulted special member 6893 // C++11 [class.dtor]p5: 6894 // -- any direct or virtual base class [...] has a type with a destructor 6895 // that is deleted or inaccessible 6896 if (!(CSM == Sema::CXXDefaultConstructor && 6897 Field && Field->hasInClassInitializer()) && 6898 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6899 false)) 6900 return true; 6901 6902 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6903 // -- any direct or virtual base class or non-static data member has a 6904 // type with a destructor that is deleted or inaccessible 6905 if (IsConstructor) { 6906 Sema::SpecialMemberOverloadResult SMOR = 6907 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6908 false, false, false, false, false); 6909 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6910 return true; 6911 } 6912 6913 return false; 6914 } 6915 6916 /// Check whether we should delete a special member function due to the class 6917 /// having a particular direct or virtual base class. 6918 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6919 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6920 // If program is correct, BaseClass cannot be null, but if it is, the error 6921 // must be reported elsewhere. 6922 if (!BaseClass) 6923 return false; 6924 // If we have an inheriting constructor, check whether we're calling an 6925 // inherited constructor instead of a default constructor. 6926 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6927 if (auto *BaseCtor = SMOR.getMethod()) { 6928 // Note that we do not check access along this path; other than that, 6929 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6930 // FIXME: Check that the base has a usable destructor! Sink this into 6931 // shouldDeleteForClassSubobject. 6932 if (BaseCtor->isDeleted() && Diagnose) { 6933 S.Diag(Base->getLocStart(), 6934 diag::note_deleted_special_member_class_subobject) 6935 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6936 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6937 S.NoteDeletedFunction(BaseCtor); 6938 } 6939 return BaseCtor->isDeleted(); 6940 } 6941 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6942 } 6943 6944 /// Check whether we should delete a special member function due to the class 6945 /// having a particular non-static data member. 6946 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6947 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6948 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6949 6950 if (CSM == Sema::CXXDefaultConstructor) { 6951 // For a default constructor, all references must be initialized in-class 6952 // and, if a union, it must have a non-const member. 6953 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6954 if (Diagnose) 6955 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6956 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6957 return true; 6958 } 6959 // C++11 [class.ctor]p5: any non-variant non-static data member of 6960 // const-qualified type (or array thereof) with no 6961 // brace-or-equal-initializer does not have a user-provided default 6962 // constructor. 6963 if (!inUnion() && FieldType.isConstQualified() && 6964 !FD->hasInClassInitializer() && 6965 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6966 if (Diagnose) 6967 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6968 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6969 return true; 6970 } 6971 6972 if (inUnion() && !FieldType.isConstQualified()) 6973 AllFieldsAreConst = false; 6974 } else if (CSM == Sema::CXXCopyConstructor) { 6975 // For a copy constructor, data members must not be of rvalue reference 6976 // type. 6977 if (FieldType->isRValueReferenceType()) { 6978 if (Diagnose) 6979 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6980 << MD->getParent() << FD << FieldType; 6981 return true; 6982 } 6983 } else if (IsAssignment) { 6984 // For an assignment operator, data members must not be of reference type. 6985 if (FieldType->isReferenceType()) { 6986 if (Diagnose) 6987 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6988 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6989 return true; 6990 } 6991 if (!FieldRecord && FieldType.isConstQualified()) { 6992 // C++11 [class.copy]p23: 6993 // -- a non-static data member of const non-class type (or array thereof) 6994 if (Diagnose) 6995 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6996 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6997 return true; 6998 } 6999 } 7000 7001 if (FieldRecord) { 7002 // Some additional restrictions exist on the variant members. 7003 if (!inUnion() && FieldRecord->isUnion() && 7004 FieldRecord->isAnonymousStructOrUnion()) { 7005 bool AllVariantFieldsAreConst = true; 7006 7007 // FIXME: Handle anonymous unions declared within anonymous unions. 7008 for (auto *UI : FieldRecord->fields()) { 7009 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7010 7011 if (!UnionFieldType.isConstQualified()) 7012 AllVariantFieldsAreConst = false; 7013 7014 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7015 if (UnionFieldRecord && 7016 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7017 UnionFieldType.getCVRQualifiers())) 7018 return true; 7019 } 7020 7021 // At least one member in each anonymous union must be non-const 7022 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7023 !FieldRecord->field_empty()) { 7024 if (Diagnose) 7025 S.Diag(FieldRecord->getLocation(), 7026 diag::note_deleted_default_ctor_all_const) 7027 << !!ICI << MD->getParent() << /*anonymous union*/1; 7028 return true; 7029 } 7030 7031 // Don't check the implicit member of the anonymous union type. 7032 // This is technically non-conformant, but sanity demands it. 7033 return false; 7034 } 7035 7036 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7037 FieldType.getCVRQualifiers())) 7038 return true; 7039 } 7040 7041 return false; 7042 } 7043 7044 /// C++11 [class.ctor] p5: 7045 /// A defaulted default constructor for a class X is defined as deleted if 7046 /// X is a union and all of its variant members are of const-qualified type. 7047 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7048 // This is a silly definition, because it gives an empty union a deleted 7049 // default constructor. Don't do that. 7050 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7051 bool AnyFields = false; 7052 for (auto *F : MD->getParent()->fields()) 7053 if ((AnyFields = !F->isUnnamedBitfield())) 7054 break; 7055 if (!AnyFields) 7056 return false; 7057 if (Diagnose) 7058 S.Diag(MD->getParent()->getLocation(), 7059 diag::note_deleted_default_ctor_all_const) 7060 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7061 return true; 7062 } 7063 return false; 7064 } 7065 7066 /// Determine whether a defaulted special member function should be defined as 7067 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7068 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7069 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7070 InheritedConstructorInfo *ICI, 7071 bool Diagnose) { 7072 if (MD->isInvalidDecl()) 7073 return false; 7074 CXXRecordDecl *RD = MD->getParent(); 7075 assert(!RD->isDependentType() && "do deletion after instantiation"); 7076 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7077 return false; 7078 7079 // C++11 [expr.lambda.prim]p19: 7080 // The closure type associated with a lambda-expression has a 7081 // deleted (8.4.3) default constructor and a deleted copy 7082 // assignment operator. 7083 if (RD->isLambda() && 7084 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7085 if (Diagnose) 7086 Diag(RD->getLocation(), diag::note_lambda_decl); 7087 return true; 7088 } 7089 7090 // For an anonymous struct or union, the copy and assignment special members 7091 // will never be used, so skip the check. For an anonymous union declared at 7092 // namespace scope, the constructor and destructor are used. 7093 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7094 RD->isAnonymousStructOrUnion()) 7095 return false; 7096 7097 // C++11 [class.copy]p7, p18: 7098 // If the class definition declares a move constructor or move assignment 7099 // operator, an implicitly declared copy constructor or copy assignment 7100 // operator is defined as deleted. 7101 if (MD->isImplicit() && 7102 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7103 CXXMethodDecl *UserDeclaredMove = nullptr; 7104 7105 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7106 // deletion of the corresponding copy operation, not both copy operations. 7107 // MSVC 2015 has adopted the standards conforming behavior. 7108 bool DeletesOnlyMatchingCopy = 7109 getLangOpts().MSVCCompat && 7110 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7111 7112 if (RD->hasUserDeclaredMoveConstructor() && 7113 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7114 if (!Diagnose) return true; 7115 7116 // Find any user-declared move constructor. 7117 for (auto *I : RD->ctors()) { 7118 if (I->isMoveConstructor()) { 7119 UserDeclaredMove = I; 7120 break; 7121 } 7122 } 7123 assert(UserDeclaredMove); 7124 } else if (RD->hasUserDeclaredMoveAssignment() && 7125 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7126 if (!Diagnose) return true; 7127 7128 // Find any user-declared move assignment operator. 7129 for (auto *I : RD->methods()) { 7130 if (I->isMoveAssignmentOperator()) { 7131 UserDeclaredMove = I; 7132 break; 7133 } 7134 } 7135 assert(UserDeclaredMove); 7136 } 7137 7138 if (UserDeclaredMove) { 7139 Diag(UserDeclaredMove->getLocation(), 7140 diag::note_deleted_copy_user_declared_move) 7141 << (CSM == CXXCopyAssignment) << RD 7142 << UserDeclaredMove->isMoveAssignmentOperator(); 7143 return true; 7144 } 7145 } 7146 7147 // Do access control from the special member function 7148 ContextRAII MethodContext(*this, MD); 7149 7150 // C++11 [class.dtor]p5: 7151 // -- for a virtual destructor, lookup of the non-array deallocation function 7152 // results in an ambiguity or in a function that is deleted or inaccessible 7153 if (CSM == CXXDestructor && MD->isVirtual()) { 7154 FunctionDecl *OperatorDelete = nullptr; 7155 DeclarationName Name = 7156 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7157 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7158 OperatorDelete, /*Diagnose*/false)) { 7159 if (Diagnose) 7160 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7161 return true; 7162 } 7163 } 7164 7165 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7166 7167 // Per DR1611, do not consider virtual bases of constructors of abstract 7168 // classes, since we are not going to construct them. 7169 // Per DR1658, do not consider virtual bases of destructors of abstract 7170 // classes either. 7171 // Per DR2180, for assignment operators we only assign (and thus only 7172 // consider) direct bases. 7173 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7174 : SMI.VisitPotentiallyConstructedBases)) 7175 return true; 7176 7177 if (SMI.shouldDeleteForAllConstMembers()) 7178 return true; 7179 7180 if (getLangOpts().CUDA) { 7181 // We should delete the special member in CUDA mode if target inference 7182 // failed. 7183 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7184 Diagnose); 7185 } 7186 7187 return false; 7188 } 7189 7190 /// Perform lookup for a special member of the specified kind, and determine 7191 /// whether it is trivial. If the triviality can be determined without the 7192 /// lookup, skip it. This is intended for use when determining whether a 7193 /// special member of a containing object is trivial, and thus does not ever 7194 /// perform overload resolution for default constructors. 7195 /// 7196 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7197 /// member that was most likely to be intended to be trivial, if any. 7198 /// 7199 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7200 /// determine whether the special member is trivial. 7201 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7202 Sema::CXXSpecialMember CSM, unsigned Quals, 7203 bool ConstRHS, 7204 Sema::TrivialABIHandling TAH, 7205 CXXMethodDecl **Selected) { 7206 if (Selected) 7207 *Selected = nullptr; 7208 7209 switch (CSM) { 7210 case Sema::CXXInvalid: 7211 llvm_unreachable("not a special member"); 7212 7213 case Sema::CXXDefaultConstructor: 7214 // C++11 [class.ctor]p5: 7215 // A default constructor is trivial if: 7216 // - all the [direct subobjects] have trivial default constructors 7217 // 7218 // Note, no overload resolution is performed in this case. 7219 if (RD->hasTrivialDefaultConstructor()) 7220 return true; 7221 7222 if (Selected) { 7223 // If there's a default constructor which could have been trivial, dig it 7224 // out. Otherwise, if there's any user-provided default constructor, point 7225 // to that as an example of why there's not a trivial one. 7226 CXXConstructorDecl *DefCtor = nullptr; 7227 if (RD->needsImplicitDefaultConstructor()) 7228 S.DeclareImplicitDefaultConstructor(RD); 7229 for (auto *CI : RD->ctors()) { 7230 if (!CI->isDefaultConstructor()) 7231 continue; 7232 DefCtor = CI; 7233 if (!DefCtor->isUserProvided()) 7234 break; 7235 } 7236 7237 *Selected = DefCtor; 7238 } 7239 7240 return false; 7241 7242 case Sema::CXXDestructor: 7243 // C++11 [class.dtor]p5: 7244 // A destructor is trivial if: 7245 // - all the direct [subobjects] have trivial destructors 7246 if (RD->hasTrivialDestructor() || 7247 (TAH == Sema::TAH_ConsiderTrivialABI && 7248 RD->hasTrivialDestructorForCall())) 7249 return true; 7250 7251 if (Selected) { 7252 if (RD->needsImplicitDestructor()) 7253 S.DeclareImplicitDestructor(RD); 7254 *Selected = RD->getDestructor(); 7255 } 7256 7257 return false; 7258 7259 case Sema::CXXCopyConstructor: 7260 // C++11 [class.copy]p12: 7261 // A copy constructor is trivial if: 7262 // - the constructor selected to copy each direct [subobject] is trivial 7263 if (RD->hasTrivialCopyConstructor() || 7264 (TAH == Sema::TAH_ConsiderTrivialABI && 7265 RD->hasTrivialCopyConstructorForCall())) { 7266 if (Quals == Qualifiers::Const) 7267 // We must either select the trivial copy constructor or reach an 7268 // ambiguity; no need to actually perform overload resolution. 7269 return true; 7270 } else if (!Selected) { 7271 return false; 7272 } 7273 // In C++98, we are not supposed to perform overload resolution here, but we 7274 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7275 // cases like B as having a non-trivial copy constructor: 7276 // struct A { template<typename T> A(T&); }; 7277 // struct B { mutable A a; }; 7278 goto NeedOverloadResolution; 7279 7280 case Sema::CXXCopyAssignment: 7281 // C++11 [class.copy]p25: 7282 // A copy assignment operator is trivial if: 7283 // - the assignment operator selected to copy each direct [subobject] is 7284 // trivial 7285 if (RD->hasTrivialCopyAssignment()) { 7286 if (Quals == Qualifiers::Const) 7287 return true; 7288 } else if (!Selected) { 7289 return false; 7290 } 7291 // In C++98, we are not supposed to perform overload resolution here, but we 7292 // treat that as a language defect. 7293 goto NeedOverloadResolution; 7294 7295 case Sema::CXXMoveConstructor: 7296 case Sema::CXXMoveAssignment: 7297 NeedOverloadResolution: 7298 Sema::SpecialMemberOverloadResult SMOR = 7299 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7300 7301 // The standard doesn't describe how to behave if the lookup is ambiguous. 7302 // We treat it as not making the member non-trivial, just like the standard 7303 // mandates for the default constructor. This should rarely matter, because 7304 // the member will also be deleted. 7305 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7306 return true; 7307 7308 if (!SMOR.getMethod()) { 7309 assert(SMOR.getKind() == 7310 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7311 return false; 7312 } 7313 7314 // We deliberately don't check if we found a deleted special member. We're 7315 // not supposed to! 7316 if (Selected) 7317 *Selected = SMOR.getMethod(); 7318 7319 if (TAH == Sema::TAH_ConsiderTrivialABI && 7320 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7321 return SMOR.getMethod()->isTrivialForCall(); 7322 return SMOR.getMethod()->isTrivial(); 7323 } 7324 7325 llvm_unreachable("unknown special method kind"); 7326 } 7327 7328 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7329 for (auto *CI : RD->ctors()) 7330 if (!CI->isImplicit()) 7331 return CI; 7332 7333 // Look for constructor templates. 7334 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7335 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7336 if (CXXConstructorDecl *CD = 7337 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7338 return CD; 7339 } 7340 7341 return nullptr; 7342 } 7343 7344 /// The kind of subobject we are checking for triviality. The values of this 7345 /// enumeration are used in diagnostics. 7346 enum TrivialSubobjectKind { 7347 /// The subobject is a base class. 7348 TSK_BaseClass, 7349 /// The subobject is a non-static data member. 7350 TSK_Field, 7351 /// The object is actually the complete object. 7352 TSK_CompleteObject 7353 }; 7354 7355 /// Check whether the special member selected for a given type would be trivial. 7356 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7357 QualType SubType, bool ConstRHS, 7358 Sema::CXXSpecialMember CSM, 7359 TrivialSubobjectKind Kind, 7360 Sema::TrivialABIHandling TAH, bool Diagnose) { 7361 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7362 if (!SubRD) 7363 return true; 7364 7365 CXXMethodDecl *Selected; 7366 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7367 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7368 return true; 7369 7370 if (Diagnose) { 7371 if (ConstRHS) 7372 SubType.addConst(); 7373 7374 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7375 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7376 << Kind << SubType.getUnqualifiedType(); 7377 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7378 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7379 } else if (!Selected) 7380 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7381 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7382 else if (Selected->isUserProvided()) { 7383 if (Kind == TSK_CompleteObject) 7384 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7385 << Kind << SubType.getUnqualifiedType() << CSM; 7386 else { 7387 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7388 << Kind << SubType.getUnqualifiedType() << CSM; 7389 S.Diag(Selected->getLocation(), diag::note_declared_at); 7390 } 7391 } else { 7392 if (Kind != TSK_CompleteObject) 7393 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7394 << Kind << SubType.getUnqualifiedType() << CSM; 7395 7396 // Explain why the defaulted or deleted special member isn't trivial. 7397 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7398 Diagnose); 7399 } 7400 } 7401 7402 return false; 7403 } 7404 7405 /// Check whether the members of a class type allow a special member to be 7406 /// trivial. 7407 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7408 Sema::CXXSpecialMember CSM, 7409 bool ConstArg, 7410 Sema::TrivialABIHandling TAH, 7411 bool Diagnose) { 7412 for (const auto *FI : RD->fields()) { 7413 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7414 continue; 7415 7416 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7417 7418 // Pretend anonymous struct or union members are members of this class. 7419 if (FI->isAnonymousStructOrUnion()) { 7420 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7421 CSM, ConstArg, TAH, Diagnose)) 7422 return false; 7423 continue; 7424 } 7425 7426 // C++11 [class.ctor]p5: 7427 // A default constructor is trivial if [...] 7428 // -- no non-static data member of its class has a 7429 // brace-or-equal-initializer 7430 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7431 if (Diagnose) 7432 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7433 return false; 7434 } 7435 7436 // Objective C ARC 4.3.5: 7437 // [...] nontrivally ownership-qualified types are [...] not trivially 7438 // default constructible, copy constructible, move constructible, copy 7439 // assignable, move assignable, or destructible [...] 7440 if (FieldType.hasNonTrivialObjCLifetime()) { 7441 if (Diagnose) 7442 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7443 << RD << FieldType.getObjCLifetime(); 7444 return false; 7445 } 7446 7447 bool ConstRHS = ConstArg && !FI->isMutable(); 7448 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7449 CSM, TSK_Field, TAH, Diagnose)) 7450 return false; 7451 } 7452 7453 return true; 7454 } 7455 7456 /// Diagnose why the specified class does not have a trivial special member of 7457 /// the given kind. 7458 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7459 QualType Ty = Context.getRecordType(RD); 7460 7461 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7462 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7463 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7464 /*Diagnose*/true); 7465 } 7466 7467 /// Determine whether a defaulted or deleted special member function is trivial, 7468 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7469 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7470 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7471 TrivialABIHandling TAH, bool Diagnose) { 7472 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7473 7474 CXXRecordDecl *RD = MD->getParent(); 7475 7476 bool ConstArg = false; 7477 7478 // C++11 [class.copy]p12, p25: [DR1593] 7479 // A [special member] is trivial if [...] its parameter-type-list is 7480 // equivalent to the parameter-type-list of an implicit declaration [...] 7481 switch (CSM) { 7482 case CXXDefaultConstructor: 7483 case CXXDestructor: 7484 // Trivial default constructors and destructors cannot have parameters. 7485 break; 7486 7487 case CXXCopyConstructor: 7488 case CXXCopyAssignment: { 7489 // Trivial copy operations always have const, non-volatile parameter types. 7490 ConstArg = true; 7491 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7492 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7493 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7494 if (Diagnose) 7495 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7496 << Param0->getSourceRange() << Param0->getType() 7497 << Context.getLValueReferenceType( 7498 Context.getRecordType(RD).withConst()); 7499 return false; 7500 } 7501 break; 7502 } 7503 7504 case CXXMoveConstructor: 7505 case CXXMoveAssignment: { 7506 // Trivial move operations always have non-cv-qualified parameters. 7507 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7508 const RValueReferenceType *RT = 7509 Param0->getType()->getAs<RValueReferenceType>(); 7510 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7511 if (Diagnose) 7512 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7513 << Param0->getSourceRange() << Param0->getType() 7514 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7515 return false; 7516 } 7517 break; 7518 } 7519 7520 case CXXInvalid: 7521 llvm_unreachable("not a special member"); 7522 } 7523 7524 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7525 if (Diagnose) 7526 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7527 diag::note_nontrivial_default_arg) 7528 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7529 return false; 7530 } 7531 if (MD->isVariadic()) { 7532 if (Diagnose) 7533 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7534 return false; 7535 } 7536 7537 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7538 // A copy/move [constructor or assignment operator] is trivial if 7539 // -- the [member] selected to copy/move each direct base class subobject 7540 // is trivial 7541 // 7542 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7543 // A [default constructor or destructor] is trivial if 7544 // -- all the direct base classes have trivial [default constructors or 7545 // destructors] 7546 for (const auto &BI : RD->bases()) 7547 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7548 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7549 return false; 7550 7551 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7552 // A copy/move [constructor or assignment operator] for a class X is 7553 // trivial if 7554 // -- for each non-static data member of X that is of class type (or array 7555 // thereof), the constructor selected to copy/move that member is 7556 // trivial 7557 // 7558 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7559 // A [default constructor or destructor] is trivial if 7560 // -- for all of the non-static data members of its class that are of class 7561 // type (or array thereof), each such class has a trivial [default 7562 // constructor or destructor] 7563 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7564 return false; 7565 7566 // C++11 [class.dtor]p5: 7567 // A destructor is trivial if [...] 7568 // -- the destructor is not virtual 7569 if (CSM == CXXDestructor && MD->isVirtual()) { 7570 if (Diagnose) 7571 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7572 return false; 7573 } 7574 7575 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7576 // A [special member] for class X is trivial if [...] 7577 // -- class X has no virtual functions and no virtual base classes 7578 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7579 if (!Diagnose) 7580 return false; 7581 7582 if (RD->getNumVBases()) { 7583 // Check for virtual bases. We already know that the corresponding 7584 // member in all bases is trivial, so vbases must all be direct. 7585 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7586 assert(BS.isVirtual()); 7587 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7588 return false; 7589 } 7590 7591 // Must have a virtual method. 7592 for (const auto *MI : RD->methods()) { 7593 if (MI->isVirtual()) { 7594 SourceLocation MLoc = MI->getLocStart(); 7595 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7596 return false; 7597 } 7598 } 7599 7600 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7601 } 7602 7603 // Looks like it's trivial! 7604 return true; 7605 } 7606 7607 namespace { 7608 struct FindHiddenVirtualMethod { 7609 Sema *S; 7610 CXXMethodDecl *Method; 7611 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7612 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7613 7614 private: 7615 /// Check whether any most overriden method from MD in Methods 7616 static bool CheckMostOverridenMethods( 7617 const CXXMethodDecl *MD, 7618 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7619 if (MD->size_overridden_methods() == 0) 7620 return Methods.count(MD->getCanonicalDecl()); 7621 for (const CXXMethodDecl *O : MD->overridden_methods()) 7622 if (CheckMostOverridenMethods(O, Methods)) 7623 return true; 7624 return false; 7625 } 7626 7627 public: 7628 /// Member lookup function that determines whether a given C++ 7629 /// method overloads virtual methods in a base class without overriding any, 7630 /// to be used with CXXRecordDecl::lookupInBases(). 7631 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7632 RecordDecl *BaseRecord = 7633 Specifier->getType()->getAs<RecordType>()->getDecl(); 7634 7635 DeclarationName Name = Method->getDeclName(); 7636 assert(Name.getNameKind() == DeclarationName::Identifier); 7637 7638 bool foundSameNameMethod = false; 7639 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7640 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7641 Path.Decls = Path.Decls.slice(1)) { 7642 NamedDecl *D = Path.Decls.front(); 7643 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7644 MD = MD->getCanonicalDecl(); 7645 foundSameNameMethod = true; 7646 // Interested only in hidden virtual methods. 7647 if (!MD->isVirtual()) 7648 continue; 7649 // If the method we are checking overrides a method from its base 7650 // don't warn about the other overloaded methods. Clang deviates from 7651 // GCC by only diagnosing overloads of inherited virtual functions that 7652 // do not override any other virtual functions in the base. GCC's 7653 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7654 // function from a base class. These cases may be better served by a 7655 // warning (not specific to virtual functions) on call sites when the 7656 // call would select a different function from the base class, were it 7657 // visible. 7658 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7659 if (!S->IsOverload(Method, MD, false)) 7660 return true; 7661 // Collect the overload only if its hidden. 7662 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7663 overloadedMethods.push_back(MD); 7664 } 7665 } 7666 7667 if (foundSameNameMethod) 7668 OverloadedMethods.append(overloadedMethods.begin(), 7669 overloadedMethods.end()); 7670 return foundSameNameMethod; 7671 } 7672 }; 7673 } // end anonymous namespace 7674 7675 /// Add the most overriden methods from MD to Methods 7676 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7677 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7678 if (MD->size_overridden_methods() == 0) 7679 Methods.insert(MD->getCanonicalDecl()); 7680 else 7681 for (const CXXMethodDecl *O : MD->overridden_methods()) 7682 AddMostOverridenMethods(O, Methods); 7683 } 7684 7685 /// Check if a method overloads virtual methods in a base class without 7686 /// overriding any. 7687 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7688 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7689 if (!MD->getDeclName().isIdentifier()) 7690 return; 7691 7692 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7693 /*bool RecordPaths=*/false, 7694 /*bool DetectVirtual=*/false); 7695 FindHiddenVirtualMethod FHVM; 7696 FHVM.Method = MD; 7697 FHVM.S = this; 7698 7699 // Keep the base methods that were overriden or introduced in the subclass 7700 // by 'using' in a set. A base method not in this set is hidden. 7701 CXXRecordDecl *DC = MD->getParent(); 7702 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7703 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7704 NamedDecl *ND = *I; 7705 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7706 ND = shad->getTargetDecl(); 7707 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7708 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7709 } 7710 7711 if (DC->lookupInBases(FHVM, Paths)) 7712 OverloadedMethods = FHVM.OverloadedMethods; 7713 } 7714 7715 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7716 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7717 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7718 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7719 PartialDiagnostic PD = PDiag( 7720 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7721 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7722 Diag(overloadedMD->getLocation(), PD); 7723 } 7724 } 7725 7726 /// Diagnose methods which overload virtual methods in a base class 7727 /// without overriding any. 7728 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7729 if (MD->isInvalidDecl()) 7730 return; 7731 7732 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7733 return; 7734 7735 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7736 FindHiddenVirtualMethods(MD, OverloadedMethods); 7737 if (!OverloadedMethods.empty()) { 7738 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7739 << MD << (OverloadedMethods.size() > 1); 7740 7741 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7742 } 7743 } 7744 7745 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7746 auto PrintDiagAndRemoveAttr = [&]() { 7747 // No diagnostics if this is a template instantiation. 7748 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7749 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7750 diag::ext_cannot_use_trivial_abi) << &RD; 7751 RD.dropAttr<TrivialABIAttr>(); 7752 }; 7753 7754 // Ill-formed if the struct has virtual functions. 7755 if (RD.isPolymorphic()) { 7756 PrintDiagAndRemoveAttr(); 7757 return; 7758 } 7759 7760 for (const auto &B : RD.bases()) { 7761 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7762 // virtual base. 7763 if ((!B.getType()->isDependentType() && 7764 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7765 B.isVirtual()) { 7766 PrintDiagAndRemoveAttr(); 7767 return; 7768 } 7769 } 7770 7771 for (const auto *FD : RD.fields()) { 7772 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7773 // non-trivial for the purpose of calls. 7774 QualType FT = FD->getType(); 7775 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7776 PrintDiagAndRemoveAttr(); 7777 return; 7778 } 7779 7780 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7781 if (!RT->isDependentType() && 7782 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7783 PrintDiagAndRemoveAttr(); 7784 return; 7785 } 7786 } 7787 } 7788 7789 void Sema::ActOnFinishCXXMemberSpecification( 7790 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 7791 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 7792 if (!TagDecl) 7793 return; 7794 7795 AdjustDeclIfTemplate(TagDecl); 7796 7797 for (const ParsedAttr &AL : AttrList) { 7798 if (AL.getKind() != ParsedAttr::AT_Visibility) 7799 continue; 7800 AL.setInvalid(); 7801 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 7802 << AL.getName(); 7803 } 7804 7805 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7806 // strict aliasing violation! 7807 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7808 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7809 7810 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 7811 } 7812 7813 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7814 /// special functions, such as the default constructor, copy 7815 /// constructor, or destructor, to the given C++ class (C++ 7816 /// [special]p1). This routine can only be executed just before the 7817 /// definition of the class is complete. 7818 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7819 if (ClassDecl->needsImplicitDefaultConstructor()) { 7820 ++ASTContext::NumImplicitDefaultConstructors; 7821 7822 if (ClassDecl->hasInheritedConstructor()) 7823 DeclareImplicitDefaultConstructor(ClassDecl); 7824 } 7825 7826 if (ClassDecl->needsImplicitCopyConstructor()) { 7827 ++ASTContext::NumImplicitCopyConstructors; 7828 7829 // If the properties or semantics of the copy constructor couldn't be 7830 // determined while the class was being declared, force a declaration 7831 // of it now. 7832 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7833 ClassDecl->hasInheritedConstructor()) 7834 DeclareImplicitCopyConstructor(ClassDecl); 7835 // For the MS ABI we need to know whether the copy ctor is deleted. A 7836 // prerequisite for deleting the implicit copy ctor is that the class has a 7837 // move ctor or move assignment that is either user-declared or whose 7838 // semantics are inherited from a subobject. FIXME: We should provide a more 7839 // direct way for CodeGen to ask whether the constructor was deleted. 7840 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7841 (ClassDecl->hasUserDeclaredMoveConstructor() || 7842 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7843 ClassDecl->hasUserDeclaredMoveAssignment() || 7844 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7845 DeclareImplicitCopyConstructor(ClassDecl); 7846 } 7847 7848 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7849 ++ASTContext::NumImplicitMoveConstructors; 7850 7851 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7852 ClassDecl->hasInheritedConstructor()) 7853 DeclareImplicitMoveConstructor(ClassDecl); 7854 } 7855 7856 if (ClassDecl->needsImplicitCopyAssignment()) { 7857 ++ASTContext::NumImplicitCopyAssignmentOperators; 7858 7859 // If we have a dynamic class, then the copy assignment operator may be 7860 // virtual, so we have to declare it immediately. This ensures that, e.g., 7861 // it shows up in the right place in the vtable and that we diagnose 7862 // problems with the implicit exception specification. 7863 if (ClassDecl->isDynamicClass() || 7864 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7865 ClassDecl->hasInheritedAssignment()) 7866 DeclareImplicitCopyAssignment(ClassDecl); 7867 } 7868 7869 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7870 ++ASTContext::NumImplicitMoveAssignmentOperators; 7871 7872 // Likewise for the move assignment operator. 7873 if (ClassDecl->isDynamicClass() || 7874 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7875 ClassDecl->hasInheritedAssignment()) 7876 DeclareImplicitMoveAssignment(ClassDecl); 7877 } 7878 7879 if (ClassDecl->needsImplicitDestructor()) { 7880 ++ASTContext::NumImplicitDestructors; 7881 7882 // If we have a dynamic class, then the destructor may be virtual, so we 7883 // have to declare the destructor immediately. This ensures that, e.g., it 7884 // shows up in the right place in the vtable and that we diagnose problems 7885 // with the implicit exception specification. 7886 if (ClassDecl->isDynamicClass() || 7887 ClassDecl->needsOverloadResolutionForDestructor()) 7888 DeclareImplicitDestructor(ClassDecl); 7889 } 7890 } 7891 7892 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7893 if (!D) 7894 return 0; 7895 7896 // The order of template parameters is not important here. All names 7897 // get added to the same scope. 7898 SmallVector<TemplateParameterList *, 4> ParameterLists; 7899 7900 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7901 D = TD->getTemplatedDecl(); 7902 7903 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7904 ParameterLists.push_back(PSD->getTemplateParameters()); 7905 7906 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7907 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7908 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7909 7910 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7911 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7912 ParameterLists.push_back(FTD->getTemplateParameters()); 7913 } 7914 } 7915 7916 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7917 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7918 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7919 7920 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7921 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7922 ParameterLists.push_back(CTD->getTemplateParameters()); 7923 } 7924 } 7925 7926 unsigned Count = 0; 7927 for (TemplateParameterList *Params : ParameterLists) { 7928 if (Params->size() > 0) 7929 // Ignore explicit specializations; they don't contribute to the template 7930 // depth. 7931 ++Count; 7932 for (NamedDecl *Param : *Params) { 7933 if (Param->getDeclName()) { 7934 S->AddDecl(Param); 7935 IdResolver.AddDecl(Param); 7936 } 7937 } 7938 } 7939 7940 return Count; 7941 } 7942 7943 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7944 if (!RecordD) return; 7945 AdjustDeclIfTemplate(RecordD); 7946 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7947 PushDeclContext(S, Record); 7948 } 7949 7950 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7951 if (!RecordD) return; 7952 PopDeclContext(); 7953 } 7954 7955 /// This is used to implement the constant expression evaluation part of the 7956 /// attribute enable_if extension. There is nothing in standard C++ which would 7957 /// require reentering parameters. 7958 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7959 if (!Param) 7960 return; 7961 7962 S->AddDecl(Param); 7963 if (Param->getDeclName()) 7964 IdResolver.AddDecl(Param); 7965 } 7966 7967 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7968 /// parsing a top-level (non-nested) C++ class, and we are now 7969 /// parsing those parts of the given Method declaration that could 7970 /// not be parsed earlier (C++ [class.mem]p2), such as default 7971 /// arguments. This action should enter the scope of the given 7972 /// Method declaration as if we had just parsed the qualified method 7973 /// name. However, it should not bring the parameters into scope; 7974 /// that will be performed by ActOnDelayedCXXMethodParameter. 7975 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7976 } 7977 7978 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7979 /// C++ method declaration. We're (re-)introducing the given 7980 /// function parameter into scope for use in parsing later parts of 7981 /// the method declaration. For example, we could see an 7982 /// ActOnParamDefaultArgument event for this parameter. 7983 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7984 if (!ParamD) 7985 return; 7986 7987 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7988 7989 // If this parameter has an unparsed default argument, clear it out 7990 // to make way for the parsed default argument. 7991 if (Param->hasUnparsedDefaultArg()) 7992 Param->setDefaultArg(nullptr); 7993 7994 S->AddDecl(Param); 7995 if (Param->getDeclName()) 7996 IdResolver.AddDecl(Param); 7997 } 7998 7999 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8000 /// processing the delayed method declaration for Method. The method 8001 /// declaration is now considered finished. There may be a separate 8002 /// ActOnStartOfFunctionDef action later (not necessarily 8003 /// immediately!) for this method, if it was also defined inside the 8004 /// class body. 8005 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8006 if (!MethodD) 8007 return; 8008 8009 AdjustDeclIfTemplate(MethodD); 8010 8011 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8012 8013 // Now that we have our default arguments, check the constructor 8014 // again. It could produce additional diagnostics or affect whether 8015 // the class has implicitly-declared destructors, among other 8016 // things. 8017 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8018 CheckConstructor(Constructor); 8019 8020 // Check the default arguments, which we may have added. 8021 if (!Method->isInvalidDecl()) 8022 CheckCXXDefaultArguments(Method); 8023 } 8024 8025 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8026 /// the well-formedness of the constructor declarator @p D with type @p 8027 /// R. If there are any errors in the declarator, this routine will 8028 /// emit diagnostics and set the invalid bit to true. In any case, the type 8029 /// will be updated to reflect a well-formed type for the constructor and 8030 /// returned. 8031 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8032 StorageClass &SC) { 8033 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8034 8035 // C++ [class.ctor]p3: 8036 // A constructor shall not be virtual (10.3) or static (9.4). A 8037 // constructor can be invoked for a const, volatile or const 8038 // volatile object. A constructor shall not be declared const, 8039 // volatile, or const volatile (9.3.2). 8040 if (isVirtual) { 8041 if (!D.isInvalidType()) 8042 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8043 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8044 << SourceRange(D.getIdentifierLoc()); 8045 D.setInvalidType(); 8046 } 8047 if (SC == SC_Static) { 8048 if (!D.isInvalidType()) 8049 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8050 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8051 << SourceRange(D.getIdentifierLoc()); 8052 D.setInvalidType(); 8053 SC = SC_None; 8054 } 8055 8056 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8057 diagnoseIgnoredQualifiers( 8058 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8059 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8060 D.getDeclSpec().getRestrictSpecLoc(), 8061 D.getDeclSpec().getAtomicSpecLoc()); 8062 D.setInvalidType(); 8063 } 8064 8065 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8066 if (FTI.TypeQuals != 0) { 8067 if (FTI.TypeQuals & Qualifiers::Const) 8068 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8069 << "const" << SourceRange(D.getIdentifierLoc()); 8070 if (FTI.TypeQuals & Qualifiers::Volatile) 8071 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8072 << "volatile" << SourceRange(D.getIdentifierLoc()); 8073 if (FTI.TypeQuals & Qualifiers::Restrict) 8074 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8075 << "restrict" << SourceRange(D.getIdentifierLoc()); 8076 D.setInvalidType(); 8077 } 8078 8079 // C++0x [class.ctor]p4: 8080 // A constructor shall not be declared with a ref-qualifier. 8081 if (FTI.hasRefQualifier()) { 8082 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8083 << FTI.RefQualifierIsLValueRef 8084 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8085 D.setInvalidType(); 8086 } 8087 8088 // Rebuild the function type "R" without any type qualifiers (in 8089 // case any of the errors above fired) and with "void" as the 8090 // return type, since constructors don't have return types. 8091 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8092 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8093 return R; 8094 8095 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8096 EPI.TypeQuals = 0; 8097 EPI.RefQualifier = RQ_None; 8098 8099 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8100 } 8101 8102 /// CheckConstructor - Checks a fully-formed constructor for 8103 /// well-formedness, issuing any diagnostics required. Returns true if 8104 /// the constructor declarator is invalid. 8105 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8106 CXXRecordDecl *ClassDecl 8107 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8108 if (!ClassDecl) 8109 return Constructor->setInvalidDecl(); 8110 8111 // C++ [class.copy]p3: 8112 // A declaration of a constructor for a class X is ill-formed if 8113 // its first parameter is of type (optionally cv-qualified) X and 8114 // either there are no other parameters or else all other 8115 // parameters have default arguments. 8116 if (!Constructor->isInvalidDecl() && 8117 ((Constructor->getNumParams() == 1) || 8118 (Constructor->getNumParams() > 1 && 8119 Constructor->getParamDecl(1)->hasDefaultArg())) && 8120 Constructor->getTemplateSpecializationKind() 8121 != TSK_ImplicitInstantiation) { 8122 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8123 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8124 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8125 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8126 const char *ConstRef 8127 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8128 : " const &"; 8129 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8130 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8131 8132 // FIXME: Rather that making the constructor invalid, we should endeavor 8133 // to fix the type. 8134 Constructor->setInvalidDecl(); 8135 } 8136 } 8137 } 8138 8139 /// CheckDestructor - Checks a fully-formed destructor definition for 8140 /// well-formedness, issuing any diagnostics required. Returns true 8141 /// on error. 8142 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8143 CXXRecordDecl *RD = Destructor->getParent(); 8144 8145 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8146 SourceLocation Loc; 8147 8148 if (!Destructor->isImplicit()) 8149 Loc = Destructor->getLocation(); 8150 else 8151 Loc = RD->getLocation(); 8152 8153 // If we have a virtual destructor, look up the deallocation function 8154 if (FunctionDecl *OperatorDelete = 8155 FindDeallocationFunctionForDestructor(Loc, RD)) { 8156 Expr *ThisArg = nullptr; 8157 8158 // If the notional 'delete this' expression requires a non-trivial 8159 // conversion from 'this' to the type of a destroying operator delete's 8160 // first parameter, perform that conversion now. 8161 if (OperatorDelete->isDestroyingOperatorDelete()) { 8162 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8163 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8164 // C++ [class.dtor]p13: 8165 // ... as if for the expression 'delete this' appearing in a 8166 // non-virtual destructor of the destructor's class. 8167 ContextRAII SwitchContext(*this, Destructor); 8168 ExprResult This = 8169 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8170 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8171 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8172 if (This.isInvalid()) { 8173 // FIXME: Register this as a context note so that it comes out 8174 // in the right order. 8175 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8176 return true; 8177 } 8178 ThisArg = This.get(); 8179 } 8180 } 8181 8182 MarkFunctionReferenced(Loc, OperatorDelete); 8183 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8184 } 8185 } 8186 8187 return false; 8188 } 8189 8190 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8191 /// the well-formednes of the destructor declarator @p D with type @p 8192 /// R. If there are any errors in the declarator, this routine will 8193 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8194 /// will be updated to reflect a well-formed type for the destructor and 8195 /// returned. 8196 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8197 StorageClass& SC) { 8198 // C++ [class.dtor]p1: 8199 // [...] A typedef-name that names a class is a class-name 8200 // (7.1.3); however, a typedef-name that names a class shall not 8201 // be used as the identifier in the declarator for a destructor 8202 // declaration. 8203 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8204 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8205 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8206 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8207 else if (const TemplateSpecializationType *TST = 8208 DeclaratorType->getAs<TemplateSpecializationType>()) 8209 if (TST->isTypeAlias()) 8210 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8211 << DeclaratorType << 1; 8212 8213 // C++ [class.dtor]p2: 8214 // A destructor is used to destroy objects of its class type. A 8215 // destructor takes no parameters, and no return type can be 8216 // specified for it (not even void). The address of a destructor 8217 // shall not be taken. A destructor shall not be static. A 8218 // destructor can be invoked for a const, volatile or const 8219 // volatile object. A destructor shall not be declared const, 8220 // volatile or const volatile (9.3.2). 8221 if (SC == SC_Static) { 8222 if (!D.isInvalidType()) 8223 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8224 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8225 << SourceRange(D.getIdentifierLoc()) 8226 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8227 8228 SC = SC_None; 8229 } 8230 if (!D.isInvalidType()) { 8231 // Destructors don't have return types, but the parser will 8232 // happily parse something like: 8233 // 8234 // class X { 8235 // float ~X(); 8236 // }; 8237 // 8238 // The return type will be eliminated later. 8239 if (D.getDeclSpec().hasTypeSpecifier()) 8240 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8241 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8242 << SourceRange(D.getIdentifierLoc()); 8243 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8244 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8245 SourceLocation(), 8246 D.getDeclSpec().getConstSpecLoc(), 8247 D.getDeclSpec().getVolatileSpecLoc(), 8248 D.getDeclSpec().getRestrictSpecLoc(), 8249 D.getDeclSpec().getAtomicSpecLoc()); 8250 D.setInvalidType(); 8251 } 8252 } 8253 8254 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8255 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8256 if (FTI.TypeQuals & Qualifiers::Const) 8257 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8258 << "const" << SourceRange(D.getIdentifierLoc()); 8259 if (FTI.TypeQuals & Qualifiers::Volatile) 8260 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8261 << "volatile" << SourceRange(D.getIdentifierLoc()); 8262 if (FTI.TypeQuals & Qualifiers::Restrict) 8263 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8264 << "restrict" << SourceRange(D.getIdentifierLoc()); 8265 D.setInvalidType(); 8266 } 8267 8268 // C++0x [class.dtor]p2: 8269 // A destructor shall not be declared with a ref-qualifier. 8270 if (FTI.hasRefQualifier()) { 8271 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8272 << FTI.RefQualifierIsLValueRef 8273 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8274 D.setInvalidType(); 8275 } 8276 8277 // Make sure we don't have any parameters. 8278 if (FTIHasNonVoidParameters(FTI)) { 8279 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8280 8281 // Delete the parameters. 8282 FTI.freeParams(); 8283 D.setInvalidType(); 8284 } 8285 8286 // Make sure the destructor isn't variadic. 8287 if (FTI.isVariadic) { 8288 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8289 D.setInvalidType(); 8290 } 8291 8292 // Rebuild the function type "R" without any type qualifiers or 8293 // parameters (in case any of the errors above fired) and with 8294 // "void" as the return type, since destructors don't have return 8295 // types. 8296 if (!D.isInvalidType()) 8297 return R; 8298 8299 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8300 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8301 EPI.Variadic = false; 8302 EPI.TypeQuals = 0; 8303 EPI.RefQualifier = RQ_None; 8304 return Context.getFunctionType(Context.VoidTy, None, EPI); 8305 } 8306 8307 static void extendLeft(SourceRange &R, SourceRange Before) { 8308 if (Before.isInvalid()) 8309 return; 8310 R.setBegin(Before.getBegin()); 8311 if (R.getEnd().isInvalid()) 8312 R.setEnd(Before.getEnd()); 8313 } 8314 8315 static void extendRight(SourceRange &R, SourceRange After) { 8316 if (After.isInvalid()) 8317 return; 8318 if (R.getBegin().isInvalid()) 8319 R.setBegin(After.getBegin()); 8320 R.setEnd(After.getEnd()); 8321 } 8322 8323 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8324 /// well-formednes of the conversion function declarator @p D with 8325 /// type @p R. If there are any errors in the declarator, this routine 8326 /// will emit diagnostics and return true. Otherwise, it will return 8327 /// false. Either way, the type @p R will be updated to reflect a 8328 /// well-formed type for the conversion operator. 8329 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8330 StorageClass& SC) { 8331 // C++ [class.conv.fct]p1: 8332 // Neither parameter types nor return type can be specified. The 8333 // type of a conversion function (8.3.5) is "function taking no 8334 // parameter returning conversion-type-id." 8335 if (SC == SC_Static) { 8336 if (!D.isInvalidType()) 8337 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8338 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8339 << D.getName().getSourceRange(); 8340 D.setInvalidType(); 8341 SC = SC_None; 8342 } 8343 8344 TypeSourceInfo *ConvTSI = nullptr; 8345 QualType ConvType = 8346 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8347 8348 const DeclSpec &DS = D.getDeclSpec(); 8349 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8350 // Conversion functions don't have return types, but the parser will 8351 // happily parse something like: 8352 // 8353 // class X { 8354 // float operator bool(); 8355 // }; 8356 // 8357 // The return type will be changed later anyway. 8358 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8359 << SourceRange(DS.getTypeSpecTypeLoc()) 8360 << SourceRange(D.getIdentifierLoc()); 8361 D.setInvalidType(); 8362 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8363 // It's also plausible that the user writes type qualifiers in the wrong 8364 // place, such as: 8365 // struct S { const operator int(); }; 8366 // FIXME: we could provide a fixit to move the qualifiers onto the 8367 // conversion type. 8368 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8369 << SourceRange(D.getIdentifierLoc()) << 0; 8370 D.setInvalidType(); 8371 } 8372 8373 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8374 8375 // Make sure we don't have any parameters. 8376 if (Proto->getNumParams() > 0) { 8377 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8378 8379 // Delete the parameters. 8380 D.getFunctionTypeInfo().freeParams(); 8381 D.setInvalidType(); 8382 } else if (Proto->isVariadic()) { 8383 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8384 D.setInvalidType(); 8385 } 8386 8387 // Diagnose "&operator bool()" and other such nonsense. This 8388 // is actually a gcc extension which we don't support. 8389 if (Proto->getReturnType() != ConvType) { 8390 bool NeedsTypedef = false; 8391 SourceRange Before, After; 8392 8393 // Walk the chunks and extract information on them for our diagnostic. 8394 bool PastFunctionChunk = false; 8395 for (auto &Chunk : D.type_objects()) { 8396 switch (Chunk.Kind) { 8397 case DeclaratorChunk::Function: 8398 if (!PastFunctionChunk) { 8399 if (Chunk.Fun.HasTrailingReturnType) { 8400 TypeSourceInfo *TRT = nullptr; 8401 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8402 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8403 } 8404 PastFunctionChunk = true; 8405 break; 8406 } 8407 LLVM_FALLTHROUGH; 8408 case DeclaratorChunk::Array: 8409 NeedsTypedef = true; 8410 extendRight(After, Chunk.getSourceRange()); 8411 break; 8412 8413 case DeclaratorChunk::Pointer: 8414 case DeclaratorChunk::BlockPointer: 8415 case DeclaratorChunk::Reference: 8416 case DeclaratorChunk::MemberPointer: 8417 case DeclaratorChunk::Pipe: 8418 extendLeft(Before, Chunk.getSourceRange()); 8419 break; 8420 8421 case DeclaratorChunk::Paren: 8422 extendLeft(Before, Chunk.Loc); 8423 extendRight(After, Chunk.EndLoc); 8424 break; 8425 } 8426 } 8427 8428 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8429 After.isValid() ? After.getBegin() : 8430 D.getIdentifierLoc(); 8431 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8432 DB << Before << After; 8433 8434 if (!NeedsTypedef) { 8435 DB << /*don't need a typedef*/0; 8436 8437 // If we can provide a correct fix-it hint, do so. 8438 if (After.isInvalid() && ConvTSI) { 8439 SourceLocation InsertLoc = 8440 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8441 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8442 << FixItHint::CreateInsertionFromRange( 8443 InsertLoc, CharSourceRange::getTokenRange(Before)) 8444 << FixItHint::CreateRemoval(Before); 8445 } 8446 } else if (!Proto->getReturnType()->isDependentType()) { 8447 DB << /*typedef*/1 << Proto->getReturnType(); 8448 } else if (getLangOpts().CPlusPlus11) { 8449 DB << /*alias template*/2 << Proto->getReturnType(); 8450 } else { 8451 DB << /*might not be fixable*/3; 8452 } 8453 8454 // Recover by incorporating the other type chunks into the result type. 8455 // Note, this does *not* change the name of the function. This is compatible 8456 // with the GCC extension: 8457 // struct S { &operator int(); } s; 8458 // int &r = s.operator int(); // ok in GCC 8459 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8460 ConvType = Proto->getReturnType(); 8461 } 8462 8463 // C++ [class.conv.fct]p4: 8464 // The conversion-type-id shall not represent a function type nor 8465 // an array type. 8466 if (ConvType->isArrayType()) { 8467 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8468 ConvType = Context.getPointerType(ConvType); 8469 D.setInvalidType(); 8470 } else if (ConvType->isFunctionType()) { 8471 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8472 ConvType = Context.getPointerType(ConvType); 8473 D.setInvalidType(); 8474 } 8475 8476 // Rebuild the function type "R" without any parameters (in case any 8477 // of the errors above fired) and with the conversion type as the 8478 // return type. 8479 if (D.isInvalidType()) 8480 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8481 8482 // C++0x explicit conversion operators. 8483 if (DS.isExplicitSpecified()) 8484 Diag(DS.getExplicitSpecLoc(), 8485 getLangOpts().CPlusPlus11 8486 ? diag::warn_cxx98_compat_explicit_conversion_functions 8487 : diag::ext_explicit_conversion_functions) 8488 << SourceRange(DS.getExplicitSpecLoc()); 8489 } 8490 8491 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8492 /// the declaration of the given C++ conversion function. This routine 8493 /// is responsible for recording the conversion function in the C++ 8494 /// class, if possible. 8495 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8496 assert(Conversion && "Expected to receive a conversion function declaration"); 8497 8498 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8499 8500 // Make sure we aren't redeclaring the conversion function. 8501 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8502 8503 // C++ [class.conv.fct]p1: 8504 // [...] A conversion function is never used to convert a 8505 // (possibly cv-qualified) object to the (possibly cv-qualified) 8506 // same object type (or a reference to it), to a (possibly 8507 // cv-qualified) base class of that type (or a reference to it), 8508 // or to (possibly cv-qualified) void. 8509 // FIXME: Suppress this warning if the conversion function ends up being a 8510 // virtual function that overrides a virtual function in a base class. 8511 QualType ClassType 8512 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8513 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8514 ConvType = ConvTypeRef->getPointeeType(); 8515 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8516 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8517 /* Suppress diagnostics for instantiations. */; 8518 else if (ConvType->isRecordType()) { 8519 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8520 if (ConvType == ClassType) 8521 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8522 << ClassType; 8523 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8524 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8525 << ClassType << ConvType; 8526 } else if (ConvType->isVoidType()) { 8527 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8528 << ClassType << ConvType; 8529 } 8530 8531 if (FunctionTemplateDecl *ConversionTemplate 8532 = Conversion->getDescribedFunctionTemplate()) 8533 return ConversionTemplate; 8534 8535 return Conversion; 8536 } 8537 8538 namespace { 8539 /// Utility class to accumulate and print a diagnostic listing the invalid 8540 /// specifier(s) on a declaration. 8541 struct BadSpecifierDiagnoser { 8542 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8543 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8544 ~BadSpecifierDiagnoser() { 8545 Diagnostic << Specifiers; 8546 } 8547 8548 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8549 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8550 } 8551 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8552 return check(SpecLoc, 8553 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8554 } 8555 void check(SourceLocation SpecLoc, const char *Spec) { 8556 if (SpecLoc.isInvalid()) return; 8557 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8558 if (!Specifiers.empty()) Specifiers += " "; 8559 Specifiers += Spec; 8560 } 8561 8562 Sema &S; 8563 Sema::SemaDiagnosticBuilder Diagnostic; 8564 std::string Specifiers; 8565 }; 8566 } 8567 8568 /// Check the validity of a declarator that we parsed for a deduction-guide. 8569 /// These aren't actually declarators in the grammar, so we need to check that 8570 /// the user didn't specify any pieces that are not part of the deduction-guide 8571 /// grammar. 8572 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8573 StorageClass &SC) { 8574 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8575 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8576 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8577 8578 // C++ [temp.deduct.guide]p3: 8579 // A deduction-gide shall be declared in the same scope as the 8580 // corresponding class template. 8581 if (!CurContext->getRedeclContext()->Equals( 8582 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8583 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8584 << GuidedTemplateDecl; 8585 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8586 } 8587 8588 auto &DS = D.getMutableDeclSpec(); 8589 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8590 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8591 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8592 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8593 BadSpecifierDiagnoser Diagnoser( 8594 *this, D.getIdentifierLoc(), 8595 diag::err_deduction_guide_invalid_specifier); 8596 8597 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8598 DS.ClearStorageClassSpecs(); 8599 SC = SC_None; 8600 8601 // 'explicit' is permitted. 8602 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8603 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8604 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8605 DS.ClearConstexprSpec(); 8606 8607 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8608 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8609 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8610 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8611 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8612 DS.ClearTypeQualifiers(); 8613 8614 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8615 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8616 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8617 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8618 DS.ClearTypeSpecType(); 8619 } 8620 8621 if (D.isInvalidType()) 8622 return; 8623 8624 // Check the declarator is simple enough. 8625 bool FoundFunction = false; 8626 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8627 if (Chunk.Kind == DeclaratorChunk::Paren) 8628 continue; 8629 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8630 Diag(D.getDeclSpec().getLocStart(), 8631 diag::err_deduction_guide_with_complex_decl) 8632 << D.getSourceRange(); 8633 break; 8634 } 8635 if (!Chunk.Fun.hasTrailingReturnType()) { 8636 Diag(D.getName().getLocStart(), 8637 diag::err_deduction_guide_no_trailing_return_type); 8638 break; 8639 } 8640 8641 // Check that the return type is written as a specialization of 8642 // the template specified as the deduction-guide's name. 8643 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8644 TypeSourceInfo *TSI = nullptr; 8645 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8646 assert(TSI && "deduction guide has valid type but invalid return type?"); 8647 bool AcceptableReturnType = false; 8648 bool MightInstantiateToSpecialization = false; 8649 if (auto RetTST = 8650 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8651 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8652 bool TemplateMatches = 8653 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8654 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8655 AcceptableReturnType = true; 8656 else { 8657 // This could still instantiate to the right type, unless we know it 8658 // names the wrong class template. 8659 auto *TD = SpecifiedName.getAsTemplateDecl(); 8660 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8661 !TemplateMatches); 8662 } 8663 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8664 MightInstantiateToSpecialization = true; 8665 } 8666 8667 if (!AcceptableReturnType) { 8668 Diag(TSI->getTypeLoc().getLocStart(), 8669 diag::err_deduction_guide_bad_trailing_return_type) 8670 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8671 << TSI->getTypeLoc().getSourceRange(); 8672 } 8673 8674 // Keep going to check that we don't have any inner declarator pieces (we 8675 // could still have a function returning a pointer to a function). 8676 FoundFunction = true; 8677 } 8678 8679 if (D.isFunctionDefinition()) 8680 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8681 } 8682 8683 //===----------------------------------------------------------------------===// 8684 // Namespace Handling 8685 //===----------------------------------------------------------------------===// 8686 8687 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8688 /// reopened. 8689 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8690 SourceLocation Loc, 8691 IdentifierInfo *II, bool *IsInline, 8692 NamespaceDecl *PrevNS) { 8693 assert(*IsInline != PrevNS->isInline()); 8694 8695 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8696 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8697 // inline namespaces, with the intention of bringing names into namespace std. 8698 // 8699 // We support this just well enough to get that case working; this is not 8700 // sufficient to support reopening namespaces as inline in general. 8701 if (*IsInline && II && II->getName().startswith("__atomic") && 8702 S.getSourceManager().isInSystemHeader(Loc)) { 8703 // Mark all prior declarations of the namespace as inline. 8704 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8705 NS = NS->getPreviousDecl()) 8706 NS->setInline(*IsInline); 8707 // Patch up the lookup table for the containing namespace. This isn't really 8708 // correct, but it's good enough for this particular case. 8709 for (auto *I : PrevNS->decls()) 8710 if (auto *ND = dyn_cast<NamedDecl>(I)) 8711 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8712 return; 8713 } 8714 8715 if (PrevNS->isInline()) 8716 // The user probably just forgot the 'inline', so suggest that it 8717 // be added back. 8718 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8719 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8720 else 8721 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8722 8723 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8724 *IsInline = PrevNS->isInline(); 8725 } 8726 8727 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8728 /// definition. 8729 Decl *Sema::ActOnStartNamespaceDef( 8730 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 8731 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 8732 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 8733 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8734 // For anonymous namespace, take the location of the left brace. 8735 SourceLocation Loc = II ? IdentLoc : LBrace; 8736 bool IsInline = InlineLoc.isValid(); 8737 bool IsInvalid = false; 8738 bool IsStd = false; 8739 bool AddToKnown = false; 8740 Scope *DeclRegionScope = NamespcScope->getParent(); 8741 8742 NamespaceDecl *PrevNS = nullptr; 8743 if (II) { 8744 // C++ [namespace.def]p2: 8745 // The identifier in an original-namespace-definition shall not 8746 // have been previously defined in the declarative region in 8747 // which the original-namespace-definition appears. The 8748 // identifier in an original-namespace-definition is the name of 8749 // the namespace. Subsequently in that declarative region, it is 8750 // treated as an original-namespace-name. 8751 // 8752 // Since namespace names are unique in their scope, and we don't 8753 // look through using directives, just look for any ordinary names 8754 // as if by qualified name lookup. 8755 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8756 ForExternalRedeclaration); 8757 LookupQualifiedName(R, CurContext->getRedeclContext()); 8758 NamedDecl *PrevDecl = 8759 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8760 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8761 8762 if (PrevNS) { 8763 // This is an extended namespace definition. 8764 if (IsInline != PrevNS->isInline()) 8765 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8766 &IsInline, PrevNS); 8767 } else if (PrevDecl) { 8768 // This is an invalid name redefinition. 8769 Diag(Loc, diag::err_redefinition_different_kind) 8770 << II; 8771 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8772 IsInvalid = true; 8773 // Continue on to push Namespc as current DeclContext and return it. 8774 } else if (II->isStr("std") && 8775 CurContext->getRedeclContext()->isTranslationUnit()) { 8776 // This is the first "real" definition of the namespace "std", so update 8777 // our cache of the "std" namespace to point at this definition. 8778 PrevNS = getStdNamespace(); 8779 IsStd = true; 8780 AddToKnown = !IsInline; 8781 } else { 8782 // We've seen this namespace for the first time. 8783 AddToKnown = !IsInline; 8784 } 8785 } else { 8786 // Anonymous namespaces. 8787 8788 // Determine whether the parent already has an anonymous namespace. 8789 DeclContext *Parent = CurContext->getRedeclContext(); 8790 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8791 PrevNS = TU->getAnonymousNamespace(); 8792 } else { 8793 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8794 PrevNS = ND->getAnonymousNamespace(); 8795 } 8796 8797 if (PrevNS && IsInline != PrevNS->isInline()) 8798 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8799 &IsInline, PrevNS); 8800 } 8801 8802 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8803 StartLoc, Loc, II, PrevNS); 8804 if (IsInvalid) 8805 Namespc->setInvalidDecl(); 8806 8807 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8808 AddPragmaAttributes(DeclRegionScope, Namespc); 8809 8810 // FIXME: Should we be merging attributes? 8811 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8812 PushNamespaceVisibilityAttr(Attr, Loc); 8813 8814 if (IsStd) 8815 StdNamespace = Namespc; 8816 if (AddToKnown) 8817 KnownNamespaces[Namespc] = false; 8818 8819 if (II) { 8820 PushOnScopeChains(Namespc, DeclRegionScope); 8821 } else { 8822 // Link the anonymous namespace into its parent. 8823 DeclContext *Parent = CurContext->getRedeclContext(); 8824 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8825 TU->setAnonymousNamespace(Namespc); 8826 } else { 8827 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8828 } 8829 8830 CurContext->addDecl(Namespc); 8831 8832 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8833 // behaves as if it were replaced by 8834 // namespace unique { /* empty body */ } 8835 // using namespace unique; 8836 // namespace unique { namespace-body } 8837 // where all occurrences of 'unique' in a translation unit are 8838 // replaced by the same identifier and this identifier differs 8839 // from all other identifiers in the entire program. 8840 8841 // We just create the namespace with an empty name and then add an 8842 // implicit using declaration, just like the standard suggests. 8843 // 8844 // CodeGen enforces the "universally unique" aspect by giving all 8845 // declarations semantically contained within an anonymous 8846 // namespace internal linkage. 8847 8848 if (!PrevNS) { 8849 UD = UsingDirectiveDecl::Create(Context, Parent, 8850 /* 'using' */ LBrace, 8851 /* 'namespace' */ SourceLocation(), 8852 /* qualifier */ NestedNameSpecifierLoc(), 8853 /* identifier */ SourceLocation(), 8854 Namespc, 8855 /* Ancestor */ Parent); 8856 UD->setImplicit(); 8857 Parent->addDecl(UD); 8858 } 8859 } 8860 8861 ActOnDocumentableDecl(Namespc); 8862 8863 // Although we could have an invalid decl (i.e. the namespace name is a 8864 // redefinition), push it as current DeclContext and try to continue parsing. 8865 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8866 // for the namespace has the declarations that showed up in that particular 8867 // namespace definition. 8868 PushDeclContext(NamespcScope, Namespc); 8869 return Namespc; 8870 } 8871 8872 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8873 /// is a namespace alias, returns the namespace it points to. 8874 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8875 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8876 return AD->getNamespace(); 8877 return dyn_cast_or_null<NamespaceDecl>(D); 8878 } 8879 8880 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8881 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8882 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8883 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8884 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8885 Namespc->setRBraceLoc(RBrace); 8886 PopDeclContext(); 8887 if (Namespc->hasAttr<VisibilityAttr>()) 8888 PopPragmaVisibility(true, RBrace); 8889 } 8890 8891 CXXRecordDecl *Sema::getStdBadAlloc() const { 8892 return cast_or_null<CXXRecordDecl>( 8893 StdBadAlloc.get(Context.getExternalSource())); 8894 } 8895 8896 EnumDecl *Sema::getStdAlignValT() const { 8897 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8898 } 8899 8900 NamespaceDecl *Sema::getStdNamespace() const { 8901 return cast_or_null<NamespaceDecl>( 8902 StdNamespace.get(Context.getExternalSource())); 8903 } 8904 8905 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8906 if (!StdExperimentalNamespaceCache) { 8907 if (auto Std = getStdNamespace()) { 8908 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8909 SourceLocation(), LookupNamespaceName); 8910 if (!LookupQualifiedName(Result, Std) || 8911 !(StdExperimentalNamespaceCache = 8912 Result.getAsSingle<NamespaceDecl>())) 8913 Result.suppressDiagnostics(); 8914 } 8915 } 8916 return StdExperimentalNamespaceCache; 8917 } 8918 8919 namespace { 8920 8921 enum UnsupportedSTLSelect { 8922 USS_InvalidMember, 8923 USS_MissingMember, 8924 USS_NonTrivial, 8925 USS_Other 8926 }; 8927 8928 struct InvalidSTLDiagnoser { 8929 Sema &S; 8930 SourceLocation Loc; 8931 QualType TyForDiags; 8932 8933 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 8934 const VarDecl *VD = nullptr) { 8935 { 8936 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 8937 << TyForDiags << ((int)Sel); 8938 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 8939 assert(!Name.empty()); 8940 D << Name; 8941 } 8942 } 8943 if (Sel == USS_InvalidMember) { 8944 S.Diag(VD->getLocation(), diag::note_var_declared_here) 8945 << VD << VD->getSourceRange(); 8946 } 8947 return QualType(); 8948 } 8949 }; 8950 } // namespace 8951 8952 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 8953 SourceLocation Loc) { 8954 assert(getLangOpts().CPlusPlus && 8955 "Looking for comparison category type outside of C++."); 8956 8957 // Check if we've already successfully checked the comparison category type 8958 // before. If so, skip checking it again. 8959 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 8960 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 8961 return Info->getType(); 8962 8963 // If lookup failed 8964 if (!Info) { 8965 std::string NameForDiags = "std::"; 8966 NameForDiags += ComparisonCategories::getCategoryString(Kind); 8967 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 8968 << NameForDiags; 8969 return QualType(); 8970 } 8971 8972 assert(Info->Kind == Kind); 8973 assert(Info->Record); 8974 8975 // Update the Record decl in case we encountered a forward declaration on our 8976 // first pass. FIXME: This is a bit of a hack. 8977 if (Info->Record->hasDefinition()) 8978 Info->Record = Info->Record->getDefinition(); 8979 8980 // Use an elaborated type for diagnostics which has a name containing the 8981 // prepended 'std' namespace but not any inline namespace names. 8982 QualType TyForDiags = [&]() { 8983 auto *NNS = 8984 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 8985 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 8986 }(); 8987 8988 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 8989 return QualType(); 8990 8991 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 8992 8993 if (!Info->Record->isTriviallyCopyable()) 8994 return UnsupportedSTLError(USS_NonTrivial); 8995 8996 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 8997 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 8998 // Tolerate empty base classes. 8999 if (Base->isEmpty()) 9000 continue; 9001 // Reject STL implementations which have at least one non-empty base. 9002 return UnsupportedSTLError(); 9003 } 9004 9005 // Check that the STL has implemented the types using a single integer field. 9006 // This expectation allows better codegen for builtin operators. We require: 9007 // (1) The class has exactly one field. 9008 // (2) The field is an integral or enumeration type. 9009 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9010 if (std::distance(FIt, FEnd) != 1 || 9011 !FIt->getType()->isIntegralOrEnumerationType()) { 9012 return UnsupportedSTLError(); 9013 } 9014 9015 // Build each of the require values and store them in Info. 9016 for (ComparisonCategoryResult CCR : 9017 ComparisonCategories::getPossibleResultsForType(Kind)) { 9018 StringRef MemName = ComparisonCategories::getResultString(CCR); 9019 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9020 9021 if (!ValInfo) 9022 return UnsupportedSTLError(USS_MissingMember, MemName); 9023 9024 VarDecl *VD = ValInfo->VD; 9025 assert(VD && "should not be null!"); 9026 9027 // Attempt to diagnose reasons why the STL definition of this type 9028 // might be foobar, including it failing to be a constant expression. 9029 // TODO Handle more ways the lookup or result can be invalid. 9030 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9031 !VD->checkInitIsICE()) 9032 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9033 9034 // Attempt to evaluate the var decl as a constant expression and extract 9035 // the value of its first field as a ICE. If this fails, the STL 9036 // implementation is not supported. 9037 if (!ValInfo->hasValidIntValue()) 9038 return UnsupportedSTLError(); 9039 9040 MarkVariableReferenced(Loc, VD); 9041 } 9042 9043 // We've successfully built the required types and expressions. Update 9044 // the cache and return the newly cached value. 9045 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9046 return Info->getType(); 9047 } 9048 9049 /// Retrieve the special "std" namespace, which may require us to 9050 /// implicitly define the namespace. 9051 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9052 if (!StdNamespace) { 9053 // The "std" namespace has not yet been defined, so build one implicitly. 9054 StdNamespace = NamespaceDecl::Create(Context, 9055 Context.getTranslationUnitDecl(), 9056 /*Inline=*/false, 9057 SourceLocation(), SourceLocation(), 9058 &PP.getIdentifierTable().get("std"), 9059 /*PrevDecl=*/nullptr); 9060 getStdNamespace()->setImplicit(true); 9061 } 9062 9063 return getStdNamespace(); 9064 } 9065 9066 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9067 assert(getLangOpts().CPlusPlus && 9068 "Looking for std::initializer_list outside of C++."); 9069 9070 // We're looking for implicit instantiations of 9071 // template <typename E> class std::initializer_list. 9072 9073 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9074 return false; 9075 9076 ClassTemplateDecl *Template = nullptr; 9077 const TemplateArgument *Arguments = nullptr; 9078 9079 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9080 9081 ClassTemplateSpecializationDecl *Specialization = 9082 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9083 if (!Specialization) 9084 return false; 9085 9086 Template = Specialization->getSpecializedTemplate(); 9087 Arguments = Specialization->getTemplateArgs().data(); 9088 } else if (const TemplateSpecializationType *TST = 9089 Ty->getAs<TemplateSpecializationType>()) { 9090 Template = dyn_cast_or_null<ClassTemplateDecl>( 9091 TST->getTemplateName().getAsTemplateDecl()); 9092 Arguments = TST->getArgs(); 9093 } 9094 if (!Template) 9095 return false; 9096 9097 if (!StdInitializerList) { 9098 // Haven't recognized std::initializer_list yet, maybe this is it. 9099 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9100 if (TemplateClass->getIdentifier() != 9101 &PP.getIdentifierTable().get("initializer_list") || 9102 !getStdNamespace()->InEnclosingNamespaceSetOf( 9103 TemplateClass->getDeclContext())) 9104 return false; 9105 // This is a template called std::initializer_list, but is it the right 9106 // template? 9107 TemplateParameterList *Params = Template->getTemplateParameters(); 9108 if (Params->getMinRequiredArguments() != 1) 9109 return false; 9110 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9111 return false; 9112 9113 // It's the right template. 9114 StdInitializerList = Template; 9115 } 9116 9117 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9118 return false; 9119 9120 // This is an instance of std::initializer_list. Find the argument type. 9121 if (Element) 9122 *Element = Arguments[0].getAsType(); 9123 return true; 9124 } 9125 9126 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9127 NamespaceDecl *Std = S.getStdNamespace(); 9128 if (!Std) { 9129 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9130 return nullptr; 9131 } 9132 9133 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9134 Loc, Sema::LookupOrdinaryName); 9135 if (!S.LookupQualifiedName(Result, Std)) { 9136 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9137 return nullptr; 9138 } 9139 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9140 if (!Template) { 9141 Result.suppressDiagnostics(); 9142 // We found something weird. Complain about the first thing we found. 9143 NamedDecl *Found = *Result.begin(); 9144 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9145 return nullptr; 9146 } 9147 9148 // We found some template called std::initializer_list. Now verify that it's 9149 // correct. 9150 TemplateParameterList *Params = Template->getTemplateParameters(); 9151 if (Params->getMinRequiredArguments() != 1 || 9152 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9153 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9154 return nullptr; 9155 } 9156 9157 return Template; 9158 } 9159 9160 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9161 if (!StdInitializerList) { 9162 StdInitializerList = LookupStdInitializerList(*this, Loc); 9163 if (!StdInitializerList) 9164 return QualType(); 9165 } 9166 9167 TemplateArgumentListInfo Args(Loc, Loc); 9168 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9169 Context.getTrivialTypeSourceInfo(Element, 9170 Loc))); 9171 return Context.getCanonicalType( 9172 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9173 } 9174 9175 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9176 // C++ [dcl.init.list]p2: 9177 // A constructor is an initializer-list constructor if its first parameter 9178 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9179 // std::initializer_list<E> for some type E, and either there are no other 9180 // parameters or else all other parameters have default arguments. 9181 if (Ctor->getNumParams() < 1 || 9182 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9183 return false; 9184 9185 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9186 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9187 ArgType = RT->getPointeeType().getUnqualifiedType(); 9188 9189 return isStdInitializerList(ArgType, nullptr); 9190 } 9191 9192 /// Determine whether a using statement is in a context where it will be 9193 /// apply in all contexts. 9194 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9195 switch (CurContext->getDeclKind()) { 9196 case Decl::TranslationUnit: 9197 return true; 9198 case Decl::LinkageSpec: 9199 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9200 default: 9201 return false; 9202 } 9203 } 9204 9205 namespace { 9206 9207 // Callback to only accept typo corrections that are namespaces. 9208 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9209 public: 9210 bool ValidateCandidate(const TypoCorrection &candidate) override { 9211 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9212 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9213 return false; 9214 } 9215 }; 9216 9217 } 9218 9219 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9220 CXXScopeSpec &SS, 9221 SourceLocation IdentLoc, 9222 IdentifierInfo *Ident) { 9223 R.clear(); 9224 if (TypoCorrection Corrected = 9225 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9226 llvm::make_unique<NamespaceValidatorCCC>(), 9227 Sema::CTK_ErrorRecovery)) { 9228 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9229 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9230 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9231 Ident->getName().equals(CorrectedStr); 9232 S.diagnoseTypo(Corrected, 9233 S.PDiag(diag::err_using_directive_member_suggest) 9234 << Ident << DC << DroppedSpecifier << SS.getRange(), 9235 S.PDiag(diag::note_namespace_defined_here)); 9236 } else { 9237 S.diagnoseTypo(Corrected, 9238 S.PDiag(diag::err_using_directive_suggest) << Ident, 9239 S.PDiag(diag::note_namespace_defined_here)); 9240 } 9241 R.addDecl(Corrected.getFoundDecl()); 9242 return true; 9243 } 9244 return false; 9245 } 9246 9247 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9248 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9249 SourceLocation IdentLoc, 9250 IdentifierInfo *NamespcName, 9251 const ParsedAttributesView &AttrList) { 9252 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9253 assert(NamespcName && "Invalid NamespcName."); 9254 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9255 9256 // This can only happen along a recovery path. 9257 while (S->isTemplateParamScope()) 9258 S = S->getParent(); 9259 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9260 9261 UsingDirectiveDecl *UDir = nullptr; 9262 NestedNameSpecifier *Qualifier = nullptr; 9263 if (SS.isSet()) 9264 Qualifier = SS.getScopeRep(); 9265 9266 // Lookup namespace name. 9267 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9268 LookupParsedName(R, S, &SS); 9269 if (R.isAmbiguous()) 9270 return nullptr; 9271 9272 if (R.empty()) { 9273 R.clear(); 9274 // Allow "using namespace std;" or "using namespace ::std;" even if 9275 // "std" hasn't been defined yet, for GCC compatibility. 9276 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9277 NamespcName->isStr("std")) { 9278 Diag(IdentLoc, diag::ext_using_undefined_std); 9279 R.addDecl(getOrCreateStdNamespace()); 9280 R.resolveKind(); 9281 } 9282 // Otherwise, attempt typo correction. 9283 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9284 } 9285 9286 if (!R.empty()) { 9287 NamedDecl *Named = R.getRepresentativeDecl(); 9288 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9289 assert(NS && "expected namespace decl"); 9290 9291 // The use of a nested name specifier may trigger deprecation warnings. 9292 DiagnoseUseOfDecl(Named, IdentLoc); 9293 9294 // C++ [namespace.udir]p1: 9295 // A using-directive specifies that the names in the nominated 9296 // namespace can be used in the scope in which the 9297 // using-directive appears after the using-directive. During 9298 // unqualified name lookup (3.4.1), the names appear as if they 9299 // were declared in the nearest enclosing namespace which 9300 // contains both the using-directive and the nominated 9301 // namespace. [Note: in this context, "contains" means "contains 9302 // directly or indirectly". ] 9303 9304 // Find enclosing context containing both using-directive and 9305 // nominated namespace. 9306 DeclContext *CommonAncestor = NS; 9307 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9308 CommonAncestor = CommonAncestor->getParent(); 9309 9310 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9311 SS.getWithLocInContext(Context), 9312 IdentLoc, Named, CommonAncestor); 9313 9314 if (IsUsingDirectiveInToplevelContext(CurContext) && 9315 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9316 Diag(IdentLoc, diag::warn_using_directive_in_header); 9317 } 9318 9319 PushUsingDirective(S, UDir); 9320 } else { 9321 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9322 } 9323 9324 if (UDir) 9325 ProcessDeclAttributeList(S, UDir, AttrList); 9326 9327 return UDir; 9328 } 9329 9330 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9331 // If the scope has an associated entity and the using directive is at 9332 // namespace or translation unit scope, add the UsingDirectiveDecl into 9333 // its lookup structure so qualified name lookup can find it. 9334 DeclContext *Ctx = S->getEntity(); 9335 if (Ctx && !Ctx->isFunctionOrMethod()) 9336 Ctx->addDecl(UDir); 9337 else 9338 // Otherwise, it is at block scope. The using-directives will affect lookup 9339 // only to the end of the scope. 9340 S->PushUsingDirective(UDir); 9341 } 9342 9343 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9344 SourceLocation UsingLoc, 9345 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9346 UnqualifiedId &Name, 9347 SourceLocation EllipsisLoc, 9348 const ParsedAttributesView &AttrList) { 9349 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9350 9351 if (SS.isEmpty()) { 9352 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 9353 return nullptr; 9354 } 9355 9356 switch (Name.getKind()) { 9357 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9358 case UnqualifiedIdKind::IK_Identifier: 9359 case UnqualifiedIdKind::IK_OperatorFunctionId: 9360 case UnqualifiedIdKind::IK_LiteralOperatorId: 9361 case UnqualifiedIdKind::IK_ConversionFunctionId: 9362 break; 9363 9364 case UnqualifiedIdKind::IK_ConstructorName: 9365 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9366 // C++11 inheriting constructors. 9367 Diag(Name.getLocStart(), 9368 getLangOpts().CPlusPlus11 ? 9369 diag::warn_cxx98_compat_using_decl_constructor : 9370 diag::err_using_decl_constructor) 9371 << SS.getRange(); 9372 9373 if (getLangOpts().CPlusPlus11) break; 9374 9375 return nullptr; 9376 9377 case UnqualifiedIdKind::IK_DestructorName: 9378 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9379 << SS.getRange(); 9380 return nullptr; 9381 9382 case UnqualifiedIdKind::IK_TemplateId: 9383 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9384 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9385 return nullptr; 9386 9387 case UnqualifiedIdKind::IK_DeductionGuideName: 9388 llvm_unreachable("cannot parse qualified deduction guide name"); 9389 } 9390 9391 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9392 DeclarationName TargetName = TargetNameInfo.getName(); 9393 if (!TargetName) 9394 return nullptr; 9395 9396 // Warn about access declarations. 9397 if (UsingLoc.isInvalid()) { 9398 Diag(Name.getLocStart(), 9399 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9400 : diag::warn_access_decl_deprecated) 9401 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9402 } 9403 9404 if (EllipsisLoc.isInvalid()) { 9405 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9406 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9407 return nullptr; 9408 } else { 9409 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9410 !TargetNameInfo.containsUnexpandedParameterPack()) { 9411 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9412 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9413 EllipsisLoc = SourceLocation(); 9414 } 9415 } 9416 9417 NamedDecl *UD = 9418 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9419 SS, TargetNameInfo, EllipsisLoc, AttrList, 9420 /*IsInstantiation*/false); 9421 if (UD) 9422 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9423 9424 return UD; 9425 } 9426 9427 /// Determine whether a using declaration considers the given 9428 /// declarations as "equivalent", e.g., if they are redeclarations of 9429 /// the same entity or are both typedefs of the same type. 9430 static bool 9431 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9432 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9433 return true; 9434 9435 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9436 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9437 return Context.hasSameType(TD1->getUnderlyingType(), 9438 TD2->getUnderlyingType()); 9439 9440 return false; 9441 } 9442 9443 9444 /// Determines whether to create a using shadow decl for a particular 9445 /// decl, given the set of decls existing prior to this using lookup. 9446 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9447 const LookupResult &Previous, 9448 UsingShadowDecl *&PrevShadow) { 9449 // Diagnose finding a decl which is not from a base class of the 9450 // current class. We do this now because there are cases where this 9451 // function will silently decide not to build a shadow decl, which 9452 // will pre-empt further diagnostics. 9453 // 9454 // We don't need to do this in C++11 because we do the check once on 9455 // the qualifier. 9456 // 9457 // FIXME: diagnose the following if we care enough: 9458 // struct A { int foo; }; 9459 // struct B : A { using A::foo; }; 9460 // template <class T> struct C : A {}; 9461 // template <class T> struct D : C<T> { using B::foo; } // <--- 9462 // This is invalid (during instantiation) in C++03 because B::foo 9463 // resolves to the using decl in B, which is not a base class of D<T>. 9464 // We can't diagnose it immediately because C<T> is an unknown 9465 // specialization. The UsingShadowDecl in D<T> then points directly 9466 // to A::foo, which will look well-formed when we instantiate. 9467 // The right solution is to not collapse the shadow-decl chain. 9468 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9469 DeclContext *OrigDC = Orig->getDeclContext(); 9470 9471 // Handle enums and anonymous structs. 9472 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9473 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9474 while (OrigRec->isAnonymousStructOrUnion()) 9475 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9476 9477 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9478 if (OrigDC == CurContext) { 9479 Diag(Using->getLocation(), 9480 diag::err_using_decl_nested_name_specifier_is_current_class) 9481 << Using->getQualifierLoc().getSourceRange(); 9482 Diag(Orig->getLocation(), diag::note_using_decl_target); 9483 Using->setInvalidDecl(); 9484 return true; 9485 } 9486 9487 Diag(Using->getQualifierLoc().getBeginLoc(), 9488 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9489 << Using->getQualifier() 9490 << cast<CXXRecordDecl>(CurContext) 9491 << Using->getQualifierLoc().getSourceRange(); 9492 Diag(Orig->getLocation(), diag::note_using_decl_target); 9493 Using->setInvalidDecl(); 9494 return true; 9495 } 9496 } 9497 9498 if (Previous.empty()) return false; 9499 9500 NamedDecl *Target = Orig; 9501 if (isa<UsingShadowDecl>(Target)) 9502 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9503 9504 // If the target happens to be one of the previous declarations, we 9505 // don't have a conflict. 9506 // 9507 // FIXME: but we might be increasing its access, in which case we 9508 // should redeclare it. 9509 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9510 bool FoundEquivalentDecl = false; 9511 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9512 I != E; ++I) { 9513 NamedDecl *D = (*I)->getUnderlyingDecl(); 9514 // We can have UsingDecls in our Previous results because we use the same 9515 // LookupResult for checking whether the UsingDecl itself is a valid 9516 // redeclaration. 9517 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9518 continue; 9519 9520 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9521 // C++ [class.mem]p19: 9522 // If T is the name of a class, then [every named member other than 9523 // a non-static data member] shall have a name different from T 9524 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9525 !isa<IndirectFieldDecl>(Target) && 9526 !isa<UnresolvedUsingValueDecl>(Target) && 9527 DiagnoseClassNameShadow( 9528 CurContext, 9529 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9530 return true; 9531 } 9532 9533 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9534 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9535 PrevShadow = Shadow; 9536 FoundEquivalentDecl = true; 9537 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9538 // We don't conflict with an existing using shadow decl of an equivalent 9539 // declaration, but we're not a redeclaration of it. 9540 FoundEquivalentDecl = true; 9541 } 9542 9543 if (isVisible(D)) 9544 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9545 } 9546 9547 if (FoundEquivalentDecl) 9548 return false; 9549 9550 if (FunctionDecl *FD = Target->getAsFunction()) { 9551 NamedDecl *OldDecl = nullptr; 9552 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9553 /*IsForUsingDecl*/ true)) { 9554 case Ovl_Overload: 9555 return false; 9556 9557 case Ovl_NonFunction: 9558 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9559 break; 9560 9561 // We found a decl with the exact signature. 9562 case Ovl_Match: 9563 // If we're in a record, we want to hide the target, so we 9564 // return true (without a diagnostic) to tell the caller not to 9565 // build a shadow decl. 9566 if (CurContext->isRecord()) 9567 return true; 9568 9569 // If we're not in a record, this is an error. 9570 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9571 break; 9572 } 9573 9574 Diag(Target->getLocation(), diag::note_using_decl_target); 9575 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9576 Using->setInvalidDecl(); 9577 return true; 9578 } 9579 9580 // Target is not a function. 9581 9582 if (isa<TagDecl>(Target)) { 9583 // No conflict between a tag and a non-tag. 9584 if (!Tag) return false; 9585 9586 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9587 Diag(Target->getLocation(), diag::note_using_decl_target); 9588 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9589 Using->setInvalidDecl(); 9590 return true; 9591 } 9592 9593 // No conflict between a tag and a non-tag. 9594 if (!NonTag) return false; 9595 9596 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9597 Diag(Target->getLocation(), diag::note_using_decl_target); 9598 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9599 Using->setInvalidDecl(); 9600 return true; 9601 } 9602 9603 /// Determine whether a direct base class is a virtual base class. 9604 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9605 if (!Derived->getNumVBases()) 9606 return false; 9607 for (auto &B : Derived->bases()) 9608 if (B.getType()->getAsCXXRecordDecl() == Base) 9609 return B.isVirtual(); 9610 llvm_unreachable("not a direct base class"); 9611 } 9612 9613 /// Builds a shadow declaration corresponding to a 'using' declaration. 9614 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9615 UsingDecl *UD, 9616 NamedDecl *Orig, 9617 UsingShadowDecl *PrevDecl) { 9618 // If we resolved to another shadow declaration, just coalesce them. 9619 NamedDecl *Target = Orig; 9620 if (isa<UsingShadowDecl>(Target)) { 9621 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9622 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9623 } 9624 9625 NamedDecl *NonTemplateTarget = Target; 9626 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9627 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9628 9629 UsingShadowDecl *Shadow; 9630 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9631 bool IsVirtualBase = 9632 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9633 UD->getQualifier()->getAsRecordDecl()); 9634 Shadow = ConstructorUsingShadowDecl::Create( 9635 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9636 } else { 9637 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9638 Target); 9639 } 9640 UD->addShadowDecl(Shadow); 9641 9642 Shadow->setAccess(UD->getAccess()); 9643 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9644 Shadow->setInvalidDecl(); 9645 9646 Shadow->setPreviousDecl(PrevDecl); 9647 9648 if (S) 9649 PushOnScopeChains(Shadow, S); 9650 else 9651 CurContext->addDecl(Shadow); 9652 9653 9654 return Shadow; 9655 } 9656 9657 /// Hides a using shadow declaration. This is required by the current 9658 /// using-decl implementation when a resolvable using declaration in a 9659 /// class is followed by a declaration which would hide or override 9660 /// one or more of the using decl's targets; for example: 9661 /// 9662 /// struct Base { void foo(int); }; 9663 /// struct Derived : Base { 9664 /// using Base::foo; 9665 /// void foo(int); 9666 /// }; 9667 /// 9668 /// The governing language is C++03 [namespace.udecl]p12: 9669 /// 9670 /// When a using-declaration brings names from a base class into a 9671 /// derived class scope, member functions in the derived class 9672 /// override and/or hide member functions with the same name and 9673 /// parameter types in a base class (rather than conflicting). 9674 /// 9675 /// There are two ways to implement this: 9676 /// (1) optimistically create shadow decls when they're not hidden 9677 /// by existing declarations, or 9678 /// (2) don't create any shadow decls (or at least don't make them 9679 /// visible) until we've fully parsed/instantiated the class. 9680 /// The problem with (1) is that we might have to retroactively remove 9681 /// a shadow decl, which requires several O(n) operations because the 9682 /// decl structures are (very reasonably) not designed for removal. 9683 /// (2) avoids this but is very fiddly and phase-dependent. 9684 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9685 if (Shadow->getDeclName().getNameKind() == 9686 DeclarationName::CXXConversionFunctionName) 9687 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9688 9689 // Remove it from the DeclContext... 9690 Shadow->getDeclContext()->removeDecl(Shadow); 9691 9692 // ...and the scope, if applicable... 9693 if (S) { 9694 S->RemoveDecl(Shadow); 9695 IdResolver.RemoveDecl(Shadow); 9696 } 9697 9698 // ...and the using decl. 9699 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9700 9701 // TODO: complain somehow if Shadow was used. It shouldn't 9702 // be possible for this to happen, because...? 9703 } 9704 9705 /// Find the base specifier for a base class with the given type. 9706 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9707 QualType DesiredBase, 9708 bool &AnyDependentBases) { 9709 // Check whether the named type is a direct base class. 9710 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9711 for (auto &Base : Derived->bases()) { 9712 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9713 if (CanonicalDesiredBase == BaseType) 9714 return &Base; 9715 if (BaseType->isDependentType()) 9716 AnyDependentBases = true; 9717 } 9718 return nullptr; 9719 } 9720 9721 namespace { 9722 class UsingValidatorCCC : public CorrectionCandidateCallback { 9723 public: 9724 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9725 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9726 : HasTypenameKeyword(HasTypenameKeyword), 9727 IsInstantiation(IsInstantiation), OldNNS(NNS), 9728 RequireMemberOf(RequireMemberOf) {} 9729 9730 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9731 NamedDecl *ND = Candidate.getCorrectionDecl(); 9732 9733 // Keywords are not valid here. 9734 if (!ND || isa<NamespaceDecl>(ND)) 9735 return false; 9736 9737 // Completely unqualified names are invalid for a 'using' declaration. 9738 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9739 return false; 9740 9741 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9742 // reject. 9743 9744 if (RequireMemberOf) { 9745 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9746 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9747 // No-one ever wants a using-declaration to name an injected-class-name 9748 // of a base class, unless they're declaring an inheriting constructor. 9749 ASTContext &Ctx = ND->getASTContext(); 9750 if (!Ctx.getLangOpts().CPlusPlus11) 9751 return false; 9752 QualType FoundType = Ctx.getRecordType(FoundRecord); 9753 9754 // Check that the injected-class-name is named as a member of its own 9755 // type; we don't want to suggest 'using Derived::Base;', since that 9756 // means something else. 9757 NestedNameSpecifier *Specifier = 9758 Candidate.WillReplaceSpecifier() 9759 ? Candidate.getCorrectionSpecifier() 9760 : OldNNS; 9761 if (!Specifier->getAsType() || 9762 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9763 return false; 9764 9765 // Check that this inheriting constructor declaration actually names a 9766 // direct base class of the current class. 9767 bool AnyDependentBases = false; 9768 if (!findDirectBaseWithType(RequireMemberOf, 9769 Ctx.getRecordType(FoundRecord), 9770 AnyDependentBases) && 9771 !AnyDependentBases) 9772 return false; 9773 } else { 9774 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9775 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9776 return false; 9777 9778 // FIXME: Check that the base class member is accessible? 9779 } 9780 } else { 9781 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9782 if (FoundRecord && FoundRecord->isInjectedClassName()) 9783 return false; 9784 } 9785 9786 if (isa<TypeDecl>(ND)) 9787 return HasTypenameKeyword || !IsInstantiation; 9788 9789 return !HasTypenameKeyword; 9790 } 9791 9792 private: 9793 bool HasTypenameKeyword; 9794 bool IsInstantiation; 9795 NestedNameSpecifier *OldNNS; 9796 CXXRecordDecl *RequireMemberOf; 9797 }; 9798 } // end anonymous namespace 9799 9800 /// Builds a using declaration. 9801 /// 9802 /// \param IsInstantiation - Whether this call arises from an 9803 /// instantiation of an unresolved using declaration. We treat 9804 /// the lookup differently for these declarations. 9805 NamedDecl *Sema::BuildUsingDeclaration( 9806 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 9807 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 9808 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 9809 const ParsedAttributesView &AttrList, bool IsInstantiation) { 9810 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9811 SourceLocation IdentLoc = NameInfo.getLoc(); 9812 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9813 9814 // FIXME: We ignore attributes for now. 9815 9816 // For an inheriting constructor declaration, the name of the using 9817 // declaration is the name of a constructor in this class, not in the 9818 // base class. 9819 DeclarationNameInfo UsingName = NameInfo; 9820 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9821 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9822 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9823 Context.getCanonicalType(Context.getRecordType(RD)))); 9824 9825 // Do the redeclaration lookup in the current scope. 9826 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9827 ForVisibleRedeclaration); 9828 Previous.setHideTags(false); 9829 if (S) { 9830 LookupName(Previous, S); 9831 9832 // It is really dumb that we have to do this. 9833 LookupResult::Filter F = Previous.makeFilter(); 9834 while (F.hasNext()) { 9835 NamedDecl *D = F.next(); 9836 if (!isDeclInScope(D, CurContext, S)) 9837 F.erase(); 9838 // If we found a local extern declaration that's not ordinarily visible, 9839 // and this declaration is being added to a non-block scope, ignore it. 9840 // We're only checking for scope conflicts here, not also for violations 9841 // of the linkage rules. 9842 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9843 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9844 F.erase(); 9845 } 9846 F.done(); 9847 } else { 9848 assert(IsInstantiation && "no scope in non-instantiation"); 9849 if (CurContext->isRecord()) 9850 LookupQualifiedName(Previous, CurContext); 9851 else { 9852 // No redeclaration check is needed here; in non-member contexts we 9853 // diagnosed all possible conflicts with other using-declarations when 9854 // building the template: 9855 // 9856 // For a dependent non-type using declaration, the only valid case is 9857 // if we instantiate to a single enumerator. We check for conflicts 9858 // between shadow declarations we introduce, and we check in the template 9859 // definition for conflicts between a non-type using declaration and any 9860 // other declaration, which together covers all cases. 9861 // 9862 // A dependent typename using declaration will never successfully 9863 // instantiate, since it will always name a class member, so we reject 9864 // that in the template definition. 9865 } 9866 } 9867 9868 // Check for invalid redeclarations. 9869 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9870 SS, IdentLoc, Previous)) 9871 return nullptr; 9872 9873 // Check for bad qualifiers. 9874 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9875 IdentLoc)) 9876 return nullptr; 9877 9878 DeclContext *LookupContext = computeDeclContext(SS); 9879 NamedDecl *D; 9880 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9881 if (!LookupContext || EllipsisLoc.isValid()) { 9882 if (HasTypenameKeyword) { 9883 // FIXME: not all declaration name kinds are legal here 9884 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9885 UsingLoc, TypenameLoc, 9886 QualifierLoc, 9887 IdentLoc, NameInfo.getName(), 9888 EllipsisLoc); 9889 } else { 9890 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9891 QualifierLoc, NameInfo, EllipsisLoc); 9892 } 9893 D->setAccess(AS); 9894 CurContext->addDecl(D); 9895 return D; 9896 } 9897 9898 auto Build = [&](bool Invalid) { 9899 UsingDecl *UD = 9900 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9901 UsingName, HasTypenameKeyword); 9902 UD->setAccess(AS); 9903 CurContext->addDecl(UD); 9904 UD->setInvalidDecl(Invalid); 9905 return UD; 9906 }; 9907 auto BuildInvalid = [&]{ return Build(true); }; 9908 auto BuildValid = [&]{ return Build(false); }; 9909 9910 if (RequireCompleteDeclContext(SS, LookupContext)) 9911 return BuildInvalid(); 9912 9913 // Look up the target name. 9914 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9915 9916 // Unlike most lookups, we don't always want to hide tag 9917 // declarations: tag names are visible through the using declaration 9918 // even if hidden by ordinary names, *except* in a dependent context 9919 // where it's important for the sanity of two-phase lookup. 9920 if (!IsInstantiation) 9921 R.setHideTags(false); 9922 9923 // For the purposes of this lookup, we have a base object type 9924 // equal to that of the current context. 9925 if (CurContext->isRecord()) { 9926 R.setBaseObjectType( 9927 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9928 } 9929 9930 LookupQualifiedName(R, LookupContext); 9931 9932 // Try to correct typos if possible. If constructor name lookup finds no 9933 // results, that means the named class has no explicit constructors, and we 9934 // suppressed declaring implicit ones (probably because it's dependent or 9935 // invalid). 9936 if (R.empty() && 9937 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9938 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9939 // it will believe that glibc provides a ::gets in cases where it does not, 9940 // and will try to pull it into namespace std with a using-declaration. 9941 // Just ignore the using-declaration in that case. 9942 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9943 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9944 CurContext->isStdNamespace() && 9945 isa<TranslationUnitDecl>(LookupContext) && 9946 getSourceManager().isInSystemHeader(UsingLoc)) 9947 return nullptr; 9948 if (TypoCorrection Corrected = CorrectTypo( 9949 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9950 llvm::make_unique<UsingValidatorCCC>( 9951 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9952 dyn_cast<CXXRecordDecl>(CurContext)), 9953 CTK_ErrorRecovery)) { 9954 // We reject candidates where DroppedSpecifier == true, hence the 9955 // literal '0' below. 9956 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9957 << NameInfo.getName() << LookupContext << 0 9958 << SS.getRange()); 9959 9960 // If we picked a correction with no attached Decl we can't do anything 9961 // useful with it, bail out. 9962 NamedDecl *ND = Corrected.getCorrectionDecl(); 9963 if (!ND) 9964 return BuildInvalid(); 9965 9966 // If we corrected to an inheriting constructor, handle it as one. 9967 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9968 if (RD && RD->isInjectedClassName()) { 9969 // The parent of the injected class name is the class itself. 9970 RD = cast<CXXRecordDecl>(RD->getParent()); 9971 9972 // Fix up the information we'll use to build the using declaration. 9973 if (Corrected.WillReplaceSpecifier()) { 9974 NestedNameSpecifierLocBuilder Builder; 9975 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9976 QualifierLoc.getSourceRange()); 9977 QualifierLoc = Builder.getWithLocInContext(Context); 9978 } 9979 9980 // In this case, the name we introduce is the name of a derived class 9981 // constructor. 9982 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9983 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9984 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9985 UsingName.setNamedTypeInfo(nullptr); 9986 for (auto *Ctor : LookupConstructors(RD)) 9987 R.addDecl(Ctor); 9988 R.resolveKind(); 9989 } else { 9990 // FIXME: Pick up all the declarations if we found an overloaded 9991 // function. 9992 UsingName.setName(ND->getDeclName()); 9993 R.addDecl(ND); 9994 } 9995 } else { 9996 Diag(IdentLoc, diag::err_no_member) 9997 << NameInfo.getName() << LookupContext << SS.getRange(); 9998 return BuildInvalid(); 9999 } 10000 } 10001 10002 if (R.isAmbiguous()) 10003 return BuildInvalid(); 10004 10005 if (HasTypenameKeyword) { 10006 // If we asked for a typename and got a non-type decl, error out. 10007 if (!R.getAsSingle<TypeDecl>()) { 10008 Diag(IdentLoc, diag::err_using_typename_non_type); 10009 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10010 Diag((*I)->getUnderlyingDecl()->getLocation(), 10011 diag::note_using_decl_target); 10012 return BuildInvalid(); 10013 } 10014 } else { 10015 // If we asked for a non-typename and we got a type, error out, 10016 // but only if this is an instantiation of an unresolved using 10017 // decl. Otherwise just silently find the type name. 10018 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10019 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10020 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10021 return BuildInvalid(); 10022 } 10023 } 10024 10025 // C++14 [namespace.udecl]p6: 10026 // A using-declaration shall not name a namespace. 10027 if (R.getAsSingle<NamespaceDecl>()) { 10028 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10029 << SS.getRange(); 10030 return BuildInvalid(); 10031 } 10032 10033 // C++14 [namespace.udecl]p7: 10034 // A using-declaration shall not name a scoped enumerator. 10035 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10036 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10037 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10038 << SS.getRange(); 10039 return BuildInvalid(); 10040 } 10041 } 10042 10043 UsingDecl *UD = BuildValid(); 10044 10045 // Some additional rules apply to inheriting constructors. 10046 if (UsingName.getName().getNameKind() == 10047 DeclarationName::CXXConstructorName) { 10048 // Suppress access diagnostics; the access check is instead performed at the 10049 // point of use for an inheriting constructor. 10050 R.suppressDiagnostics(); 10051 if (CheckInheritingConstructorUsingDecl(UD)) 10052 return UD; 10053 } 10054 10055 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10056 UsingShadowDecl *PrevDecl = nullptr; 10057 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10058 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10059 } 10060 10061 return UD; 10062 } 10063 10064 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10065 ArrayRef<NamedDecl *> Expansions) { 10066 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10067 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10068 isa<UsingPackDecl>(InstantiatedFrom)); 10069 10070 auto *UPD = 10071 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10072 UPD->setAccess(InstantiatedFrom->getAccess()); 10073 CurContext->addDecl(UPD); 10074 return UPD; 10075 } 10076 10077 /// Additional checks for a using declaration referring to a constructor name. 10078 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10079 assert(!UD->hasTypename() && "expecting a constructor name"); 10080 10081 const Type *SourceType = UD->getQualifier()->getAsType(); 10082 assert(SourceType && 10083 "Using decl naming constructor doesn't have type in scope spec."); 10084 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10085 10086 // Check whether the named type is a direct base class. 10087 bool AnyDependentBases = false; 10088 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10089 AnyDependentBases); 10090 if (!Base && !AnyDependentBases) { 10091 Diag(UD->getUsingLoc(), 10092 diag::err_using_decl_constructor_not_in_direct_base) 10093 << UD->getNameInfo().getSourceRange() 10094 << QualType(SourceType, 0) << TargetClass; 10095 UD->setInvalidDecl(); 10096 return true; 10097 } 10098 10099 if (Base) 10100 Base->setInheritConstructors(); 10101 10102 return false; 10103 } 10104 10105 /// Checks that the given using declaration is not an invalid 10106 /// redeclaration. Note that this is checking only for the using decl 10107 /// itself, not for any ill-formedness among the UsingShadowDecls. 10108 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10109 bool HasTypenameKeyword, 10110 const CXXScopeSpec &SS, 10111 SourceLocation NameLoc, 10112 const LookupResult &Prev) { 10113 NestedNameSpecifier *Qual = SS.getScopeRep(); 10114 10115 // C++03 [namespace.udecl]p8: 10116 // C++0x [namespace.udecl]p10: 10117 // A using-declaration is a declaration and can therefore be used 10118 // repeatedly where (and only where) multiple declarations are 10119 // allowed. 10120 // 10121 // That's in non-member contexts. 10122 if (!CurContext->getRedeclContext()->isRecord()) { 10123 // A dependent qualifier outside a class can only ever resolve to an 10124 // enumeration type. Therefore it conflicts with any other non-type 10125 // declaration in the same scope. 10126 // FIXME: How should we check for dependent type-type conflicts at block 10127 // scope? 10128 if (Qual->isDependent() && !HasTypenameKeyword) { 10129 for (auto *D : Prev) { 10130 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10131 bool OldCouldBeEnumerator = 10132 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10133 Diag(NameLoc, 10134 OldCouldBeEnumerator ? diag::err_redefinition 10135 : diag::err_redefinition_different_kind) 10136 << Prev.getLookupName(); 10137 Diag(D->getLocation(), diag::note_previous_definition); 10138 return true; 10139 } 10140 } 10141 } 10142 return false; 10143 } 10144 10145 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10146 NamedDecl *D = *I; 10147 10148 bool DTypename; 10149 NestedNameSpecifier *DQual; 10150 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10151 DTypename = UD->hasTypename(); 10152 DQual = UD->getQualifier(); 10153 } else if (UnresolvedUsingValueDecl *UD 10154 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10155 DTypename = false; 10156 DQual = UD->getQualifier(); 10157 } else if (UnresolvedUsingTypenameDecl *UD 10158 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10159 DTypename = true; 10160 DQual = UD->getQualifier(); 10161 } else continue; 10162 10163 // using decls differ if one says 'typename' and the other doesn't. 10164 // FIXME: non-dependent using decls? 10165 if (HasTypenameKeyword != DTypename) continue; 10166 10167 // using decls differ if they name different scopes (but note that 10168 // template instantiation can cause this check to trigger when it 10169 // didn't before instantiation). 10170 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10171 Context.getCanonicalNestedNameSpecifier(DQual)) 10172 continue; 10173 10174 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10175 Diag(D->getLocation(), diag::note_using_decl) << 1; 10176 return true; 10177 } 10178 10179 return false; 10180 } 10181 10182 10183 /// Checks that the given nested-name qualifier used in a using decl 10184 /// in the current context is appropriately related to the current 10185 /// scope. If an error is found, diagnoses it and returns true. 10186 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10187 bool HasTypename, 10188 const CXXScopeSpec &SS, 10189 const DeclarationNameInfo &NameInfo, 10190 SourceLocation NameLoc) { 10191 DeclContext *NamedContext = computeDeclContext(SS); 10192 10193 if (!CurContext->isRecord()) { 10194 // C++03 [namespace.udecl]p3: 10195 // C++0x [namespace.udecl]p8: 10196 // A using-declaration for a class member shall be a member-declaration. 10197 10198 // If we weren't able to compute a valid scope, it might validly be a 10199 // dependent class scope or a dependent enumeration unscoped scope. If 10200 // we have a 'typename' keyword, the scope must resolve to a class type. 10201 if ((HasTypename && !NamedContext) || 10202 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10203 auto *RD = NamedContext 10204 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10205 : nullptr; 10206 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10207 RD = nullptr; 10208 10209 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10210 << SS.getRange(); 10211 10212 // If we have a complete, non-dependent source type, try to suggest a 10213 // way to get the same effect. 10214 if (!RD) 10215 return true; 10216 10217 // Find what this using-declaration was referring to. 10218 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10219 R.setHideTags(false); 10220 R.suppressDiagnostics(); 10221 LookupQualifiedName(R, RD); 10222 10223 if (R.getAsSingle<TypeDecl>()) { 10224 if (getLangOpts().CPlusPlus11) { 10225 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10226 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10227 << 0 // alias declaration 10228 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10229 NameInfo.getName().getAsString() + 10230 " = "); 10231 } else { 10232 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10233 SourceLocation InsertLoc = 10234 getLocForEndOfToken(NameInfo.getLocEnd()); 10235 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10236 << 1 // typedef declaration 10237 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10238 << FixItHint::CreateInsertion( 10239 InsertLoc, " " + NameInfo.getName().getAsString()); 10240 } 10241 } else if (R.getAsSingle<VarDecl>()) { 10242 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10243 // repeating the type of the static data member here. 10244 FixItHint FixIt; 10245 if (getLangOpts().CPlusPlus11) { 10246 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10247 FixIt = FixItHint::CreateReplacement( 10248 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10249 } 10250 10251 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10252 << 2 // reference declaration 10253 << FixIt; 10254 } else if (R.getAsSingle<EnumConstantDecl>()) { 10255 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10256 // repeating the type of the enumeration here, and we can't do so if 10257 // the type is anonymous. 10258 FixItHint FixIt; 10259 if (getLangOpts().CPlusPlus11) { 10260 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10261 FixIt = FixItHint::CreateReplacement( 10262 UsingLoc, 10263 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10264 } 10265 10266 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10267 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10268 << FixIt; 10269 } 10270 return true; 10271 } 10272 10273 // Otherwise, this might be valid. 10274 return false; 10275 } 10276 10277 // The current scope is a record. 10278 10279 // If the named context is dependent, we can't decide much. 10280 if (!NamedContext) { 10281 // FIXME: in C++0x, we can diagnose if we can prove that the 10282 // nested-name-specifier does not refer to a base class, which is 10283 // still possible in some cases. 10284 10285 // Otherwise we have to conservatively report that things might be 10286 // okay. 10287 return false; 10288 } 10289 10290 if (!NamedContext->isRecord()) { 10291 // Ideally this would point at the last name in the specifier, 10292 // but we don't have that level of source info. 10293 Diag(SS.getRange().getBegin(), 10294 diag::err_using_decl_nested_name_specifier_is_not_class) 10295 << SS.getScopeRep() << SS.getRange(); 10296 return true; 10297 } 10298 10299 if (!NamedContext->isDependentContext() && 10300 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10301 return true; 10302 10303 if (getLangOpts().CPlusPlus11) { 10304 // C++11 [namespace.udecl]p3: 10305 // In a using-declaration used as a member-declaration, the 10306 // nested-name-specifier shall name a base class of the class 10307 // being defined. 10308 10309 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10310 cast<CXXRecordDecl>(NamedContext))) { 10311 if (CurContext == NamedContext) { 10312 Diag(NameLoc, 10313 diag::err_using_decl_nested_name_specifier_is_current_class) 10314 << SS.getRange(); 10315 return true; 10316 } 10317 10318 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10319 Diag(SS.getRange().getBegin(), 10320 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10321 << SS.getScopeRep() 10322 << cast<CXXRecordDecl>(CurContext) 10323 << SS.getRange(); 10324 } 10325 return true; 10326 } 10327 10328 return false; 10329 } 10330 10331 // C++03 [namespace.udecl]p4: 10332 // A using-declaration used as a member-declaration shall refer 10333 // to a member of a base class of the class being defined [etc.]. 10334 10335 // Salient point: SS doesn't have to name a base class as long as 10336 // lookup only finds members from base classes. Therefore we can 10337 // diagnose here only if we can prove that that can't happen, 10338 // i.e. if the class hierarchies provably don't intersect. 10339 10340 // TODO: it would be nice if "definitely valid" results were cached 10341 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10342 // need to be repeated. 10343 10344 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10345 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10346 Bases.insert(Base); 10347 return true; 10348 }; 10349 10350 // Collect all bases. Return false if we find a dependent base. 10351 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10352 return false; 10353 10354 // Returns true if the base is dependent or is one of the accumulated base 10355 // classes. 10356 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10357 return !Bases.count(Base); 10358 }; 10359 10360 // Return false if the class has a dependent base or if it or one 10361 // of its bases is present in the base set of the current context. 10362 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10363 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10364 return false; 10365 10366 Diag(SS.getRange().getBegin(), 10367 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10368 << SS.getScopeRep() 10369 << cast<CXXRecordDecl>(CurContext) 10370 << SS.getRange(); 10371 10372 return true; 10373 } 10374 10375 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10376 MultiTemplateParamsArg TemplateParamLists, 10377 SourceLocation UsingLoc, UnqualifiedId &Name, 10378 const ParsedAttributesView &AttrList, 10379 TypeResult Type, Decl *DeclFromDeclSpec) { 10380 // Skip up to the relevant declaration scope. 10381 while (S->isTemplateParamScope()) 10382 S = S->getParent(); 10383 assert((S->getFlags() & Scope::DeclScope) && 10384 "got alias-declaration outside of declaration scope"); 10385 10386 if (Type.isInvalid()) 10387 return nullptr; 10388 10389 bool Invalid = false; 10390 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10391 TypeSourceInfo *TInfo = nullptr; 10392 GetTypeFromParser(Type.get(), &TInfo); 10393 10394 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10395 return nullptr; 10396 10397 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10398 UPPC_DeclarationType)) { 10399 Invalid = true; 10400 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10401 TInfo->getTypeLoc().getBeginLoc()); 10402 } 10403 10404 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10405 TemplateParamLists.size() 10406 ? forRedeclarationInCurContext() 10407 : ForVisibleRedeclaration); 10408 LookupName(Previous, S); 10409 10410 // Warn about shadowing the name of a template parameter. 10411 if (Previous.isSingleResult() && 10412 Previous.getFoundDecl()->isTemplateParameter()) { 10413 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10414 Previous.clear(); 10415 } 10416 10417 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10418 "name in alias declaration must be an identifier"); 10419 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10420 Name.StartLocation, 10421 Name.Identifier, TInfo); 10422 10423 NewTD->setAccess(AS); 10424 10425 if (Invalid) 10426 NewTD->setInvalidDecl(); 10427 10428 ProcessDeclAttributeList(S, NewTD, AttrList); 10429 AddPragmaAttributes(S, NewTD); 10430 10431 CheckTypedefForVariablyModifiedType(S, NewTD); 10432 Invalid |= NewTD->isInvalidDecl(); 10433 10434 bool Redeclaration = false; 10435 10436 NamedDecl *NewND; 10437 if (TemplateParamLists.size()) { 10438 TypeAliasTemplateDecl *OldDecl = nullptr; 10439 TemplateParameterList *OldTemplateParams = nullptr; 10440 10441 if (TemplateParamLists.size() != 1) { 10442 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10443 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10444 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10445 } 10446 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10447 10448 // Check that we can declare a template here. 10449 if (CheckTemplateDeclScope(S, TemplateParams)) 10450 return nullptr; 10451 10452 // Only consider previous declarations in the same scope. 10453 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10454 /*ExplicitInstantiationOrSpecialization*/false); 10455 if (!Previous.empty()) { 10456 Redeclaration = true; 10457 10458 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10459 if (!OldDecl && !Invalid) { 10460 Diag(UsingLoc, diag::err_redefinition_different_kind) 10461 << Name.Identifier; 10462 10463 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10464 if (OldD->getLocation().isValid()) 10465 Diag(OldD->getLocation(), diag::note_previous_definition); 10466 10467 Invalid = true; 10468 } 10469 10470 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10471 if (TemplateParameterListsAreEqual(TemplateParams, 10472 OldDecl->getTemplateParameters(), 10473 /*Complain=*/true, 10474 TPL_TemplateMatch)) 10475 OldTemplateParams = OldDecl->getTemplateParameters(); 10476 else 10477 Invalid = true; 10478 10479 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10480 if (!Invalid && 10481 !Context.hasSameType(OldTD->getUnderlyingType(), 10482 NewTD->getUnderlyingType())) { 10483 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10484 // but we can't reasonably accept it. 10485 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10486 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10487 if (OldTD->getLocation().isValid()) 10488 Diag(OldTD->getLocation(), diag::note_previous_definition); 10489 Invalid = true; 10490 } 10491 } 10492 } 10493 10494 // Merge any previous default template arguments into our parameters, 10495 // and check the parameter list. 10496 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10497 TPC_TypeAliasTemplate)) 10498 return nullptr; 10499 10500 TypeAliasTemplateDecl *NewDecl = 10501 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10502 Name.Identifier, TemplateParams, 10503 NewTD); 10504 NewTD->setDescribedAliasTemplate(NewDecl); 10505 10506 NewDecl->setAccess(AS); 10507 10508 if (Invalid) 10509 NewDecl->setInvalidDecl(); 10510 else if (OldDecl) { 10511 NewDecl->setPreviousDecl(OldDecl); 10512 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10513 } 10514 10515 NewND = NewDecl; 10516 } else { 10517 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10518 setTagNameForLinkagePurposes(TD, NewTD); 10519 handleTagNumbering(TD, S); 10520 } 10521 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10522 NewND = NewTD; 10523 } 10524 10525 PushOnScopeChains(NewND, S); 10526 ActOnDocumentableDecl(NewND); 10527 return NewND; 10528 } 10529 10530 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10531 SourceLocation AliasLoc, 10532 IdentifierInfo *Alias, CXXScopeSpec &SS, 10533 SourceLocation IdentLoc, 10534 IdentifierInfo *Ident) { 10535 10536 // Lookup the namespace name. 10537 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10538 LookupParsedName(R, S, &SS); 10539 10540 if (R.isAmbiguous()) 10541 return nullptr; 10542 10543 if (R.empty()) { 10544 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10545 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10546 return nullptr; 10547 } 10548 } 10549 assert(!R.isAmbiguous() && !R.empty()); 10550 NamedDecl *ND = R.getRepresentativeDecl(); 10551 10552 // Check if we have a previous declaration with the same name. 10553 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10554 ForVisibleRedeclaration); 10555 LookupName(PrevR, S); 10556 10557 // Check we're not shadowing a template parameter. 10558 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10559 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10560 PrevR.clear(); 10561 } 10562 10563 // Filter out any other lookup result from an enclosing scope. 10564 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10565 /*AllowInlineNamespace*/false); 10566 10567 // Find the previous declaration and check that we can redeclare it. 10568 NamespaceAliasDecl *Prev = nullptr; 10569 if (PrevR.isSingleResult()) { 10570 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10571 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10572 // We already have an alias with the same name that points to the same 10573 // namespace; check that it matches. 10574 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10575 Prev = AD; 10576 } else if (isVisible(PrevDecl)) { 10577 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10578 << Alias; 10579 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10580 << AD->getNamespace(); 10581 return nullptr; 10582 } 10583 } else if (isVisible(PrevDecl)) { 10584 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10585 ? diag::err_redefinition 10586 : diag::err_redefinition_different_kind; 10587 Diag(AliasLoc, DiagID) << Alias; 10588 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10589 return nullptr; 10590 } 10591 } 10592 10593 // The use of a nested name specifier may trigger deprecation warnings. 10594 DiagnoseUseOfDecl(ND, IdentLoc); 10595 10596 NamespaceAliasDecl *AliasDecl = 10597 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10598 Alias, SS.getWithLocInContext(Context), 10599 IdentLoc, ND); 10600 if (Prev) 10601 AliasDecl->setPreviousDecl(Prev); 10602 10603 PushOnScopeChains(AliasDecl, S); 10604 return AliasDecl; 10605 } 10606 10607 namespace { 10608 struct SpecialMemberExceptionSpecInfo 10609 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10610 SourceLocation Loc; 10611 Sema::ImplicitExceptionSpecification ExceptSpec; 10612 10613 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10614 Sema::CXXSpecialMember CSM, 10615 Sema::InheritedConstructorInfo *ICI, 10616 SourceLocation Loc) 10617 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10618 10619 bool visitBase(CXXBaseSpecifier *Base); 10620 bool visitField(FieldDecl *FD); 10621 10622 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10623 unsigned Quals); 10624 10625 void visitSubobjectCall(Subobject Subobj, 10626 Sema::SpecialMemberOverloadResult SMOR); 10627 }; 10628 } 10629 10630 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10631 auto *RT = Base->getType()->getAs<RecordType>(); 10632 if (!RT) 10633 return false; 10634 10635 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10636 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10637 if (auto *BaseCtor = SMOR.getMethod()) { 10638 visitSubobjectCall(Base, BaseCtor); 10639 return false; 10640 } 10641 10642 visitClassSubobject(BaseClass, Base, 0); 10643 return false; 10644 } 10645 10646 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10647 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10648 Expr *E = FD->getInClassInitializer(); 10649 if (!E) 10650 // FIXME: It's a little wasteful to build and throw away a 10651 // CXXDefaultInitExpr here. 10652 // FIXME: We should have a single context note pointing at Loc, and 10653 // this location should be MD->getLocation() instead, since that's 10654 // the location where we actually use the default init expression. 10655 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10656 if (E) 10657 ExceptSpec.CalledExpr(E); 10658 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10659 ->getAs<RecordType>()) { 10660 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10661 FD->getType().getCVRQualifiers()); 10662 } 10663 return false; 10664 } 10665 10666 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10667 Subobject Subobj, 10668 unsigned Quals) { 10669 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10670 bool IsMutable = Field && Field->isMutable(); 10671 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10672 } 10673 10674 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10675 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10676 // Note, if lookup fails, it doesn't matter what exception specification we 10677 // choose because the special member will be deleted. 10678 if (CXXMethodDecl *MD = SMOR.getMethod()) 10679 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10680 } 10681 10682 static Sema::ImplicitExceptionSpecification 10683 ComputeDefaultedSpecialMemberExceptionSpec( 10684 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10685 Sema::InheritedConstructorInfo *ICI) { 10686 CXXRecordDecl *ClassDecl = MD->getParent(); 10687 10688 // C++ [except.spec]p14: 10689 // An implicitly declared special member function (Clause 12) shall have an 10690 // exception-specification. [...] 10691 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10692 if (ClassDecl->isInvalidDecl()) 10693 return Info.ExceptSpec; 10694 10695 // C++1z [except.spec]p7: 10696 // [Look for exceptions thrown by] a constructor selected [...] to 10697 // initialize a potentially constructed subobject, 10698 // C++1z [except.spec]p8: 10699 // The exception specification for an implicitly-declared destructor, or a 10700 // destructor without a noexcept-specifier, is potentially-throwing if and 10701 // only if any of the destructors for any of its potentially constructed 10702 // subojects is potentially throwing. 10703 // FIXME: We respect the first rule but ignore the "potentially constructed" 10704 // in the second rule to resolve a core issue (no number yet) that would have 10705 // us reject: 10706 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10707 // struct B : A {}; 10708 // struct C : B { void f(); }; 10709 // ... due to giving B::~B() a non-throwing exception specification. 10710 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10711 : Info.VisitAllBases); 10712 10713 return Info.ExceptSpec; 10714 } 10715 10716 namespace { 10717 /// RAII object to register a special member as being currently declared. 10718 struct DeclaringSpecialMember { 10719 Sema &S; 10720 Sema::SpecialMemberDecl D; 10721 Sema::ContextRAII SavedContext; 10722 bool WasAlreadyBeingDeclared; 10723 10724 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10725 : S(S), D(RD, CSM), SavedContext(S, RD) { 10726 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10727 if (WasAlreadyBeingDeclared) 10728 // This almost never happens, but if it does, ensure that our cache 10729 // doesn't contain a stale result. 10730 S.SpecialMemberCache.clear(); 10731 else { 10732 // Register a note to be produced if we encounter an error while 10733 // declaring the special member. 10734 Sema::CodeSynthesisContext Ctx; 10735 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10736 // FIXME: We don't have a location to use here. Using the class's 10737 // location maintains the fiction that we declare all special members 10738 // with the class, but (1) it's not clear that lying about that helps our 10739 // users understand what's going on, and (2) there may be outer contexts 10740 // on the stack (some of which are relevant) and printing them exposes 10741 // our lies. 10742 Ctx.PointOfInstantiation = RD->getLocation(); 10743 Ctx.Entity = RD; 10744 Ctx.SpecialMember = CSM; 10745 S.pushCodeSynthesisContext(Ctx); 10746 } 10747 } 10748 ~DeclaringSpecialMember() { 10749 if (!WasAlreadyBeingDeclared) { 10750 S.SpecialMembersBeingDeclared.erase(D); 10751 S.popCodeSynthesisContext(); 10752 } 10753 } 10754 10755 /// Are we already trying to declare this special member? 10756 bool isAlreadyBeingDeclared() const { 10757 return WasAlreadyBeingDeclared; 10758 } 10759 }; 10760 } 10761 10762 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10763 // Look up any existing declarations, but don't trigger declaration of all 10764 // implicit special members with this name. 10765 DeclarationName Name = FD->getDeclName(); 10766 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10767 ForExternalRedeclaration); 10768 for (auto *D : FD->getParent()->lookup(Name)) 10769 if (auto *Acceptable = R.getAcceptableDecl(D)) 10770 R.addDecl(Acceptable); 10771 R.resolveKind(); 10772 R.suppressDiagnostics(); 10773 10774 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10775 } 10776 10777 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10778 CXXRecordDecl *ClassDecl) { 10779 // C++ [class.ctor]p5: 10780 // A default constructor for a class X is a constructor of class X 10781 // that can be called without an argument. If there is no 10782 // user-declared constructor for class X, a default constructor is 10783 // implicitly declared. An implicitly-declared default constructor 10784 // is an inline public member of its class. 10785 assert(ClassDecl->needsImplicitDefaultConstructor() && 10786 "Should not build implicit default constructor!"); 10787 10788 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10789 if (DSM.isAlreadyBeingDeclared()) 10790 return nullptr; 10791 10792 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10793 CXXDefaultConstructor, 10794 false); 10795 10796 // Create the actual constructor declaration. 10797 CanQualType ClassType 10798 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10799 SourceLocation ClassLoc = ClassDecl->getLocation(); 10800 DeclarationName Name 10801 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10802 DeclarationNameInfo NameInfo(Name, ClassLoc); 10803 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10804 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10805 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10806 /*isImplicitlyDeclared=*/true, Constexpr); 10807 DefaultCon->setAccess(AS_public); 10808 DefaultCon->setDefaulted(); 10809 10810 if (getLangOpts().CUDA) { 10811 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10812 DefaultCon, 10813 /* ConstRHS */ false, 10814 /* Diagnose */ false); 10815 } 10816 10817 // Build an exception specification pointing back at this constructor. 10818 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10819 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10820 10821 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10822 // constructors is easy to compute. 10823 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10824 10825 // Note that we have declared this constructor. 10826 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10827 10828 Scope *S = getScopeForContext(ClassDecl); 10829 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10830 10831 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10832 SetDeclDeleted(DefaultCon, ClassLoc); 10833 10834 if (S) 10835 PushOnScopeChains(DefaultCon, S, false); 10836 ClassDecl->addDecl(DefaultCon); 10837 10838 return DefaultCon; 10839 } 10840 10841 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10842 CXXConstructorDecl *Constructor) { 10843 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10844 !Constructor->doesThisDeclarationHaveABody() && 10845 !Constructor->isDeleted()) && 10846 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10847 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10848 return; 10849 10850 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10851 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10852 10853 SynthesizedFunctionScope Scope(*this, Constructor); 10854 10855 // The exception specification is needed because we are defining the 10856 // function. 10857 ResolveExceptionSpec(CurrentLocation, 10858 Constructor->getType()->castAs<FunctionProtoType>()); 10859 MarkVTableUsed(CurrentLocation, ClassDecl); 10860 10861 // Add a context note for diagnostics produced after this point. 10862 Scope.addContextNote(CurrentLocation); 10863 10864 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10865 Constructor->setInvalidDecl(); 10866 return; 10867 } 10868 10869 SourceLocation Loc = Constructor->getLocEnd().isValid() 10870 ? Constructor->getLocEnd() 10871 : Constructor->getLocation(); 10872 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10873 Constructor->markUsed(Context); 10874 10875 if (ASTMutationListener *L = getASTMutationListener()) { 10876 L->CompletedImplicitDefinition(Constructor); 10877 } 10878 10879 DiagnoseUninitializedFields(*this, Constructor); 10880 } 10881 10882 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10883 // Perform any delayed checks on exception specifications. 10884 CheckDelayedMemberExceptionSpecs(); 10885 } 10886 10887 /// Find or create the fake constructor we synthesize to model constructing an 10888 /// object of a derived class via a constructor of a base class. 10889 CXXConstructorDecl * 10890 Sema::findInheritingConstructor(SourceLocation Loc, 10891 CXXConstructorDecl *BaseCtor, 10892 ConstructorUsingShadowDecl *Shadow) { 10893 CXXRecordDecl *Derived = Shadow->getParent(); 10894 SourceLocation UsingLoc = Shadow->getLocation(); 10895 10896 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10897 // For now we use the name of the base class constructor as a member of the 10898 // derived class to indicate a (fake) inherited constructor name. 10899 DeclarationName Name = BaseCtor->getDeclName(); 10900 10901 // Check to see if we already have a fake constructor for this inherited 10902 // constructor call. 10903 for (NamedDecl *Ctor : Derived->lookup(Name)) 10904 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10905 ->getInheritedConstructor() 10906 .getConstructor(), 10907 BaseCtor)) 10908 return cast<CXXConstructorDecl>(Ctor); 10909 10910 DeclarationNameInfo NameInfo(Name, UsingLoc); 10911 TypeSourceInfo *TInfo = 10912 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10913 FunctionProtoTypeLoc ProtoLoc = 10914 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10915 10916 // Check the inherited constructor is valid and find the list of base classes 10917 // from which it was inherited. 10918 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10919 10920 bool Constexpr = 10921 BaseCtor->isConstexpr() && 10922 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10923 false, BaseCtor, &ICI); 10924 10925 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10926 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10927 BaseCtor->isExplicit(), /*Inline=*/true, 10928 /*ImplicitlyDeclared=*/true, Constexpr, 10929 InheritedConstructor(Shadow, BaseCtor)); 10930 if (Shadow->isInvalidDecl()) 10931 DerivedCtor->setInvalidDecl(); 10932 10933 // Build an unevaluated exception specification for this fake constructor. 10934 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10935 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10936 EPI.ExceptionSpec.Type = EST_Unevaluated; 10937 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10938 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10939 FPT->getParamTypes(), EPI)); 10940 10941 // Build the parameter declarations. 10942 SmallVector<ParmVarDecl *, 16> ParamDecls; 10943 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10944 TypeSourceInfo *TInfo = 10945 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10946 ParmVarDecl *PD = ParmVarDecl::Create( 10947 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10948 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10949 PD->setScopeInfo(0, I); 10950 PD->setImplicit(); 10951 // Ensure attributes are propagated onto parameters (this matters for 10952 // format, pass_object_size, ...). 10953 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10954 ParamDecls.push_back(PD); 10955 ProtoLoc.setParam(I, PD); 10956 } 10957 10958 // Set up the new constructor. 10959 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10960 DerivedCtor->setAccess(BaseCtor->getAccess()); 10961 DerivedCtor->setParams(ParamDecls); 10962 Derived->addDecl(DerivedCtor); 10963 10964 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10965 SetDeclDeleted(DerivedCtor, UsingLoc); 10966 10967 return DerivedCtor; 10968 } 10969 10970 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10971 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10972 Ctor->getInheritedConstructor().getShadowDecl()); 10973 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10974 /*Diagnose*/true); 10975 } 10976 10977 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10978 CXXConstructorDecl *Constructor) { 10979 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10980 assert(Constructor->getInheritedConstructor() && 10981 !Constructor->doesThisDeclarationHaveABody() && 10982 !Constructor->isDeleted()); 10983 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10984 return; 10985 10986 // Initializations are performed "as if by a defaulted default constructor", 10987 // so enter the appropriate scope. 10988 SynthesizedFunctionScope Scope(*this, Constructor); 10989 10990 // The exception specification is needed because we are defining the 10991 // function. 10992 ResolveExceptionSpec(CurrentLocation, 10993 Constructor->getType()->castAs<FunctionProtoType>()); 10994 MarkVTableUsed(CurrentLocation, ClassDecl); 10995 10996 // Add a context note for diagnostics produced after this point. 10997 Scope.addContextNote(CurrentLocation); 10998 10999 ConstructorUsingShadowDecl *Shadow = 11000 Constructor->getInheritedConstructor().getShadowDecl(); 11001 CXXConstructorDecl *InheritedCtor = 11002 Constructor->getInheritedConstructor().getConstructor(); 11003 11004 // [class.inhctor.init]p1: 11005 // initialization proceeds as if a defaulted default constructor is used to 11006 // initialize the D object and each base class subobject from which the 11007 // constructor was inherited 11008 11009 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11010 CXXRecordDecl *RD = Shadow->getParent(); 11011 SourceLocation InitLoc = Shadow->getLocation(); 11012 11013 // Build explicit initializers for all base classes from which the 11014 // constructor was inherited. 11015 SmallVector<CXXCtorInitializer*, 8> Inits; 11016 for (bool VBase : {false, true}) { 11017 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11018 if (B.isVirtual() != VBase) 11019 continue; 11020 11021 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11022 if (!BaseRD) 11023 continue; 11024 11025 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11026 if (!BaseCtor.first) 11027 continue; 11028 11029 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11030 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11031 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11032 11033 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11034 Inits.push_back(new (Context) CXXCtorInitializer( 11035 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11036 SourceLocation())); 11037 } 11038 } 11039 11040 // We now proceed as if for a defaulted default constructor, with the relevant 11041 // initializers replaced. 11042 11043 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11044 Constructor->setInvalidDecl(); 11045 return; 11046 } 11047 11048 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11049 Constructor->markUsed(Context); 11050 11051 if (ASTMutationListener *L = getASTMutationListener()) { 11052 L->CompletedImplicitDefinition(Constructor); 11053 } 11054 11055 DiagnoseUninitializedFields(*this, Constructor); 11056 } 11057 11058 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11059 // C++ [class.dtor]p2: 11060 // If a class has no user-declared destructor, a destructor is 11061 // declared implicitly. An implicitly-declared destructor is an 11062 // inline public member of its class. 11063 assert(ClassDecl->needsImplicitDestructor()); 11064 11065 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11066 if (DSM.isAlreadyBeingDeclared()) 11067 return nullptr; 11068 11069 // Create the actual destructor declaration. 11070 CanQualType ClassType 11071 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11072 SourceLocation ClassLoc = ClassDecl->getLocation(); 11073 DeclarationName Name 11074 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11075 DeclarationNameInfo NameInfo(Name, ClassLoc); 11076 CXXDestructorDecl *Destructor 11077 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11078 QualType(), nullptr, /*isInline=*/true, 11079 /*isImplicitlyDeclared=*/true); 11080 Destructor->setAccess(AS_public); 11081 Destructor->setDefaulted(); 11082 11083 if (getLangOpts().CUDA) { 11084 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11085 Destructor, 11086 /* ConstRHS */ false, 11087 /* Diagnose */ false); 11088 } 11089 11090 // Build an exception specification pointing back at this destructor. 11091 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 11092 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11093 11094 // We don't need to use SpecialMemberIsTrivial here; triviality for 11095 // destructors is easy to compute. 11096 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11097 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11098 ClassDecl->hasTrivialDestructorForCall()); 11099 11100 // Note that we have declared this destructor. 11101 ++ASTContext::NumImplicitDestructorsDeclared; 11102 11103 Scope *S = getScopeForContext(ClassDecl); 11104 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11105 11106 // We can't check whether an implicit destructor is deleted before we complete 11107 // the definition of the class, because its validity depends on the alignment 11108 // of the class. We'll check this from ActOnFields once the class is complete. 11109 if (ClassDecl->isCompleteDefinition() && 11110 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11111 SetDeclDeleted(Destructor, ClassLoc); 11112 11113 // Introduce this destructor into its scope. 11114 if (S) 11115 PushOnScopeChains(Destructor, S, false); 11116 ClassDecl->addDecl(Destructor); 11117 11118 return Destructor; 11119 } 11120 11121 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11122 CXXDestructorDecl *Destructor) { 11123 assert((Destructor->isDefaulted() && 11124 !Destructor->doesThisDeclarationHaveABody() && 11125 !Destructor->isDeleted()) && 11126 "DefineImplicitDestructor - call it for implicit default dtor"); 11127 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11128 return; 11129 11130 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11131 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11132 11133 SynthesizedFunctionScope Scope(*this, Destructor); 11134 11135 // The exception specification is needed because we are defining the 11136 // function. 11137 ResolveExceptionSpec(CurrentLocation, 11138 Destructor->getType()->castAs<FunctionProtoType>()); 11139 MarkVTableUsed(CurrentLocation, ClassDecl); 11140 11141 // Add a context note for diagnostics produced after this point. 11142 Scope.addContextNote(CurrentLocation); 11143 11144 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11145 Destructor->getParent()); 11146 11147 if (CheckDestructor(Destructor)) { 11148 Destructor->setInvalidDecl(); 11149 return; 11150 } 11151 11152 SourceLocation Loc = Destructor->getLocEnd().isValid() 11153 ? Destructor->getLocEnd() 11154 : Destructor->getLocation(); 11155 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11156 Destructor->markUsed(Context); 11157 11158 if (ASTMutationListener *L = getASTMutationListener()) { 11159 L->CompletedImplicitDefinition(Destructor); 11160 } 11161 } 11162 11163 /// Perform any semantic analysis which needs to be delayed until all 11164 /// pending class member declarations have been parsed. 11165 void Sema::ActOnFinishCXXMemberDecls() { 11166 // If the context is an invalid C++ class, just suppress these checks. 11167 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11168 if (Record->isInvalidDecl()) { 11169 DelayedDefaultedMemberExceptionSpecs.clear(); 11170 DelayedExceptionSpecChecks.clear(); 11171 return; 11172 } 11173 checkForMultipleExportedDefaultConstructors(*this, Record); 11174 } 11175 } 11176 11177 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11178 referenceDLLExportedClassMethods(); 11179 } 11180 11181 void Sema::referenceDLLExportedClassMethods() { 11182 if (!DelayedDllExportClasses.empty()) { 11183 // Calling ReferenceDllExportedMembers might cause the current function to 11184 // be called again, so use a local copy of DelayedDllExportClasses. 11185 SmallVector<CXXRecordDecl *, 4> WorkList; 11186 std::swap(DelayedDllExportClasses, WorkList); 11187 for (CXXRecordDecl *Class : WorkList) 11188 ReferenceDllExportedMembers(*this, Class); 11189 } 11190 } 11191 11192 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 11193 CXXDestructorDecl *Destructor) { 11194 assert(getLangOpts().CPlusPlus11 && 11195 "adjusting dtor exception specs was introduced in c++11"); 11196 11197 // C++11 [class.dtor]p3: 11198 // A declaration of a destructor that does not have an exception- 11199 // specification is implicitly considered to have the same exception- 11200 // specification as an implicit declaration. 11201 const FunctionProtoType *DtorType = Destructor->getType()-> 11202 getAs<FunctionProtoType>(); 11203 if (DtorType->hasExceptionSpec()) 11204 return; 11205 11206 // Replace the destructor's type, building off the existing one. Fortunately, 11207 // the only thing of interest in the destructor type is its extended info. 11208 // The return and arguments are fixed. 11209 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11210 EPI.ExceptionSpec.Type = EST_Unevaluated; 11211 EPI.ExceptionSpec.SourceDecl = Destructor; 11212 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11213 11214 // FIXME: If the destructor has a body that could throw, and the newly created 11215 // spec doesn't allow exceptions, we should emit a warning, because this 11216 // change in behavior can break conforming C++03 programs at runtime. 11217 // However, we don't have a body or an exception specification yet, so it 11218 // needs to be done somewhere else. 11219 } 11220 11221 namespace { 11222 /// An abstract base class for all helper classes used in building the 11223 // copy/move operators. These classes serve as factory functions and help us 11224 // avoid using the same Expr* in the AST twice. 11225 class ExprBuilder { 11226 ExprBuilder(const ExprBuilder&) = delete; 11227 ExprBuilder &operator=(const ExprBuilder&) = delete; 11228 11229 protected: 11230 static Expr *assertNotNull(Expr *E) { 11231 assert(E && "Expression construction must not fail."); 11232 return E; 11233 } 11234 11235 public: 11236 ExprBuilder() {} 11237 virtual ~ExprBuilder() {} 11238 11239 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11240 }; 11241 11242 class RefBuilder: public ExprBuilder { 11243 VarDecl *Var; 11244 QualType VarType; 11245 11246 public: 11247 Expr *build(Sema &S, SourceLocation Loc) const override { 11248 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11249 } 11250 11251 RefBuilder(VarDecl *Var, QualType VarType) 11252 : Var(Var), VarType(VarType) {} 11253 }; 11254 11255 class ThisBuilder: public ExprBuilder { 11256 public: 11257 Expr *build(Sema &S, SourceLocation Loc) const override { 11258 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11259 } 11260 }; 11261 11262 class CastBuilder: public ExprBuilder { 11263 const ExprBuilder &Builder; 11264 QualType Type; 11265 ExprValueKind Kind; 11266 const CXXCastPath &Path; 11267 11268 public: 11269 Expr *build(Sema &S, SourceLocation Loc) const override { 11270 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11271 CK_UncheckedDerivedToBase, Kind, 11272 &Path).get()); 11273 } 11274 11275 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11276 const CXXCastPath &Path) 11277 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11278 }; 11279 11280 class DerefBuilder: public ExprBuilder { 11281 const ExprBuilder &Builder; 11282 11283 public: 11284 Expr *build(Sema &S, SourceLocation Loc) const override { 11285 return assertNotNull( 11286 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11287 } 11288 11289 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11290 }; 11291 11292 class MemberBuilder: public ExprBuilder { 11293 const ExprBuilder &Builder; 11294 QualType Type; 11295 CXXScopeSpec SS; 11296 bool IsArrow; 11297 LookupResult &MemberLookup; 11298 11299 public: 11300 Expr *build(Sema &S, SourceLocation Loc) const override { 11301 return assertNotNull(S.BuildMemberReferenceExpr( 11302 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11303 nullptr, MemberLookup, nullptr, nullptr).get()); 11304 } 11305 11306 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11307 LookupResult &MemberLookup) 11308 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11309 MemberLookup(MemberLookup) {} 11310 }; 11311 11312 class MoveCastBuilder: public ExprBuilder { 11313 const ExprBuilder &Builder; 11314 11315 public: 11316 Expr *build(Sema &S, SourceLocation Loc) const override { 11317 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11318 } 11319 11320 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11321 }; 11322 11323 class LvalueConvBuilder: public ExprBuilder { 11324 const ExprBuilder &Builder; 11325 11326 public: 11327 Expr *build(Sema &S, SourceLocation Loc) const override { 11328 return assertNotNull( 11329 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11330 } 11331 11332 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11333 }; 11334 11335 class SubscriptBuilder: public ExprBuilder { 11336 const ExprBuilder &Base; 11337 const ExprBuilder &Index; 11338 11339 public: 11340 Expr *build(Sema &S, SourceLocation Loc) const override { 11341 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11342 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11343 } 11344 11345 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11346 : Base(Base), Index(Index) {} 11347 }; 11348 11349 } // end anonymous namespace 11350 11351 /// When generating a defaulted copy or move assignment operator, if a field 11352 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11353 /// do so. This optimization only applies for arrays of scalars, and for arrays 11354 /// of class type where the selected copy/move-assignment operator is trivial. 11355 static StmtResult 11356 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11357 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11358 // Compute the size of the memory buffer to be copied. 11359 QualType SizeType = S.Context.getSizeType(); 11360 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11361 S.Context.getTypeSizeInChars(T).getQuantity()); 11362 11363 // Take the address of the field references for "from" and "to". We 11364 // directly construct UnaryOperators here because semantic analysis 11365 // does not permit us to take the address of an xvalue. 11366 Expr *From = FromB.build(S, Loc); 11367 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11368 S.Context.getPointerType(From->getType()), 11369 VK_RValue, OK_Ordinary, Loc, false); 11370 Expr *To = ToB.build(S, Loc); 11371 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11372 S.Context.getPointerType(To->getType()), 11373 VK_RValue, OK_Ordinary, Loc, false); 11374 11375 const Type *E = T->getBaseElementTypeUnsafe(); 11376 bool NeedsCollectableMemCpy = 11377 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11378 11379 // Create a reference to the __builtin_objc_memmove_collectable function 11380 StringRef MemCpyName = NeedsCollectableMemCpy ? 11381 "__builtin_objc_memmove_collectable" : 11382 "__builtin_memcpy"; 11383 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11384 Sema::LookupOrdinaryName); 11385 S.LookupName(R, S.TUScope, true); 11386 11387 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11388 if (!MemCpy) 11389 // Something went horribly wrong earlier, and we will have complained 11390 // about it. 11391 return StmtError(); 11392 11393 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11394 VK_RValue, Loc, nullptr); 11395 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11396 11397 Expr *CallArgs[] = { 11398 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11399 }; 11400 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11401 Loc, CallArgs, Loc); 11402 11403 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11404 return Call.getAs<Stmt>(); 11405 } 11406 11407 /// Builds a statement that copies/moves the given entity from \p From to 11408 /// \c To. 11409 /// 11410 /// This routine is used to copy/move the members of a class with an 11411 /// implicitly-declared copy/move assignment operator. When the entities being 11412 /// copied are arrays, this routine builds for loops to copy them. 11413 /// 11414 /// \param S The Sema object used for type-checking. 11415 /// 11416 /// \param Loc The location where the implicit copy/move is being generated. 11417 /// 11418 /// \param T The type of the expressions being copied/moved. Both expressions 11419 /// must have this type. 11420 /// 11421 /// \param To The expression we are copying/moving to. 11422 /// 11423 /// \param From The expression we are copying/moving from. 11424 /// 11425 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11426 /// Otherwise, it's a non-static member subobject. 11427 /// 11428 /// \param Copying Whether we're copying or moving. 11429 /// 11430 /// \param Depth Internal parameter recording the depth of the recursion. 11431 /// 11432 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11433 /// if a memcpy should be used instead. 11434 static StmtResult 11435 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11436 const ExprBuilder &To, const ExprBuilder &From, 11437 bool CopyingBaseSubobject, bool Copying, 11438 unsigned Depth = 0) { 11439 // C++11 [class.copy]p28: 11440 // Each subobject is assigned in the manner appropriate to its type: 11441 // 11442 // - if the subobject is of class type, as if by a call to operator= with 11443 // the subobject as the object expression and the corresponding 11444 // subobject of x as a single function argument (as if by explicit 11445 // qualification; that is, ignoring any possible virtual overriding 11446 // functions in more derived classes); 11447 // 11448 // C++03 [class.copy]p13: 11449 // - if the subobject is of class type, the copy assignment operator for 11450 // the class is used (as if by explicit qualification; that is, 11451 // ignoring any possible virtual overriding functions in more derived 11452 // classes); 11453 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11454 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11455 11456 // Look for operator=. 11457 DeclarationName Name 11458 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11459 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11460 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11461 11462 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11463 // operator. 11464 if (!S.getLangOpts().CPlusPlus11) { 11465 LookupResult::Filter F = OpLookup.makeFilter(); 11466 while (F.hasNext()) { 11467 NamedDecl *D = F.next(); 11468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11469 if (Method->isCopyAssignmentOperator() || 11470 (!Copying && Method->isMoveAssignmentOperator())) 11471 continue; 11472 11473 F.erase(); 11474 } 11475 F.done(); 11476 } 11477 11478 // Suppress the protected check (C++ [class.protected]) for each of the 11479 // assignment operators we found. This strange dance is required when 11480 // we're assigning via a base classes's copy-assignment operator. To 11481 // ensure that we're getting the right base class subobject (without 11482 // ambiguities), we need to cast "this" to that subobject type; to 11483 // ensure that we don't go through the virtual call mechanism, we need 11484 // to qualify the operator= name with the base class (see below). However, 11485 // this means that if the base class has a protected copy assignment 11486 // operator, the protected member access check will fail. So, we 11487 // rewrite "protected" access to "public" access in this case, since we 11488 // know by construction that we're calling from a derived class. 11489 if (CopyingBaseSubobject) { 11490 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11491 L != LEnd; ++L) { 11492 if (L.getAccess() == AS_protected) 11493 L.setAccess(AS_public); 11494 } 11495 } 11496 11497 // Create the nested-name-specifier that will be used to qualify the 11498 // reference to operator=; this is required to suppress the virtual 11499 // call mechanism. 11500 CXXScopeSpec SS; 11501 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11502 SS.MakeTrivial(S.Context, 11503 NestedNameSpecifier::Create(S.Context, nullptr, false, 11504 CanonicalT), 11505 Loc); 11506 11507 // Create the reference to operator=. 11508 ExprResult OpEqualRef 11509 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11510 SS, /*TemplateKWLoc=*/SourceLocation(), 11511 /*FirstQualifierInScope=*/nullptr, 11512 OpLookup, 11513 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11514 /*SuppressQualifierCheck=*/true); 11515 if (OpEqualRef.isInvalid()) 11516 return StmtError(); 11517 11518 // Build the call to the assignment operator. 11519 11520 Expr *FromInst = From.build(S, Loc); 11521 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11522 OpEqualRef.getAs<Expr>(), 11523 Loc, FromInst, Loc); 11524 if (Call.isInvalid()) 11525 return StmtError(); 11526 11527 // If we built a call to a trivial 'operator=' while copying an array, 11528 // bail out. We'll replace the whole shebang with a memcpy. 11529 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11530 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11531 return StmtResult((Stmt*)nullptr); 11532 11533 // Convert to an expression-statement, and clean up any produced 11534 // temporaries. 11535 return S.ActOnExprStmt(Call); 11536 } 11537 11538 // - if the subobject is of scalar type, the built-in assignment 11539 // operator is used. 11540 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11541 if (!ArrayTy) { 11542 ExprResult Assignment = S.CreateBuiltinBinOp( 11543 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11544 if (Assignment.isInvalid()) 11545 return StmtError(); 11546 return S.ActOnExprStmt(Assignment); 11547 } 11548 11549 // - if the subobject is an array, each element is assigned, in the 11550 // manner appropriate to the element type; 11551 11552 // Construct a loop over the array bounds, e.g., 11553 // 11554 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11555 // 11556 // that will copy each of the array elements. 11557 QualType SizeType = S.Context.getSizeType(); 11558 11559 // Create the iteration variable. 11560 IdentifierInfo *IterationVarName = nullptr; 11561 { 11562 SmallString<8> Str; 11563 llvm::raw_svector_ostream OS(Str); 11564 OS << "__i" << Depth; 11565 IterationVarName = &S.Context.Idents.get(OS.str()); 11566 } 11567 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11568 IterationVarName, SizeType, 11569 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11570 SC_None); 11571 11572 // Initialize the iteration variable to zero. 11573 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11574 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11575 11576 // Creates a reference to the iteration variable. 11577 RefBuilder IterationVarRef(IterationVar, SizeType); 11578 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11579 11580 // Create the DeclStmt that holds the iteration variable. 11581 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11582 11583 // Subscript the "from" and "to" expressions with the iteration variable. 11584 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11585 MoveCastBuilder FromIndexMove(FromIndexCopy); 11586 const ExprBuilder *FromIndex; 11587 if (Copying) 11588 FromIndex = &FromIndexCopy; 11589 else 11590 FromIndex = &FromIndexMove; 11591 11592 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11593 11594 // Build the copy/move for an individual element of the array. 11595 StmtResult Copy = 11596 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11597 ToIndex, *FromIndex, CopyingBaseSubobject, 11598 Copying, Depth + 1); 11599 // Bail out if copying fails or if we determined that we should use memcpy. 11600 if (Copy.isInvalid() || !Copy.get()) 11601 return Copy; 11602 11603 // Create the comparison against the array bound. 11604 llvm::APInt Upper 11605 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11606 Expr *Comparison 11607 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11608 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11609 BO_NE, S.Context.BoolTy, 11610 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11611 11612 // Create the pre-increment of the iteration variable. We can determine 11613 // whether the increment will overflow based on the value of the array 11614 // bound. 11615 Expr *Increment = new (S.Context) 11616 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11617 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11618 11619 // Construct the loop that copies all elements of this array. 11620 return S.ActOnForStmt( 11621 Loc, Loc, InitStmt, 11622 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11623 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11624 } 11625 11626 static StmtResult 11627 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11628 const ExprBuilder &To, const ExprBuilder &From, 11629 bool CopyingBaseSubobject, bool Copying) { 11630 // Maybe we should use a memcpy? 11631 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11632 T.isTriviallyCopyableType(S.Context)) 11633 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11634 11635 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11636 CopyingBaseSubobject, 11637 Copying, 0)); 11638 11639 // If we ended up picking a trivial assignment operator for an array of a 11640 // non-trivially-copyable class type, just emit a memcpy. 11641 if (!Result.isInvalid() && !Result.get()) 11642 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11643 11644 return Result; 11645 } 11646 11647 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11648 // Note: The following rules are largely analoguous to the copy 11649 // constructor rules. Note that virtual bases are not taken into account 11650 // for determining the argument type of the operator. Note also that 11651 // operators taking an object instead of a reference are allowed. 11652 assert(ClassDecl->needsImplicitCopyAssignment()); 11653 11654 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11655 if (DSM.isAlreadyBeingDeclared()) 11656 return nullptr; 11657 11658 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11659 QualType RetType = Context.getLValueReferenceType(ArgType); 11660 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11661 if (Const) 11662 ArgType = ArgType.withConst(); 11663 ArgType = Context.getLValueReferenceType(ArgType); 11664 11665 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11666 CXXCopyAssignment, 11667 Const); 11668 11669 // An implicitly-declared copy assignment operator is an inline public 11670 // member of its class. 11671 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11672 SourceLocation ClassLoc = ClassDecl->getLocation(); 11673 DeclarationNameInfo NameInfo(Name, ClassLoc); 11674 CXXMethodDecl *CopyAssignment = 11675 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11676 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11677 /*isInline=*/true, Constexpr, SourceLocation()); 11678 CopyAssignment->setAccess(AS_public); 11679 CopyAssignment->setDefaulted(); 11680 CopyAssignment->setImplicit(); 11681 11682 if (getLangOpts().CUDA) { 11683 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11684 CopyAssignment, 11685 /* ConstRHS */ Const, 11686 /* Diagnose */ false); 11687 } 11688 11689 // Build an exception specification pointing back at this member. 11690 FunctionProtoType::ExtProtoInfo EPI = 11691 getImplicitMethodEPI(*this, CopyAssignment); 11692 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11693 11694 // Add the parameter to the operator. 11695 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11696 ClassLoc, ClassLoc, 11697 /*Id=*/nullptr, ArgType, 11698 /*TInfo=*/nullptr, SC_None, 11699 nullptr); 11700 CopyAssignment->setParams(FromParam); 11701 11702 CopyAssignment->setTrivial( 11703 ClassDecl->needsOverloadResolutionForCopyAssignment() 11704 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11705 : ClassDecl->hasTrivialCopyAssignment()); 11706 11707 // Note that we have added this copy-assignment operator. 11708 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11709 11710 Scope *S = getScopeForContext(ClassDecl); 11711 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11712 11713 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11714 SetDeclDeleted(CopyAssignment, ClassLoc); 11715 11716 if (S) 11717 PushOnScopeChains(CopyAssignment, S, false); 11718 ClassDecl->addDecl(CopyAssignment); 11719 11720 return CopyAssignment; 11721 } 11722 11723 /// Diagnose an implicit copy operation for a class which is odr-used, but 11724 /// which is deprecated because the class has a user-declared copy constructor, 11725 /// copy assignment operator, or destructor. 11726 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11727 assert(CopyOp->isImplicit()); 11728 11729 CXXRecordDecl *RD = CopyOp->getParent(); 11730 CXXMethodDecl *UserDeclaredOperation = nullptr; 11731 11732 // In Microsoft mode, assignment operations don't affect constructors and 11733 // vice versa. 11734 if (RD->hasUserDeclaredDestructor()) { 11735 UserDeclaredOperation = RD->getDestructor(); 11736 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11737 RD->hasUserDeclaredCopyConstructor() && 11738 !S.getLangOpts().MSVCCompat) { 11739 // Find any user-declared copy constructor. 11740 for (auto *I : RD->ctors()) { 11741 if (I->isCopyConstructor()) { 11742 UserDeclaredOperation = I; 11743 break; 11744 } 11745 } 11746 assert(UserDeclaredOperation); 11747 } else if (isa<CXXConstructorDecl>(CopyOp) && 11748 RD->hasUserDeclaredCopyAssignment() && 11749 !S.getLangOpts().MSVCCompat) { 11750 // Find any user-declared move assignment operator. 11751 for (auto *I : RD->methods()) { 11752 if (I->isCopyAssignmentOperator()) { 11753 UserDeclaredOperation = I; 11754 break; 11755 } 11756 } 11757 assert(UserDeclaredOperation); 11758 } 11759 11760 if (UserDeclaredOperation) { 11761 S.Diag(UserDeclaredOperation->getLocation(), 11762 diag::warn_deprecated_copy_operation) 11763 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11764 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11765 } 11766 } 11767 11768 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11769 CXXMethodDecl *CopyAssignOperator) { 11770 assert((CopyAssignOperator->isDefaulted() && 11771 CopyAssignOperator->isOverloadedOperator() && 11772 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11773 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11774 !CopyAssignOperator->isDeleted()) && 11775 "DefineImplicitCopyAssignment called for wrong function"); 11776 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11777 return; 11778 11779 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11780 if (ClassDecl->isInvalidDecl()) { 11781 CopyAssignOperator->setInvalidDecl(); 11782 return; 11783 } 11784 11785 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11786 11787 // The exception specification is needed because we are defining the 11788 // function. 11789 ResolveExceptionSpec(CurrentLocation, 11790 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11791 11792 // Add a context note for diagnostics produced after this point. 11793 Scope.addContextNote(CurrentLocation); 11794 11795 // C++11 [class.copy]p18: 11796 // The [definition of an implicitly declared copy assignment operator] is 11797 // deprecated if the class has a user-declared copy constructor or a 11798 // user-declared destructor. 11799 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11800 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11801 11802 // C++0x [class.copy]p30: 11803 // The implicitly-defined or explicitly-defaulted copy assignment operator 11804 // for a non-union class X performs memberwise copy assignment of its 11805 // subobjects. The direct base classes of X are assigned first, in the 11806 // order of their declaration in the base-specifier-list, and then the 11807 // immediate non-static data members of X are assigned, in the order in 11808 // which they were declared in the class definition. 11809 11810 // The statements that form the synthesized function body. 11811 SmallVector<Stmt*, 8> Statements; 11812 11813 // The parameter for the "other" object, which we are copying from. 11814 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11815 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11816 QualType OtherRefType = Other->getType(); 11817 if (const LValueReferenceType *OtherRef 11818 = OtherRefType->getAs<LValueReferenceType>()) { 11819 OtherRefType = OtherRef->getPointeeType(); 11820 OtherQuals = OtherRefType.getQualifiers(); 11821 } 11822 11823 // Our location for everything implicitly-generated. 11824 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11825 ? CopyAssignOperator->getLocEnd() 11826 : CopyAssignOperator->getLocation(); 11827 11828 // Builds a DeclRefExpr for the "other" object. 11829 RefBuilder OtherRef(Other, OtherRefType); 11830 11831 // Builds the "this" pointer. 11832 ThisBuilder This; 11833 11834 // Assign base classes. 11835 bool Invalid = false; 11836 for (auto &Base : ClassDecl->bases()) { 11837 // Form the assignment: 11838 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11839 QualType BaseType = Base.getType().getUnqualifiedType(); 11840 if (!BaseType->isRecordType()) { 11841 Invalid = true; 11842 continue; 11843 } 11844 11845 CXXCastPath BasePath; 11846 BasePath.push_back(&Base); 11847 11848 // Construct the "from" expression, which is an implicit cast to the 11849 // appropriately-qualified base type. 11850 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11851 VK_LValue, BasePath); 11852 11853 // Dereference "this". 11854 DerefBuilder DerefThis(This); 11855 CastBuilder To(DerefThis, 11856 Context.getCVRQualifiedType( 11857 BaseType, CopyAssignOperator->getTypeQualifiers()), 11858 VK_LValue, BasePath); 11859 11860 // Build the copy. 11861 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11862 To, From, 11863 /*CopyingBaseSubobject=*/true, 11864 /*Copying=*/true); 11865 if (Copy.isInvalid()) { 11866 CopyAssignOperator->setInvalidDecl(); 11867 return; 11868 } 11869 11870 // Success! Record the copy. 11871 Statements.push_back(Copy.getAs<Expr>()); 11872 } 11873 11874 // Assign non-static members. 11875 for (auto *Field : ClassDecl->fields()) { 11876 // FIXME: We should form some kind of AST representation for the implied 11877 // memcpy in a union copy operation. 11878 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11879 continue; 11880 11881 if (Field->isInvalidDecl()) { 11882 Invalid = true; 11883 continue; 11884 } 11885 11886 // Check for members of reference type; we can't copy those. 11887 if (Field->getType()->isReferenceType()) { 11888 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11889 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11890 Diag(Field->getLocation(), diag::note_declared_at); 11891 Invalid = true; 11892 continue; 11893 } 11894 11895 // Check for members of const-qualified, non-class type. 11896 QualType BaseType = Context.getBaseElementType(Field->getType()); 11897 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11898 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11899 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11900 Diag(Field->getLocation(), diag::note_declared_at); 11901 Invalid = true; 11902 continue; 11903 } 11904 11905 // Suppress assigning zero-width bitfields. 11906 if (Field->isZeroLengthBitField(Context)) 11907 continue; 11908 11909 QualType FieldType = Field->getType().getNonReferenceType(); 11910 if (FieldType->isIncompleteArrayType()) { 11911 assert(ClassDecl->hasFlexibleArrayMember() && 11912 "Incomplete array type is not valid"); 11913 continue; 11914 } 11915 11916 // Build references to the field in the object we're copying from and to. 11917 CXXScopeSpec SS; // Intentionally empty 11918 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11919 LookupMemberName); 11920 MemberLookup.addDecl(Field); 11921 MemberLookup.resolveKind(); 11922 11923 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11924 11925 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11926 11927 // Build the copy of this field. 11928 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11929 To, From, 11930 /*CopyingBaseSubobject=*/false, 11931 /*Copying=*/true); 11932 if (Copy.isInvalid()) { 11933 CopyAssignOperator->setInvalidDecl(); 11934 return; 11935 } 11936 11937 // Success! Record the copy. 11938 Statements.push_back(Copy.getAs<Stmt>()); 11939 } 11940 11941 if (!Invalid) { 11942 // Add a "return *this;" 11943 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11944 11945 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11946 if (Return.isInvalid()) 11947 Invalid = true; 11948 else 11949 Statements.push_back(Return.getAs<Stmt>()); 11950 } 11951 11952 if (Invalid) { 11953 CopyAssignOperator->setInvalidDecl(); 11954 return; 11955 } 11956 11957 StmtResult Body; 11958 { 11959 CompoundScopeRAII CompoundScope(*this); 11960 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11961 /*isStmtExpr=*/false); 11962 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11963 } 11964 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11965 CopyAssignOperator->markUsed(Context); 11966 11967 if (ASTMutationListener *L = getASTMutationListener()) { 11968 L->CompletedImplicitDefinition(CopyAssignOperator); 11969 } 11970 } 11971 11972 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11973 assert(ClassDecl->needsImplicitMoveAssignment()); 11974 11975 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11976 if (DSM.isAlreadyBeingDeclared()) 11977 return nullptr; 11978 11979 // Note: The following rules are largely analoguous to the move 11980 // constructor rules. 11981 11982 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11983 QualType RetType = Context.getLValueReferenceType(ArgType); 11984 ArgType = Context.getRValueReferenceType(ArgType); 11985 11986 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11987 CXXMoveAssignment, 11988 false); 11989 11990 // An implicitly-declared move assignment operator is an inline public 11991 // member of its class. 11992 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11993 SourceLocation ClassLoc = ClassDecl->getLocation(); 11994 DeclarationNameInfo NameInfo(Name, ClassLoc); 11995 CXXMethodDecl *MoveAssignment = 11996 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11997 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11998 /*isInline=*/true, Constexpr, SourceLocation()); 11999 MoveAssignment->setAccess(AS_public); 12000 MoveAssignment->setDefaulted(); 12001 MoveAssignment->setImplicit(); 12002 12003 if (getLangOpts().CUDA) { 12004 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12005 MoveAssignment, 12006 /* ConstRHS */ false, 12007 /* Diagnose */ false); 12008 } 12009 12010 // Build an exception specification pointing back at this member. 12011 FunctionProtoType::ExtProtoInfo EPI = 12012 getImplicitMethodEPI(*this, MoveAssignment); 12013 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12014 12015 // Add the parameter to the operator. 12016 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12017 ClassLoc, ClassLoc, 12018 /*Id=*/nullptr, ArgType, 12019 /*TInfo=*/nullptr, SC_None, 12020 nullptr); 12021 MoveAssignment->setParams(FromParam); 12022 12023 MoveAssignment->setTrivial( 12024 ClassDecl->needsOverloadResolutionForMoveAssignment() 12025 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12026 : ClassDecl->hasTrivialMoveAssignment()); 12027 12028 // Note that we have added this copy-assignment operator. 12029 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 12030 12031 Scope *S = getScopeForContext(ClassDecl); 12032 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12033 12034 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12035 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12036 SetDeclDeleted(MoveAssignment, ClassLoc); 12037 } 12038 12039 if (S) 12040 PushOnScopeChains(MoveAssignment, S, false); 12041 ClassDecl->addDecl(MoveAssignment); 12042 12043 return MoveAssignment; 12044 } 12045 12046 /// Check if we're implicitly defining a move assignment operator for a class 12047 /// with virtual bases. Such a move assignment might move-assign the virtual 12048 /// base multiple times. 12049 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12050 SourceLocation CurrentLocation) { 12051 assert(!Class->isDependentContext() && "should not define dependent move"); 12052 12053 // Only a virtual base could get implicitly move-assigned multiple times. 12054 // Only a non-trivial move assignment can observe this. We only want to 12055 // diagnose if we implicitly define an assignment operator that assigns 12056 // two base classes, both of which move-assign the same virtual base. 12057 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12058 Class->getNumBases() < 2) 12059 return; 12060 12061 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12062 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12063 VBaseMap VBases; 12064 12065 for (auto &BI : Class->bases()) { 12066 Worklist.push_back(&BI); 12067 while (!Worklist.empty()) { 12068 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12069 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12070 12071 // If the base has no non-trivial move assignment operators, 12072 // we don't care about moves from it. 12073 if (!Base->hasNonTrivialMoveAssignment()) 12074 continue; 12075 12076 // If there's nothing virtual here, skip it. 12077 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12078 continue; 12079 12080 // If we're not actually going to call a move assignment for this base, 12081 // or the selected move assignment is trivial, skip it. 12082 Sema::SpecialMemberOverloadResult SMOR = 12083 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12084 /*ConstArg*/false, /*VolatileArg*/false, 12085 /*RValueThis*/true, /*ConstThis*/false, 12086 /*VolatileThis*/false); 12087 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12088 !SMOR.getMethod()->isMoveAssignmentOperator()) 12089 continue; 12090 12091 if (BaseSpec->isVirtual()) { 12092 // We're going to move-assign this virtual base, and its move 12093 // assignment operator is not trivial. If this can happen for 12094 // multiple distinct direct bases of Class, diagnose it. (If it 12095 // only happens in one base, we'll diagnose it when synthesizing 12096 // that base class's move assignment operator.) 12097 CXXBaseSpecifier *&Existing = 12098 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12099 .first->second; 12100 if (Existing && Existing != &BI) { 12101 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12102 << Class << Base; 12103 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 12104 << (Base->getCanonicalDecl() == 12105 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12106 << Base << Existing->getType() << Existing->getSourceRange(); 12107 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 12108 << (Base->getCanonicalDecl() == 12109 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12110 << Base << BI.getType() << BaseSpec->getSourceRange(); 12111 12112 // Only diagnose each vbase once. 12113 Existing = nullptr; 12114 } 12115 } else { 12116 // Only walk over bases that have defaulted move assignment operators. 12117 // We assume that any user-provided move assignment operator handles 12118 // the multiple-moves-of-vbase case itself somehow. 12119 if (!SMOR.getMethod()->isDefaulted()) 12120 continue; 12121 12122 // We're going to move the base classes of Base. Add them to the list. 12123 for (auto &BI : Base->bases()) 12124 Worklist.push_back(&BI); 12125 } 12126 } 12127 } 12128 } 12129 12130 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12131 CXXMethodDecl *MoveAssignOperator) { 12132 assert((MoveAssignOperator->isDefaulted() && 12133 MoveAssignOperator->isOverloadedOperator() && 12134 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12135 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12136 !MoveAssignOperator->isDeleted()) && 12137 "DefineImplicitMoveAssignment called for wrong function"); 12138 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12139 return; 12140 12141 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12142 if (ClassDecl->isInvalidDecl()) { 12143 MoveAssignOperator->setInvalidDecl(); 12144 return; 12145 } 12146 12147 // C++0x [class.copy]p28: 12148 // The implicitly-defined or move assignment operator for a non-union class 12149 // X performs memberwise move assignment of its subobjects. The direct base 12150 // classes of X are assigned first, in the order of their declaration in the 12151 // base-specifier-list, and then the immediate non-static data members of X 12152 // are assigned, in the order in which they were declared in the class 12153 // definition. 12154 12155 // Issue a warning if our implicit move assignment operator will move 12156 // from a virtual base more than once. 12157 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12158 12159 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12160 12161 // The exception specification is needed because we are defining the 12162 // function. 12163 ResolveExceptionSpec(CurrentLocation, 12164 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12165 12166 // Add a context note for diagnostics produced after this point. 12167 Scope.addContextNote(CurrentLocation); 12168 12169 // The statements that form the synthesized function body. 12170 SmallVector<Stmt*, 8> Statements; 12171 12172 // The parameter for the "other" object, which we are move from. 12173 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12174 QualType OtherRefType = Other->getType()-> 12175 getAs<RValueReferenceType>()->getPointeeType(); 12176 assert(!OtherRefType.getQualifiers() && 12177 "Bad argument type of defaulted move assignment"); 12178 12179 // Our location for everything implicitly-generated. 12180 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 12181 ? MoveAssignOperator->getLocEnd() 12182 : MoveAssignOperator->getLocation(); 12183 12184 // Builds a reference to the "other" object. 12185 RefBuilder OtherRef(Other, OtherRefType); 12186 // Cast to rvalue. 12187 MoveCastBuilder MoveOther(OtherRef); 12188 12189 // Builds the "this" pointer. 12190 ThisBuilder This; 12191 12192 // Assign base classes. 12193 bool Invalid = false; 12194 for (auto &Base : ClassDecl->bases()) { 12195 // C++11 [class.copy]p28: 12196 // It is unspecified whether subobjects representing virtual base classes 12197 // are assigned more than once by the implicitly-defined copy assignment 12198 // operator. 12199 // FIXME: Do not assign to a vbase that will be assigned by some other base 12200 // class. For a move-assignment, this can result in the vbase being moved 12201 // multiple times. 12202 12203 // Form the assignment: 12204 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12205 QualType BaseType = Base.getType().getUnqualifiedType(); 12206 if (!BaseType->isRecordType()) { 12207 Invalid = true; 12208 continue; 12209 } 12210 12211 CXXCastPath BasePath; 12212 BasePath.push_back(&Base); 12213 12214 // Construct the "from" expression, which is an implicit cast to the 12215 // appropriately-qualified base type. 12216 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12217 12218 // Dereference "this". 12219 DerefBuilder DerefThis(This); 12220 12221 // Implicitly cast "this" to the appropriately-qualified base type. 12222 CastBuilder To(DerefThis, 12223 Context.getCVRQualifiedType( 12224 BaseType, MoveAssignOperator->getTypeQualifiers()), 12225 VK_LValue, BasePath); 12226 12227 // Build the move. 12228 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12229 To, From, 12230 /*CopyingBaseSubobject=*/true, 12231 /*Copying=*/false); 12232 if (Move.isInvalid()) { 12233 MoveAssignOperator->setInvalidDecl(); 12234 return; 12235 } 12236 12237 // Success! Record the move. 12238 Statements.push_back(Move.getAs<Expr>()); 12239 } 12240 12241 // Assign non-static members. 12242 for (auto *Field : ClassDecl->fields()) { 12243 // FIXME: We should form some kind of AST representation for the implied 12244 // memcpy in a union copy operation. 12245 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12246 continue; 12247 12248 if (Field->isInvalidDecl()) { 12249 Invalid = true; 12250 continue; 12251 } 12252 12253 // Check for members of reference type; we can't move those. 12254 if (Field->getType()->isReferenceType()) { 12255 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12256 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12257 Diag(Field->getLocation(), diag::note_declared_at); 12258 Invalid = true; 12259 continue; 12260 } 12261 12262 // Check for members of const-qualified, non-class type. 12263 QualType BaseType = Context.getBaseElementType(Field->getType()); 12264 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12265 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12266 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12267 Diag(Field->getLocation(), diag::note_declared_at); 12268 Invalid = true; 12269 continue; 12270 } 12271 12272 // Suppress assigning zero-width bitfields. 12273 if (Field->isZeroLengthBitField(Context)) 12274 continue; 12275 12276 QualType FieldType = Field->getType().getNonReferenceType(); 12277 if (FieldType->isIncompleteArrayType()) { 12278 assert(ClassDecl->hasFlexibleArrayMember() && 12279 "Incomplete array type is not valid"); 12280 continue; 12281 } 12282 12283 // Build references to the field in the object we're copying from and to. 12284 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12285 LookupMemberName); 12286 MemberLookup.addDecl(Field); 12287 MemberLookup.resolveKind(); 12288 MemberBuilder From(MoveOther, OtherRefType, 12289 /*IsArrow=*/false, MemberLookup); 12290 MemberBuilder To(This, getCurrentThisType(), 12291 /*IsArrow=*/true, MemberLookup); 12292 12293 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12294 "Member reference with rvalue base must be rvalue except for reference " 12295 "members, which aren't allowed for move assignment."); 12296 12297 // Build the move of this field. 12298 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12299 To, From, 12300 /*CopyingBaseSubobject=*/false, 12301 /*Copying=*/false); 12302 if (Move.isInvalid()) { 12303 MoveAssignOperator->setInvalidDecl(); 12304 return; 12305 } 12306 12307 // Success! Record the copy. 12308 Statements.push_back(Move.getAs<Stmt>()); 12309 } 12310 12311 if (!Invalid) { 12312 // Add a "return *this;" 12313 ExprResult ThisObj = 12314 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12315 12316 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12317 if (Return.isInvalid()) 12318 Invalid = true; 12319 else 12320 Statements.push_back(Return.getAs<Stmt>()); 12321 } 12322 12323 if (Invalid) { 12324 MoveAssignOperator->setInvalidDecl(); 12325 return; 12326 } 12327 12328 StmtResult Body; 12329 { 12330 CompoundScopeRAII CompoundScope(*this); 12331 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12332 /*isStmtExpr=*/false); 12333 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12334 } 12335 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12336 MoveAssignOperator->markUsed(Context); 12337 12338 if (ASTMutationListener *L = getASTMutationListener()) { 12339 L->CompletedImplicitDefinition(MoveAssignOperator); 12340 } 12341 } 12342 12343 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12344 CXXRecordDecl *ClassDecl) { 12345 // C++ [class.copy]p4: 12346 // If the class definition does not explicitly declare a copy 12347 // constructor, one is declared implicitly. 12348 assert(ClassDecl->needsImplicitCopyConstructor()); 12349 12350 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12351 if (DSM.isAlreadyBeingDeclared()) 12352 return nullptr; 12353 12354 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12355 QualType ArgType = ClassType; 12356 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12357 if (Const) 12358 ArgType = ArgType.withConst(); 12359 ArgType = Context.getLValueReferenceType(ArgType); 12360 12361 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12362 CXXCopyConstructor, 12363 Const); 12364 12365 DeclarationName Name 12366 = Context.DeclarationNames.getCXXConstructorName( 12367 Context.getCanonicalType(ClassType)); 12368 SourceLocation ClassLoc = ClassDecl->getLocation(); 12369 DeclarationNameInfo NameInfo(Name, ClassLoc); 12370 12371 // An implicitly-declared copy constructor is an inline public 12372 // member of its class. 12373 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12374 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12375 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12376 Constexpr); 12377 CopyConstructor->setAccess(AS_public); 12378 CopyConstructor->setDefaulted(); 12379 12380 if (getLangOpts().CUDA) { 12381 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12382 CopyConstructor, 12383 /* ConstRHS */ Const, 12384 /* Diagnose */ false); 12385 } 12386 12387 // Build an exception specification pointing back at this member. 12388 FunctionProtoType::ExtProtoInfo EPI = 12389 getImplicitMethodEPI(*this, CopyConstructor); 12390 CopyConstructor->setType( 12391 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12392 12393 // Add the parameter to the constructor. 12394 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12395 ClassLoc, ClassLoc, 12396 /*IdentifierInfo=*/nullptr, 12397 ArgType, /*TInfo=*/nullptr, 12398 SC_None, nullptr); 12399 CopyConstructor->setParams(FromParam); 12400 12401 CopyConstructor->setTrivial( 12402 ClassDecl->needsOverloadResolutionForCopyConstructor() 12403 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12404 : ClassDecl->hasTrivialCopyConstructor()); 12405 12406 CopyConstructor->setTrivialForCall( 12407 ClassDecl->hasAttr<TrivialABIAttr>() || 12408 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12409 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12410 TAH_ConsiderTrivialABI) 12411 : ClassDecl->hasTrivialCopyConstructorForCall())); 12412 12413 // Note that we have declared this constructor. 12414 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12415 12416 Scope *S = getScopeForContext(ClassDecl); 12417 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12418 12419 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12420 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12421 SetDeclDeleted(CopyConstructor, ClassLoc); 12422 } 12423 12424 if (S) 12425 PushOnScopeChains(CopyConstructor, S, false); 12426 ClassDecl->addDecl(CopyConstructor); 12427 12428 return CopyConstructor; 12429 } 12430 12431 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12432 CXXConstructorDecl *CopyConstructor) { 12433 assert((CopyConstructor->isDefaulted() && 12434 CopyConstructor->isCopyConstructor() && 12435 !CopyConstructor->doesThisDeclarationHaveABody() && 12436 !CopyConstructor->isDeleted()) && 12437 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12438 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12439 return; 12440 12441 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12442 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12443 12444 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12445 12446 // The exception specification is needed because we are defining the 12447 // function. 12448 ResolveExceptionSpec(CurrentLocation, 12449 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12450 MarkVTableUsed(CurrentLocation, ClassDecl); 12451 12452 // Add a context note for diagnostics produced after this point. 12453 Scope.addContextNote(CurrentLocation); 12454 12455 // C++11 [class.copy]p7: 12456 // The [definition of an implicitly declared copy constructor] is 12457 // deprecated if the class has a user-declared copy assignment operator 12458 // or a user-declared destructor. 12459 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12460 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12461 12462 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12463 CopyConstructor->setInvalidDecl(); 12464 } else { 12465 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12466 ? CopyConstructor->getLocEnd() 12467 : CopyConstructor->getLocation(); 12468 Sema::CompoundScopeRAII CompoundScope(*this); 12469 CopyConstructor->setBody( 12470 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12471 CopyConstructor->markUsed(Context); 12472 } 12473 12474 if (ASTMutationListener *L = getASTMutationListener()) { 12475 L->CompletedImplicitDefinition(CopyConstructor); 12476 } 12477 } 12478 12479 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12480 CXXRecordDecl *ClassDecl) { 12481 assert(ClassDecl->needsImplicitMoveConstructor()); 12482 12483 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12484 if (DSM.isAlreadyBeingDeclared()) 12485 return nullptr; 12486 12487 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12488 QualType ArgType = Context.getRValueReferenceType(ClassType); 12489 12490 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12491 CXXMoveConstructor, 12492 false); 12493 12494 DeclarationName Name 12495 = Context.DeclarationNames.getCXXConstructorName( 12496 Context.getCanonicalType(ClassType)); 12497 SourceLocation ClassLoc = ClassDecl->getLocation(); 12498 DeclarationNameInfo NameInfo(Name, ClassLoc); 12499 12500 // C++11 [class.copy]p11: 12501 // An implicitly-declared copy/move constructor is an inline public 12502 // member of its class. 12503 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12504 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12505 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12506 Constexpr); 12507 MoveConstructor->setAccess(AS_public); 12508 MoveConstructor->setDefaulted(); 12509 12510 if (getLangOpts().CUDA) { 12511 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12512 MoveConstructor, 12513 /* ConstRHS */ false, 12514 /* Diagnose */ false); 12515 } 12516 12517 // Build an exception specification pointing back at this member. 12518 FunctionProtoType::ExtProtoInfo EPI = 12519 getImplicitMethodEPI(*this, MoveConstructor); 12520 MoveConstructor->setType( 12521 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12522 12523 // Add the parameter to the constructor. 12524 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12525 ClassLoc, ClassLoc, 12526 /*IdentifierInfo=*/nullptr, 12527 ArgType, /*TInfo=*/nullptr, 12528 SC_None, nullptr); 12529 MoveConstructor->setParams(FromParam); 12530 12531 MoveConstructor->setTrivial( 12532 ClassDecl->needsOverloadResolutionForMoveConstructor() 12533 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12534 : ClassDecl->hasTrivialMoveConstructor()); 12535 12536 MoveConstructor->setTrivialForCall( 12537 ClassDecl->hasAttr<TrivialABIAttr>() || 12538 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12539 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12540 TAH_ConsiderTrivialABI) 12541 : ClassDecl->hasTrivialMoveConstructorForCall())); 12542 12543 // Note that we have declared this constructor. 12544 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12545 12546 Scope *S = getScopeForContext(ClassDecl); 12547 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12548 12549 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12550 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12551 SetDeclDeleted(MoveConstructor, ClassLoc); 12552 } 12553 12554 if (S) 12555 PushOnScopeChains(MoveConstructor, S, false); 12556 ClassDecl->addDecl(MoveConstructor); 12557 12558 return MoveConstructor; 12559 } 12560 12561 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12562 CXXConstructorDecl *MoveConstructor) { 12563 assert((MoveConstructor->isDefaulted() && 12564 MoveConstructor->isMoveConstructor() && 12565 !MoveConstructor->doesThisDeclarationHaveABody() && 12566 !MoveConstructor->isDeleted()) && 12567 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12568 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12569 return; 12570 12571 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12572 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12573 12574 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12575 12576 // The exception specification is needed because we are defining the 12577 // function. 12578 ResolveExceptionSpec(CurrentLocation, 12579 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12580 MarkVTableUsed(CurrentLocation, ClassDecl); 12581 12582 // Add a context note for diagnostics produced after this point. 12583 Scope.addContextNote(CurrentLocation); 12584 12585 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12586 MoveConstructor->setInvalidDecl(); 12587 } else { 12588 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12589 ? MoveConstructor->getLocEnd() 12590 : MoveConstructor->getLocation(); 12591 Sema::CompoundScopeRAII CompoundScope(*this); 12592 MoveConstructor->setBody(ActOnCompoundStmt( 12593 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12594 MoveConstructor->markUsed(Context); 12595 } 12596 12597 if (ASTMutationListener *L = getASTMutationListener()) { 12598 L->CompletedImplicitDefinition(MoveConstructor); 12599 } 12600 } 12601 12602 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12603 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12604 } 12605 12606 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12607 SourceLocation CurrentLocation, 12608 CXXConversionDecl *Conv) { 12609 SynthesizedFunctionScope Scope(*this, Conv); 12610 assert(!Conv->getReturnType()->isUndeducedType()); 12611 12612 CXXRecordDecl *Lambda = Conv->getParent(); 12613 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12614 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12615 12616 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12617 CallOp = InstantiateFunctionDeclaration( 12618 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12619 if (!CallOp) 12620 return; 12621 12622 Invoker = InstantiateFunctionDeclaration( 12623 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12624 if (!Invoker) 12625 return; 12626 } 12627 12628 if (CallOp->isInvalidDecl()) 12629 return; 12630 12631 // Mark the call operator referenced (and add to pending instantiations 12632 // if necessary). 12633 // For both the conversion and static-invoker template specializations 12634 // we construct their body's in this function, so no need to add them 12635 // to the PendingInstantiations. 12636 MarkFunctionReferenced(CurrentLocation, CallOp); 12637 12638 // Fill in the __invoke function with a dummy implementation. IR generation 12639 // will fill in the actual details. Update its type in case it contained 12640 // an 'auto'. 12641 Invoker->markUsed(Context); 12642 Invoker->setReferenced(); 12643 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12644 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12645 12646 // Construct the body of the conversion function { return __invoke; }. 12647 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12648 VK_LValue, Conv->getLocation()).get(); 12649 assert(FunctionRef && "Can't refer to __invoke function?"); 12650 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12651 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12652 Conv->getLocation())); 12653 Conv->markUsed(Context); 12654 Conv->setReferenced(); 12655 12656 if (ASTMutationListener *L = getASTMutationListener()) { 12657 L->CompletedImplicitDefinition(Conv); 12658 L->CompletedImplicitDefinition(Invoker); 12659 } 12660 } 12661 12662 12663 12664 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12665 SourceLocation CurrentLocation, 12666 CXXConversionDecl *Conv) 12667 { 12668 assert(!Conv->getParent()->isGenericLambda()); 12669 12670 SynthesizedFunctionScope Scope(*this, Conv); 12671 12672 // Copy-initialize the lambda object as needed to capture it. 12673 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12674 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12675 12676 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12677 Conv->getLocation(), 12678 Conv, DerefThis); 12679 12680 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12681 // behavior. Note that only the general conversion function does this 12682 // (since it's unusable otherwise); in the case where we inline the 12683 // block literal, it has block literal lifetime semantics. 12684 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12685 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12686 CK_CopyAndAutoreleaseBlockObject, 12687 BuildBlock.get(), nullptr, VK_RValue); 12688 12689 if (BuildBlock.isInvalid()) { 12690 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12691 Conv->setInvalidDecl(); 12692 return; 12693 } 12694 12695 // Create the return statement that returns the block from the conversion 12696 // function. 12697 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12698 if (Return.isInvalid()) { 12699 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12700 Conv->setInvalidDecl(); 12701 return; 12702 } 12703 12704 // Set the body of the conversion function. 12705 Stmt *ReturnS = Return.get(); 12706 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12707 Conv->getLocation())); 12708 Conv->markUsed(Context); 12709 12710 // We're done; notify the mutation listener, if any. 12711 if (ASTMutationListener *L = getASTMutationListener()) { 12712 L->CompletedImplicitDefinition(Conv); 12713 } 12714 } 12715 12716 /// Determine whether the given list arguments contains exactly one 12717 /// "real" (non-default) argument. 12718 static bool hasOneRealArgument(MultiExprArg Args) { 12719 switch (Args.size()) { 12720 case 0: 12721 return false; 12722 12723 default: 12724 if (!Args[1]->isDefaultArgument()) 12725 return false; 12726 12727 LLVM_FALLTHROUGH; 12728 case 1: 12729 return !Args[0]->isDefaultArgument(); 12730 } 12731 12732 return false; 12733 } 12734 12735 ExprResult 12736 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12737 NamedDecl *FoundDecl, 12738 CXXConstructorDecl *Constructor, 12739 MultiExprArg ExprArgs, 12740 bool HadMultipleCandidates, 12741 bool IsListInitialization, 12742 bool IsStdInitListInitialization, 12743 bool RequiresZeroInit, 12744 unsigned ConstructKind, 12745 SourceRange ParenRange) { 12746 bool Elidable = false; 12747 12748 // C++0x [class.copy]p34: 12749 // When certain criteria are met, an implementation is allowed to 12750 // omit the copy/move construction of a class object, even if the 12751 // copy/move constructor and/or destructor for the object have 12752 // side effects. [...] 12753 // - when a temporary class object that has not been bound to a 12754 // reference (12.2) would be copied/moved to a class object 12755 // with the same cv-unqualified type, the copy/move operation 12756 // can be omitted by constructing the temporary object 12757 // directly into the target of the omitted copy/move 12758 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12759 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12760 Expr *SubExpr = ExprArgs[0]; 12761 Elidable = SubExpr->isTemporaryObject( 12762 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12763 } 12764 12765 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12766 FoundDecl, Constructor, 12767 Elidable, ExprArgs, HadMultipleCandidates, 12768 IsListInitialization, 12769 IsStdInitListInitialization, RequiresZeroInit, 12770 ConstructKind, ParenRange); 12771 } 12772 12773 ExprResult 12774 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12775 NamedDecl *FoundDecl, 12776 CXXConstructorDecl *Constructor, 12777 bool Elidable, 12778 MultiExprArg ExprArgs, 12779 bool HadMultipleCandidates, 12780 bool IsListInitialization, 12781 bool IsStdInitListInitialization, 12782 bool RequiresZeroInit, 12783 unsigned ConstructKind, 12784 SourceRange ParenRange) { 12785 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12786 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12787 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12788 return ExprError(); 12789 } 12790 12791 return BuildCXXConstructExpr( 12792 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12793 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12794 RequiresZeroInit, ConstructKind, ParenRange); 12795 } 12796 12797 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12798 /// including handling of its default argument expressions. 12799 ExprResult 12800 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12801 CXXConstructorDecl *Constructor, 12802 bool Elidable, 12803 MultiExprArg ExprArgs, 12804 bool HadMultipleCandidates, 12805 bool IsListInitialization, 12806 bool IsStdInitListInitialization, 12807 bool RequiresZeroInit, 12808 unsigned ConstructKind, 12809 SourceRange ParenRange) { 12810 assert(declaresSameEntity( 12811 Constructor->getParent(), 12812 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12813 "given constructor for wrong type"); 12814 MarkFunctionReferenced(ConstructLoc, Constructor); 12815 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12816 return ExprError(); 12817 12818 return CXXConstructExpr::Create( 12819 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12820 ExprArgs, HadMultipleCandidates, IsListInitialization, 12821 IsStdInitListInitialization, RequiresZeroInit, 12822 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12823 ParenRange); 12824 } 12825 12826 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12827 assert(Field->hasInClassInitializer()); 12828 12829 // If we already have the in-class initializer nothing needs to be done. 12830 if (Field->getInClassInitializer()) 12831 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12832 12833 // If we might have already tried and failed to instantiate, don't try again. 12834 if (Field->isInvalidDecl()) 12835 return ExprError(); 12836 12837 // Maybe we haven't instantiated the in-class initializer. Go check the 12838 // pattern FieldDecl to see if it has one. 12839 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12840 12841 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12842 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12843 DeclContext::lookup_result Lookup = 12844 ClassPattern->lookup(Field->getDeclName()); 12845 12846 // Lookup can return at most two results: the pattern for the field, or the 12847 // injected class name of the parent record. No other member can have the 12848 // same name as the field. 12849 // In modules mode, lookup can return multiple results (coming from 12850 // different modules). 12851 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12852 "more than two lookup results for field name"); 12853 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12854 if (!Pattern) { 12855 assert(isa<CXXRecordDecl>(Lookup[0]) && 12856 "cannot have other non-field member with same name"); 12857 for (auto L : Lookup) 12858 if (isa<FieldDecl>(L)) { 12859 Pattern = cast<FieldDecl>(L); 12860 break; 12861 } 12862 assert(Pattern && "We must have set the Pattern!"); 12863 } 12864 12865 if (!Pattern->hasInClassInitializer() || 12866 InstantiateInClassInitializer(Loc, Field, Pattern, 12867 getTemplateInstantiationArgs(Field))) { 12868 // Don't diagnose this again. 12869 Field->setInvalidDecl(); 12870 return ExprError(); 12871 } 12872 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12873 } 12874 12875 // DR1351: 12876 // If the brace-or-equal-initializer of a non-static data member 12877 // invokes a defaulted default constructor of its class or of an 12878 // enclosing class in a potentially evaluated subexpression, the 12879 // program is ill-formed. 12880 // 12881 // This resolution is unworkable: the exception specification of the 12882 // default constructor can be needed in an unevaluated context, in 12883 // particular, in the operand of a noexcept-expression, and we can be 12884 // unable to compute an exception specification for an enclosed class. 12885 // 12886 // Any attempt to resolve the exception specification of a defaulted default 12887 // constructor before the initializer is lexically complete will ultimately 12888 // come here at which point we can diagnose it. 12889 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12890 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12891 << OutermostClass << Field; 12892 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12893 // Recover by marking the field invalid, unless we're in a SFINAE context. 12894 if (!isSFINAEContext()) 12895 Field->setInvalidDecl(); 12896 return ExprError(); 12897 } 12898 12899 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12900 if (VD->isInvalidDecl()) return; 12901 12902 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12903 if (ClassDecl->isInvalidDecl()) return; 12904 if (ClassDecl->hasIrrelevantDestructor()) return; 12905 if (ClassDecl->isDependentContext()) return; 12906 12907 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12908 MarkFunctionReferenced(VD->getLocation(), Destructor); 12909 CheckDestructorAccess(VD->getLocation(), Destructor, 12910 PDiag(diag::err_access_dtor_var) 12911 << VD->getDeclName() 12912 << VD->getType()); 12913 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12914 12915 if (Destructor->isTrivial()) return; 12916 if (!VD->hasGlobalStorage()) return; 12917 12918 // Emit warning for non-trivial dtor in global scope (a real global, 12919 // class-static, function-static). 12920 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12921 12922 // TODO: this should be re-enabled for static locals by !CXAAtExit 12923 if (!VD->isStaticLocal()) 12924 Diag(VD->getLocation(), diag::warn_global_destructor); 12925 } 12926 12927 /// Given a constructor and the set of arguments provided for the 12928 /// constructor, convert the arguments and add any required default arguments 12929 /// to form a proper call to this constructor. 12930 /// 12931 /// \returns true if an error occurred, false otherwise. 12932 bool 12933 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12934 MultiExprArg ArgsPtr, 12935 SourceLocation Loc, 12936 SmallVectorImpl<Expr*> &ConvertedArgs, 12937 bool AllowExplicit, 12938 bool IsListInitialization) { 12939 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12940 unsigned NumArgs = ArgsPtr.size(); 12941 Expr **Args = ArgsPtr.data(); 12942 12943 const FunctionProtoType *Proto 12944 = Constructor->getType()->getAs<FunctionProtoType>(); 12945 assert(Proto && "Constructor without a prototype?"); 12946 unsigned NumParams = Proto->getNumParams(); 12947 12948 // If too few arguments are available, we'll fill in the rest with defaults. 12949 if (NumArgs < NumParams) 12950 ConvertedArgs.reserve(NumParams); 12951 else 12952 ConvertedArgs.reserve(NumArgs); 12953 12954 VariadicCallType CallType = 12955 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12956 SmallVector<Expr *, 8> AllArgs; 12957 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12958 Proto, 0, 12959 llvm::makeArrayRef(Args, NumArgs), 12960 AllArgs, 12961 CallType, AllowExplicit, 12962 IsListInitialization); 12963 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12964 12965 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12966 12967 CheckConstructorCall(Constructor, 12968 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12969 Proto, Loc); 12970 12971 return Invalid; 12972 } 12973 12974 static inline bool 12975 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12976 const FunctionDecl *FnDecl) { 12977 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12978 if (isa<NamespaceDecl>(DC)) { 12979 return SemaRef.Diag(FnDecl->getLocation(), 12980 diag::err_operator_new_delete_declared_in_namespace) 12981 << FnDecl->getDeclName(); 12982 } 12983 12984 if (isa<TranslationUnitDecl>(DC) && 12985 FnDecl->getStorageClass() == SC_Static) { 12986 return SemaRef.Diag(FnDecl->getLocation(), 12987 diag::err_operator_new_delete_declared_static) 12988 << FnDecl->getDeclName(); 12989 } 12990 12991 return false; 12992 } 12993 12994 static QualType 12995 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 12996 QualType QTy = PtrTy->getPointeeType(); 12997 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 12998 return SemaRef.Context.getPointerType(QTy); 12999 } 13000 13001 static inline bool 13002 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13003 CanQualType ExpectedResultType, 13004 CanQualType ExpectedFirstParamType, 13005 unsigned DependentParamTypeDiag, 13006 unsigned InvalidParamTypeDiag) { 13007 QualType ResultType = 13008 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13009 13010 // Check that the result type is not dependent. 13011 if (ResultType->isDependentType()) 13012 return SemaRef.Diag(FnDecl->getLocation(), 13013 diag::err_operator_new_delete_dependent_result_type) 13014 << FnDecl->getDeclName() << ExpectedResultType; 13015 13016 // OpenCL C++: the operator is valid on any address space. 13017 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13018 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13019 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13020 } 13021 } 13022 13023 // Check that the result type is what we expect. 13024 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13025 return SemaRef.Diag(FnDecl->getLocation(), 13026 diag::err_operator_new_delete_invalid_result_type) 13027 << FnDecl->getDeclName() << ExpectedResultType; 13028 13029 // A function template must have at least 2 parameters. 13030 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13031 return SemaRef.Diag(FnDecl->getLocation(), 13032 diag::err_operator_new_delete_template_too_few_parameters) 13033 << FnDecl->getDeclName(); 13034 13035 // The function decl must have at least 1 parameter. 13036 if (FnDecl->getNumParams() == 0) 13037 return SemaRef.Diag(FnDecl->getLocation(), 13038 diag::err_operator_new_delete_too_few_parameters) 13039 << FnDecl->getDeclName(); 13040 13041 // Check the first parameter type is not dependent. 13042 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13043 if (FirstParamType->isDependentType()) 13044 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13045 << FnDecl->getDeclName() << ExpectedFirstParamType; 13046 13047 // Check that the first parameter type is what we expect. 13048 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13049 // OpenCL C++: the operator is valid on any address space. 13050 if (auto *PtrTy = 13051 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13052 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13053 } 13054 } 13055 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13056 ExpectedFirstParamType) 13057 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13058 << FnDecl->getDeclName() << ExpectedFirstParamType; 13059 13060 return false; 13061 } 13062 13063 static bool 13064 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13065 // C++ [basic.stc.dynamic.allocation]p1: 13066 // A program is ill-formed if an allocation function is declared in a 13067 // namespace scope other than global scope or declared static in global 13068 // scope. 13069 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13070 return true; 13071 13072 CanQualType SizeTy = 13073 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13074 13075 // C++ [basic.stc.dynamic.allocation]p1: 13076 // The return type shall be void*. The first parameter shall have type 13077 // std::size_t. 13078 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13079 SizeTy, 13080 diag::err_operator_new_dependent_param_type, 13081 diag::err_operator_new_param_type)) 13082 return true; 13083 13084 // C++ [basic.stc.dynamic.allocation]p1: 13085 // The first parameter shall not have an associated default argument. 13086 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13087 return SemaRef.Diag(FnDecl->getLocation(), 13088 diag::err_operator_new_default_arg) 13089 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13090 13091 return false; 13092 } 13093 13094 static bool 13095 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13096 // C++ [basic.stc.dynamic.deallocation]p1: 13097 // A program is ill-formed if deallocation functions are declared in a 13098 // namespace scope other than global scope or declared static in global 13099 // scope. 13100 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13101 return true; 13102 13103 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13104 13105 // C++ P0722: 13106 // Within a class C, the first parameter of a destroying operator delete 13107 // shall be of type C *. The first parameter of any other deallocation 13108 // function shall be of type void *. 13109 CanQualType ExpectedFirstParamType = 13110 MD && MD->isDestroyingOperatorDelete() 13111 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13112 SemaRef.Context.getRecordType(MD->getParent()))) 13113 : SemaRef.Context.VoidPtrTy; 13114 13115 // C++ [basic.stc.dynamic.deallocation]p2: 13116 // Each deallocation function shall return void 13117 if (CheckOperatorNewDeleteTypes( 13118 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13119 diag::err_operator_delete_dependent_param_type, 13120 diag::err_operator_delete_param_type)) 13121 return true; 13122 13123 // C++ P0722: 13124 // A destroying operator delete shall be a usual deallocation function. 13125 if (MD && !MD->getParent()->isDependentContext() && 13126 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 13127 SemaRef.Diag(MD->getLocation(), 13128 diag::err_destroying_operator_delete_not_usual); 13129 return true; 13130 } 13131 13132 return false; 13133 } 13134 13135 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13136 /// of this overloaded operator is well-formed. If so, returns false; 13137 /// otherwise, emits appropriate diagnostics and returns true. 13138 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13139 assert(FnDecl && FnDecl->isOverloadedOperator() && 13140 "Expected an overloaded operator declaration"); 13141 13142 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13143 13144 // C++ [over.oper]p5: 13145 // The allocation and deallocation functions, operator new, 13146 // operator new[], operator delete and operator delete[], are 13147 // described completely in 3.7.3. The attributes and restrictions 13148 // found in the rest of this subclause do not apply to them unless 13149 // explicitly stated in 3.7.3. 13150 if (Op == OO_Delete || Op == OO_Array_Delete) 13151 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13152 13153 if (Op == OO_New || Op == OO_Array_New) 13154 return CheckOperatorNewDeclaration(*this, FnDecl); 13155 13156 // C++ [over.oper]p6: 13157 // An operator function shall either be a non-static member 13158 // function or be a non-member function and have at least one 13159 // parameter whose type is a class, a reference to a class, an 13160 // enumeration, or a reference to an enumeration. 13161 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13162 if (MethodDecl->isStatic()) 13163 return Diag(FnDecl->getLocation(), 13164 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13165 } else { 13166 bool ClassOrEnumParam = false; 13167 for (auto Param : FnDecl->parameters()) { 13168 QualType ParamType = Param->getType().getNonReferenceType(); 13169 if (ParamType->isDependentType() || ParamType->isRecordType() || 13170 ParamType->isEnumeralType()) { 13171 ClassOrEnumParam = true; 13172 break; 13173 } 13174 } 13175 13176 if (!ClassOrEnumParam) 13177 return Diag(FnDecl->getLocation(), 13178 diag::err_operator_overload_needs_class_or_enum) 13179 << FnDecl->getDeclName(); 13180 } 13181 13182 // C++ [over.oper]p8: 13183 // An operator function cannot have default arguments (8.3.6), 13184 // except where explicitly stated below. 13185 // 13186 // Only the function-call operator allows default arguments 13187 // (C++ [over.call]p1). 13188 if (Op != OO_Call) { 13189 for (auto Param : FnDecl->parameters()) { 13190 if (Param->hasDefaultArg()) 13191 return Diag(Param->getLocation(), 13192 diag::err_operator_overload_default_arg) 13193 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13194 } 13195 } 13196 13197 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13198 { false, false, false } 13199 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13200 , { Unary, Binary, MemberOnly } 13201 #include "clang/Basic/OperatorKinds.def" 13202 }; 13203 13204 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13205 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13206 bool MustBeMemberOperator = OperatorUses[Op][2]; 13207 13208 // C++ [over.oper]p8: 13209 // [...] Operator functions cannot have more or fewer parameters 13210 // than the number required for the corresponding operator, as 13211 // described in the rest of this subclause. 13212 unsigned NumParams = FnDecl->getNumParams() 13213 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13214 if (Op != OO_Call && 13215 ((NumParams == 1 && !CanBeUnaryOperator) || 13216 (NumParams == 2 && !CanBeBinaryOperator) || 13217 (NumParams < 1) || (NumParams > 2))) { 13218 // We have the wrong number of parameters. 13219 unsigned ErrorKind; 13220 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13221 ErrorKind = 2; // 2 -> unary or binary. 13222 } else if (CanBeUnaryOperator) { 13223 ErrorKind = 0; // 0 -> unary 13224 } else { 13225 assert(CanBeBinaryOperator && 13226 "All non-call overloaded operators are unary or binary!"); 13227 ErrorKind = 1; // 1 -> binary 13228 } 13229 13230 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13231 << FnDecl->getDeclName() << NumParams << ErrorKind; 13232 } 13233 13234 // Overloaded operators other than operator() cannot be variadic. 13235 if (Op != OO_Call && 13236 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13237 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13238 << FnDecl->getDeclName(); 13239 } 13240 13241 // Some operators must be non-static member functions. 13242 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13243 return Diag(FnDecl->getLocation(), 13244 diag::err_operator_overload_must_be_member) 13245 << FnDecl->getDeclName(); 13246 } 13247 13248 // C++ [over.inc]p1: 13249 // The user-defined function called operator++ implements the 13250 // prefix and postfix ++ operator. If this function is a member 13251 // function with no parameters, or a non-member function with one 13252 // parameter of class or enumeration type, it defines the prefix 13253 // increment operator ++ for objects of that type. If the function 13254 // is a member function with one parameter (which shall be of type 13255 // int) or a non-member function with two parameters (the second 13256 // of which shall be of type int), it defines the postfix 13257 // increment operator ++ for objects of that type. 13258 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13259 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13260 QualType ParamType = LastParam->getType(); 13261 13262 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13263 !ParamType->isDependentType()) 13264 return Diag(LastParam->getLocation(), 13265 diag::err_operator_overload_post_incdec_must_be_int) 13266 << LastParam->getType() << (Op == OO_MinusMinus); 13267 } 13268 13269 return false; 13270 } 13271 13272 static bool 13273 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13274 FunctionTemplateDecl *TpDecl) { 13275 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13276 13277 // Must have one or two template parameters. 13278 if (TemplateParams->size() == 1) { 13279 NonTypeTemplateParmDecl *PmDecl = 13280 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13281 13282 // The template parameter must be a char parameter pack. 13283 if (PmDecl && PmDecl->isTemplateParameterPack() && 13284 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13285 return false; 13286 13287 } else if (TemplateParams->size() == 2) { 13288 TemplateTypeParmDecl *PmType = 13289 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13290 NonTypeTemplateParmDecl *PmArgs = 13291 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13292 13293 // The second template parameter must be a parameter pack with the 13294 // first template parameter as its type. 13295 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13296 PmArgs->isTemplateParameterPack()) { 13297 const TemplateTypeParmType *TArgs = 13298 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13299 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13300 TArgs->getIndex() == PmType->getIndex()) { 13301 if (!SemaRef.inTemplateInstantiation()) 13302 SemaRef.Diag(TpDecl->getLocation(), 13303 diag::ext_string_literal_operator_template); 13304 return false; 13305 } 13306 } 13307 } 13308 13309 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13310 diag::err_literal_operator_template) 13311 << TpDecl->getTemplateParameters()->getSourceRange(); 13312 return true; 13313 } 13314 13315 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13316 /// of this literal operator function is well-formed. If so, returns 13317 /// false; otherwise, emits appropriate diagnostics and returns true. 13318 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13319 if (isa<CXXMethodDecl>(FnDecl)) { 13320 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13321 << FnDecl->getDeclName(); 13322 return true; 13323 } 13324 13325 if (FnDecl->isExternC()) { 13326 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13327 if (const LinkageSpecDecl *LSD = 13328 FnDecl->getDeclContext()->getExternCContext()) 13329 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13330 return true; 13331 } 13332 13333 // This might be the definition of a literal operator template. 13334 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13335 13336 // This might be a specialization of a literal operator template. 13337 if (!TpDecl) 13338 TpDecl = FnDecl->getPrimaryTemplate(); 13339 13340 // template <char...> type operator "" name() and 13341 // template <class T, T...> type operator "" name() are the only valid 13342 // template signatures, and the only valid signatures with no parameters. 13343 if (TpDecl) { 13344 if (FnDecl->param_size() != 0) { 13345 Diag(FnDecl->getLocation(), 13346 diag::err_literal_operator_template_with_params); 13347 return true; 13348 } 13349 13350 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13351 return true; 13352 13353 } else if (FnDecl->param_size() == 1) { 13354 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13355 13356 QualType ParamType = Param->getType().getUnqualifiedType(); 13357 13358 // Only unsigned long long int, long double, any character type, and const 13359 // char * are allowed as the only parameters. 13360 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13361 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13362 Context.hasSameType(ParamType, Context.CharTy) || 13363 Context.hasSameType(ParamType, Context.WideCharTy) || 13364 Context.hasSameType(ParamType, Context.Char8Ty) || 13365 Context.hasSameType(ParamType, Context.Char16Ty) || 13366 Context.hasSameType(ParamType, Context.Char32Ty)) { 13367 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13368 QualType InnerType = Ptr->getPointeeType(); 13369 13370 // Pointer parameter must be a const char *. 13371 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13372 Context.CharTy) && 13373 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13374 Diag(Param->getSourceRange().getBegin(), 13375 diag::err_literal_operator_param) 13376 << ParamType << "'const char *'" << Param->getSourceRange(); 13377 return true; 13378 } 13379 13380 } else if (ParamType->isRealFloatingType()) { 13381 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13382 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13383 return true; 13384 13385 } else if (ParamType->isIntegerType()) { 13386 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13387 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13388 return true; 13389 13390 } else { 13391 Diag(Param->getSourceRange().getBegin(), 13392 diag::err_literal_operator_invalid_param) 13393 << ParamType << Param->getSourceRange(); 13394 return true; 13395 } 13396 13397 } else if (FnDecl->param_size() == 2) { 13398 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13399 13400 // First, verify that the first parameter is correct. 13401 13402 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13403 13404 // Two parameter function must have a pointer to const as a 13405 // first parameter; let's strip those qualifiers. 13406 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13407 13408 if (!PT) { 13409 Diag((*Param)->getSourceRange().getBegin(), 13410 diag::err_literal_operator_param) 13411 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13412 return true; 13413 } 13414 13415 QualType PointeeType = PT->getPointeeType(); 13416 // First parameter must be const 13417 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13418 Diag((*Param)->getSourceRange().getBegin(), 13419 diag::err_literal_operator_param) 13420 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13421 return true; 13422 } 13423 13424 QualType InnerType = PointeeType.getUnqualifiedType(); 13425 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13426 // const char32_t* are allowed as the first parameter to a two-parameter 13427 // function 13428 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13429 Context.hasSameType(InnerType, Context.WideCharTy) || 13430 Context.hasSameType(InnerType, Context.Char8Ty) || 13431 Context.hasSameType(InnerType, Context.Char16Ty) || 13432 Context.hasSameType(InnerType, Context.Char32Ty))) { 13433 Diag((*Param)->getSourceRange().getBegin(), 13434 diag::err_literal_operator_param) 13435 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13436 return true; 13437 } 13438 13439 // Move on to the second and final parameter. 13440 ++Param; 13441 13442 // The second parameter must be a std::size_t. 13443 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13444 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13445 Diag((*Param)->getSourceRange().getBegin(), 13446 diag::err_literal_operator_param) 13447 << SecondParamType << Context.getSizeType() 13448 << (*Param)->getSourceRange(); 13449 return true; 13450 } 13451 } else { 13452 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13453 return true; 13454 } 13455 13456 // Parameters are good. 13457 13458 // A parameter-declaration-clause containing a default argument is not 13459 // equivalent to any of the permitted forms. 13460 for (auto Param : FnDecl->parameters()) { 13461 if (Param->hasDefaultArg()) { 13462 Diag(Param->getDefaultArgRange().getBegin(), 13463 diag::err_literal_operator_default_argument) 13464 << Param->getDefaultArgRange(); 13465 break; 13466 } 13467 } 13468 13469 StringRef LiteralName 13470 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13471 if (LiteralName[0] != '_' && 13472 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13473 // C++11 [usrlit.suffix]p1: 13474 // Literal suffix identifiers that do not start with an underscore 13475 // are reserved for future standardization. 13476 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13477 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13478 } 13479 13480 return false; 13481 } 13482 13483 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13484 /// linkage specification, including the language and (if present) 13485 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13486 /// language string literal. LBraceLoc, if valid, provides the location of 13487 /// the '{' brace. Otherwise, this linkage specification does not 13488 /// have any braces. 13489 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13490 Expr *LangStr, 13491 SourceLocation LBraceLoc) { 13492 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13493 if (!Lit->isAscii()) { 13494 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13495 << LangStr->getSourceRange(); 13496 return nullptr; 13497 } 13498 13499 StringRef Lang = Lit->getString(); 13500 LinkageSpecDecl::LanguageIDs Language; 13501 if (Lang == "C") 13502 Language = LinkageSpecDecl::lang_c; 13503 else if (Lang == "C++") 13504 Language = LinkageSpecDecl::lang_cxx; 13505 else { 13506 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13507 << LangStr->getSourceRange(); 13508 return nullptr; 13509 } 13510 13511 // FIXME: Add all the various semantics of linkage specifications 13512 13513 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13514 LangStr->getExprLoc(), Language, 13515 LBraceLoc.isValid()); 13516 CurContext->addDecl(D); 13517 PushDeclContext(S, D); 13518 return D; 13519 } 13520 13521 /// ActOnFinishLinkageSpecification - Complete the definition of 13522 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13523 /// valid, it's the position of the closing '}' brace in a linkage 13524 /// specification that uses braces. 13525 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13526 Decl *LinkageSpec, 13527 SourceLocation RBraceLoc) { 13528 if (RBraceLoc.isValid()) { 13529 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13530 LSDecl->setRBraceLoc(RBraceLoc); 13531 } 13532 PopDeclContext(); 13533 return LinkageSpec; 13534 } 13535 13536 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13537 const ParsedAttributesView &AttrList, 13538 SourceLocation SemiLoc) { 13539 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13540 // Attribute declarations appertain to empty declaration so we handle 13541 // them here. 13542 ProcessDeclAttributeList(S, ED, AttrList); 13543 13544 CurContext->addDecl(ED); 13545 return ED; 13546 } 13547 13548 /// Perform semantic analysis for the variable declaration that 13549 /// occurs within a C++ catch clause, returning the newly-created 13550 /// variable. 13551 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13552 TypeSourceInfo *TInfo, 13553 SourceLocation StartLoc, 13554 SourceLocation Loc, 13555 IdentifierInfo *Name) { 13556 bool Invalid = false; 13557 QualType ExDeclType = TInfo->getType(); 13558 13559 // Arrays and functions decay. 13560 if (ExDeclType->isArrayType()) 13561 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13562 else if (ExDeclType->isFunctionType()) 13563 ExDeclType = Context.getPointerType(ExDeclType); 13564 13565 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13566 // The exception-declaration shall not denote a pointer or reference to an 13567 // incomplete type, other than [cv] void*. 13568 // N2844 forbids rvalue references. 13569 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13570 Diag(Loc, diag::err_catch_rvalue_ref); 13571 Invalid = true; 13572 } 13573 13574 if (ExDeclType->isVariablyModifiedType()) { 13575 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13576 Invalid = true; 13577 } 13578 13579 QualType BaseType = ExDeclType; 13580 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13581 unsigned DK = diag::err_catch_incomplete; 13582 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13583 BaseType = Ptr->getPointeeType(); 13584 Mode = 1; 13585 DK = diag::err_catch_incomplete_ptr; 13586 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13587 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13588 BaseType = Ref->getPointeeType(); 13589 Mode = 2; 13590 DK = diag::err_catch_incomplete_ref; 13591 } 13592 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13593 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13594 Invalid = true; 13595 13596 if (!Invalid && !ExDeclType->isDependentType() && 13597 RequireNonAbstractType(Loc, ExDeclType, 13598 diag::err_abstract_type_in_decl, 13599 AbstractVariableType)) 13600 Invalid = true; 13601 13602 // Only the non-fragile NeXT runtime currently supports C++ catches 13603 // of ObjC types, and no runtime supports catching ObjC types by value. 13604 if (!Invalid && getLangOpts().ObjC1) { 13605 QualType T = ExDeclType; 13606 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13607 T = RT->getPointeeType(); 13608 13609 if (T->isObjCObjectType()) { 13610 Diag(Loc, diag::err_objc_object_catch); 13611 Invalid = true; 13612 } else if (T->isObjCObjectPointerType()) { 13613 // FIXME: should this be a test for macosx-fragile specifically? 13614 if (getLangOpts().ObjCRuntime.isFragile()) 13615 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13616 } 13617 } 13618 13619 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13620 ExDeclType, TInfo, SC_None); 13621 ExDecl->setExceptionVariable(true); 13622 13623 // In ARC, infer 'retaining' for variables of retainable type. 13624 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13625 Invalid = true; 13626 13627 if (!Invalid && !ExDeclType->isDependentType()) { 13628 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13629 // Insulate this from anything else we might currently be parsing. 13630 EnterExpressionEvaluationContext scope( 13631 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13632 13633 // C++ [except.handle]p16: 13634 // The object declared in an exception-declaration or, if the 13635 // exception-declaration does not specify a name, a temporary (12.2) is 13636 // copy-initialized (8.5) from the exception object. [...] 13637 // The object is destroyed when the handler exits, after the destruction 13638 // of any automatic objects initialized within the handler. 13639 // 13640 // We just pretend to initialize the object with itself, then make sure 13641 // it can be destroyed later. 13642 QualType initType = Context.getExceptionObjectType(ExDeclType); 13643 13644 InitializedEntity entity = 13645 InitializedEntity::InitializeVariable(ExDecl); 13646 InitializationKind initKind = 13647 InitializationKind::CreateCopy(Loc, SourceLocation()); 13648 13649 Expr *opaqueValue = 13650 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13651 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13652 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13653 if (result.isInvalid()) 13654 Invalid = true; 13655 else { 13656 // If the constructor used was non-trivial, set this as the 13657 // "initializer". 13658 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13659 if (!construct->getConstructor()->isTrivial()) { 13660 Expr *init = MaybeCreateExprWithCleanups(construct); 13661 ExDecl->setInit(init); 13662 } 13663 13664 // And make sure it's destructable. 13665 FinalizeVarWithDestructor(ExDecl, recordType); 13666 } 13667 } 13668 } 13669 13670 if (Invalid) 13671 ExDecl->setInvalidDecl(); 13672 13673 return ExDecl; 13674 } 13675 13676 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13677 /// handler. 13678 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13680 bool Invalid = D.isInvalidType(); 13681 13682 // Check for unexpanded parameter packs. 13683 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13684 UPPC_ExceptionType)) { 13685 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13686 D.getIdentifierLoc()); 13687 Invalid = true; 13688 } 13689 13690 IdentifierInfo *II = D.getIdentifier(); 13691 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13692 LookupOrdinaryName, 13693 ForVisibleRedeclaration)) { 13694 // The scope should be freshly made just for us. There is just no way 13695 // it contains any previous declaration, except for function parameters in 13696 // a function-try-block's catch statement. 13697 assert(!S->isDeclScope(PrevDecl)); 13698 if (isDeclInScope(PrevDecl, CurContext, S)) { 13699 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13700 << D.getIdentifier(); 13701 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13702 Invalid = true; 13703 } else if (PrevDecl->isTemplateParameter()) 13704 // Maybe we will complain about the shadowed template parameter. 13705 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13706 } 13707 13708 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13709 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13710 << D.getCXXScopeSpec().getRange(); 13711 Invalid = true; 13712 } 13713 13714 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13715 D.getLocStart(), 13716 D.getIdentifierLoc(), 13717 D.getIdentifier()); 13718 if (Invalid) 13719 ExDecl->setInvalidDecl(); 13720 13721 // Add the exception declaration into this scope. 13722 if (II) 13723 PushOnScopeChains(ExDecl, S); 13724 else 13725 CurContext->addDecl(ExDecl); 13726 13727 ProcessDeclAttributes(S, ExDecl, D); 13728 return ExDecl; 13729 } 13730 13731 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13732 Expr *AssertExpr, 13733 Expr *AssertMessageExpr, 13734 SourceLocation RParenLoc) { 13735 StringLiteral *AssertMessage = 13736 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13737 13738 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13739 return nullptr; 13740 13741 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13742 AssertMessage, RParenLoc, false); 13743 } 13744 13745 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13746 Expr *AssertExpr, 13747 StringLiteral *AssertMessage, 13748 SourceLocation RParenLoc, 13749 bool Failed) { 13750 assert(AssertExpr != nullptr && "Expected non-null condition"); 13751 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13752 !Failed) { 13753 // In a static_assert-declaration, the constant-expression shall be a 13754 // constant expression that can be contextually converted to bool. 13755 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13756 if (Converted.isInvalid()) 13757 Failed = true; 13758 13759 llvm::APSInt Cond; 13760 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13761 diag::err_static_assert_expression_is_not_constant, 13762 /*AllowFold=*/false).isInvalid()) 13763 Failed = true; 13764 13765 if (!Failed && !Cond) { 13766 SmallString<256> MsgBuffer; 13767 llvm::raw_svector_ostream Msg(MsgBuffer); 13768 if (AssertMessage) 13769 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13770 13771 Expr *InnerCond = nullptr; 13772 std::string InnerCondDescription; 13773 std::tie(InnerCond, InnerCondDescription) = 13774 findFailedBooleanCondition(Converted.get(), 13775 /*AllowTopLevelCond=*/false); 13776 if (InnerCond) { 13777 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13778 << InnerCondDescription << !AssertMessage 13779 << Msg.str() << InnerCond->getSourceRange(); 13780 } else { 13781 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13782 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13783 } 13784 Failed = true; 13785 } 13786 } 13787 13788 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13789 /*DiscardedValue*/false, 13790 /*IsConstexpr*/true); 13791 if (FullAssertExpr.isInvalid()) 13792 Failed = true; 13793 else 13794 AssertExpr = FullAssertExpr.get(); 13795 13796 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13797 AssertExpr, AssertMessage, RParenLoc, 13798 Failed); 13799 13800 CurContext->addDecl(Decl); 13801 return Decl; 13802 } 13803 13804 /// Perform semantic analysis of the given friend type declaration. 13805 /// 13806 /// \returns A friend declaration that. 13807 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13808 SourceLocation FriendLoc, 13809 TypeSourceInfo *TSInfo) { 13810 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13811 13812 QualType T = TSInfo->getType(); 13813 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13814 13815 // C++03 [class.friend]p2: 13816 // An elaborated-type-specifier shall be used in a friend declaration 13817 // for a class.* 13818 // 13819 // * The class-key of the elaborated-type-specifier is required. 13820 if (!CodeSynthesisContexts.empty()) { 13821 // Do not complain about the form of friend template types during any kind 13822 // of code synthesis. For template instantiation, we will have complained 13823 // when the template was defined. 13824 } else { 13825 if (!T->isElaboratedTypeSpecifier()) { 13826 // If we evaluated the type to a record type, suggest putting 13827 // a tag in front. 13828 if (const RecordType *RT = T->getAs<RecordType>()) { 13829 RecordDecl *RD = RT->getDecl(); 13830 13831 SmallString<16> InsertionText(" "); 13832 InsertionText += RD->getKindName(); 13833 13834 Diag(TypeRange.getBegin(), 13835 getLangOpts().CPlusPlus11 ? 13836 diag::warn_cxx98_compat_unelaborated_friend_type : 13837 diag::ext_unelaborated_friend_type) 13838 << (unsigned) RD->getTagKind() 13839 << T 13840 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13841 InsertionText); 13842 } else { 13843 Diag(FriendLoc, 13844 getLangOpts().CPlusPlus11 ? 13845 diag::warn_cxx98_compat_nonclass_type_friend : 13846 diag::ext_nonclass_type_friend) 13847 << T 13848 << TypeRange; 13849 } 13850 } else if (T->getAs<EnumType>()) { 13851 Diag(FriendLoc, 13852 getLangOpts().CPlusPlus11 ? 13853 diag::warn_cxx98_compat_enum_friend : 13854 diag::ext_enum_friend) 13855 << T 13856 << TypeRange; 13857 } 13858 13859 // C++11 [class.friend]p3: 13860 // A friend declaration that does not declare a function shall have one 13861 // of the following forms: 13862 // friend elaborated-type-specifier ; 13863 // friend simple-type-specifier ; 13864 // friend typename-specifier ; 13865 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13866 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13867 } 13868 13869 // If the type specifier in a friend declaration designates a (possibly 13870 // cv-qualified) class type, that class is declared as a friend; otherwise, 13871 // the friend declaration is ignored. 13872 return FriendDecl::Create(Context, CurContext, 13873 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13874 FriendLoc); 13875 } 13876 13877 /// Handle a friend tag declaration where the scope specifier was 13878 /// templated. 13879 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13880 unsigned TagSpec, SourceLocation TagLoc, 13881 CXXScopeSpec &SS, IdentifierInfo *Name, 13882 SourceLocation NameLoc, 13883 const ParsedAttributesView &Attr, 13884 MultiTemplateParamsArg TempParamLists) { 13885 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13886 13887 bool IsMemberSpecialization = false; 13888 bool Invalid = false; 13889 13890 if (TemplateParameterList *TemplateParams = 13891 MatchTemplateParametersToScopeSpecifier( 13892 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13893 IsMemberSpecialization, Invalid)) { 13894 if (TemplateParams->size() > 0) { 13895 // This is a declaration of a class template. 13896 if (Invalid) 13897 return nullptr; 13898 13899 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13900 NameLoc, Attr, TemplateParams, AS_public, 13901 /*ModulePrivateLoc=*/SourceLocation(), 13902 FriendLoc, TempParamLists.size() - 1, 13903 TempParamLists.data()).get(); 13904 } else { 13905 // The "template<>" header is extraneous. 13906 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13907 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13908 IsMemberSpecialization = true; 13909 } 13910 } 13911 13912 if (Invalid) return nullptr; 13913 13914 bool isAllExplicitSpecializations = true; 13915 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13916 if (TempParamLists[I]->size()) { 13917 isAllExplicitSpecializations = false; 13918 break; 13919 } 13920 } 13921 13922 // FIXME: don't ignore attributes. 13923 13924 // If it's explicit specializations all the way down, just forget 13925 // about the template header and build an appropriate non-templated 13926 // friend. TODO: for source fidelity, remember the headers. 13927 if (isAllExplicitSpecializations) { 13928 if (SS.isEmpty()) { 13929 bool Owned = false; 13930 bool IsDependent = false; 13931 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13932 Attr, AS_public, 13933 /*ModulePrivateLoc=*/SourceLocation(), 13934 MultiTemplateParamsArg(), Owned, IsDependent, 13935 /*ScopedEnumKWLoc=*/SourceLocation(), 13936 /*ScopedEnumUsesClassTag=*/false, 13937 /*UnderlyingType=*/TypeResult(), 13938 /*IsTypeSpecifier=*/false, 13939 /*IsTemplateParamOrArg=*/false); 13940 } 13941 13942 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13943 ElaboratedTypeKeyword Keyword 13944 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13945 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13946 *Name, NameLoc); 13947 if (T.isNull()) 13948 return nullptr; 13949 13950 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13951 if (isa<DependentNameType>(T)) { 13952 DependentNameTypeLoc TL = 13953 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13954 TL.setElaboratedKeywordLoc(TagLoc); 13955 TL.setQualifierLoc(QualifierLoc); 13956 TL.setNameLoc(NameLoc); 13957 } else { 13958 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13959 TL.setElaboratedKeywordLoc(TagLoc); 13960 TL.setQualifierLoc(QualifierLoc); 13961 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13962 } 13963 13964 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13965 TSI, FriendLoc, TempParamLists); 13966 Friend->setAccess(AS_public); 13967 CurContext->addDecl(Friend); 13968 return Friend; 13969 } 13970 13971 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13972 13973 13974 13975 // Handle the case of a templated-scope friend class. e.g. 13976 // template <class T> class A<T>::B; 13977 // FIXME: we don't support these right now. 13978 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13979 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13980 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13981 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13982 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13983 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13984 TL.setElaboratedKeywordLoc(TagLoc); 13985 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13986 TL.setNameLoc(NameLoc); 13987 13988 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13989 TSI, FriendLoc, TempParamLists); 13990 Friend->setAccess(AS_public); 13991 Friend->setUnsupportedFriend(true); 13992 CurContext->addDecl(Friend); 13993 return Friend; 13994 } 13995 13996 /// Handle a friend type declaration. This works in tandem with 13997 /// ActOnTag. 13998 /// 13999 /// Notes on friend class templates: 14000 /// 14001 /// We generally treat friend class declarations as if they were 14002 /// declaring a class. So, for example, the elaborated type specifier 14003 /// in a friend declaration is required to obey the restrictions of a 14004 /// class-head (i.e. no typedefs in the scope chain), template 14005 /// parameters are required to match up with simple template-ids, &c. 14006 /// However, unlike when declaring a template specialization, it's 14007 /// okay to refer to a template specialization without an empty 14008 /// template parameter declaration, e.g. 14009 /// friend class A<T>::B<unsigned>; 14010 /// We permit this as a special case; if there are any template 14011 /// parameters present at all, require proper matching, i.e. 14012 /// template <> template \<class T> friend class A<int>::B; 14013 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14014 MultiTemplateParamsArg TempParams) { 14015 SourceLocation Loc = DS.getLocStart(); 14016 14017 assert(DS.isFriendSpecified()); 14018 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14019 14020 // Try to convert the decl specifier to a type. This works for 14021 // friend templates because ActOnTag never produces a ClassTemplateDecl 14022 // for a TUK_Friend. 14023 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14024 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14025 QualType T = TSI->getType(); 14026 if (TheDeclarator.isInvalidType()) 14027 return nullptr; 14028 14029 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14030 return nullptr; 14031 14032 // This is definitely an error in C++98. It's probably meant to 14033 // be forbidden in C++0x, too, but the specification is just 14034 // poorly written. 14035 // 14036 // The problem is with declarations like the following: 14037 // template <T> friend A<T>::foo; 14038 // where deciding whether a class C is a friend or not now hinges 14039 // on whether there exists an instantiation of A that causes 14040 // 'foo' to equal C. There are restrictions on class-heads 14041 // (which we declare (by fiat) elaborated friend declarations to 14042 // be) that makes this tractable. 14043 // 14044 // FIXME: handle "template <> friend class A<T>;", which 14045 // is possibly well-formed? Who even knows? 14046 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14047 Diag(Loc, diag::err_tagless_friend_type_template) 14048 << DS.getSourceRange(); 14049 return nullptr; 14050 } 14051 14052 // C++98 [class.friend]p1: A friend of a class is a function 14053 // or class that is not a member of the class . . . 14054 // This is fixed in DR77, which just barely didn't make the C++03 14055 // deadline. It's also a very silly restriction that seriously 14056 // affects inner classes and which nobody else seems to implement; 14057 // thus we never diagnose it, not even in -pedantic. 14058 // 14059 // But note that we could warn about it: it's always useless to 14060 // friend one of your own members (it's not, however, worthless to 14061 // friend a member of an arbitrary specialization of your template). 14062 14063 Decl *D; 14064 if (!TempParams.empty()) 14065 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14066 TempParams, 14067 TSI, 14068 DS.getFriendSpecLoc()); 14069 else 14070 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14071 14072 if (!D) 14073 return nullptr; 14074 14075 D->setAccess(AS_public); 14076 CurContext->addDecl(D); 14077 14078 return D; 14079 } 14080 14081 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14082 MultiTemplateParamsArg TemplateParams) { 14083 const DeclSpec &DS = D.getDeclSpec(); 14084 14085 assert(DS.isFriendSpecified()); 14086 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14087 14088 SourceLocation Loc = D.getIdentifierLoc(); 14089 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14090 14091 // C++ [class.friend]p1 14092 // A friend of a class is a function or class.... 14093 // Note that this sees through typedefs, which is intended. 14094 // It *doesn't* see through dependent types, which is correct 14095 // according to [temp.arg.type]p3: 14096 // If a declaration acquires a function type through a 14097 // type dependent on a template-parameter and this causes 14098 // a declaration that does not use the syntactic form of a 14099 // function declarator to have a function type, the program 14100 // is ill-formed. 14101 if (!TInfo->getType()->isFunctionType()) { 14102 Diag(Loc, diag::err_unexpected_friend); 14103 14104 // It might be worthwhile to try to recover by creating an 14105 // appropriate declaration. 14106 return nullptr; 14107 } 14108 14109 // C++ [namespace.memdef]p3 14110 // - If a friend declaration in a non-local class first declares a 14111 // class or function, the friend class or function is a member 14112 // of the innermost enclosing namespace. 14113 // - The name of the friend is not found by simple name lookup 14114 // until a matching declaration is provided in that namespace 14115 // scope (either before or after the class declaration granting 14116 // friendship). 14117 // - If a friend function is called, its name may be found by the 14118 // name lookup that considers functions from namespaces and 14119 // classes associated with the types of the function arguments. 14120 // - When looking for a prior declaration of a class or a function 14121 // declared as a friend, scopes outside the innermost enclosing 14122 // namespace scope are not considered. 14123 14124 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14125 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14126 DeclarationName Name = NameInfo.getName(); 14127 assert(Name); 14128 14129 // Check for unexpanded parameter packs. 14130 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14131 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14132 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14133 return nullptr; 14134 14135 // The context we found the declaration in, or in which we should 14136 // create the declaration. 14137 DeclContext *DC; 14138 Scope *DCScope = S; 14139 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14140 ForExternalRedeclaration); 14141 14142 // There are five cases here. 14143 // - There's no scope specifier and we're in a local class. Only look 14144 // for functions declared in the immediately-enclosing block scope. 14145 // We recover from invalid scope qualifiers as if they just weren't there. 14146 FunctionDecl *FunctionContainingLocalClass = nullptr; 14147 if ((SS.isInvalid() || !SS.isSet()) && 14148 (FunctionContainingLocalClass = 14149 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14150 // C++11 [class.friend]p11: 14151 // If a friend declaration appears in a local class and the name 14152 // specified is an unqualified name, a prior declaration is 14153 // looked up without considering scopes that are outside the 14154 // innermost enclosing non-class scope. For a friend function 14155 // declaration, if there is no prior declaration, the program is 14156 // ill-formed. 14157 14158 // Find the innermost enclosing non-class scope. This is the block 14159 // scope containing the local class definition (or for a nested class, 14160 // the outer local class). 14161 DCScope = S->getFnParent(); 14162 14163 // Look up the function name in the scope. 14164 Previous.clear(LookupLocalFriendName); 14165 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14166 14167 if (!Previous.empty()) { 14168 // All possible previous declarations must have the same context: 14169 // either they were declared at block scope or they are members of 14170 // one of the enclosing local classes. 14171 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14172 } else { 14173 // This is ill-formed, but provide the context that we would have 14174 // declared the function in, if we were permitted to, for error recovery. 14175 DC = FunctionContainingLocalClass; 14176 } 14177 adjustContextForLocalExternDecl(DC); 14178 14179 // C++ [class.friend]p6: 14180 // A function can be defined in a friend declaration of a class if and 14181 // only if the class is a non-local class (9.8), the function name is 14182 // unqualified, and the function has namespace scope. 14183 if (D.isFunctionDefinition()) { 14184 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14185 } 14186 14187 // - There's no scope specifier, in which case we just go to the 14188 // appropriate scope and look for a function or function template 14189 // there as appropriate. 14190 } else if (SS.isInvalid() || !SS.isSet()) { 14191 // C++11 [namespace.memdef]p3: 14192 // If the name in a friend declaration is neither qualified nor 14193 // a template-id and the declaration is a function or an 14194 // elaborated-type-specifier, the lookup to determine whether 14195 // the entity has been previously declared shall not consider 14196 // any scopes outside the innermost enclosing namespace. 14197 bool isTemplateId = 14198 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14199 14200 // Find the appropriate context according to the above. 14201 DC = CurContext; 14202 14203 // Skip class contexts. If someone can cite chapter and verse 14204 // for this behavior, that would be nice --- it's what GCC and 14205 // EDG do, and it seems like a reasonable intent, but the spec 14206 // really only says that checks for unqualified existing 14207 // declarations should stop at the nearest enclosing namespace, 14208 // not that they should only consider the nearest enclosing 14209 // namespace. 14210 while (DC->isRecord()) 14211 DC = DC->getParent(); 14212 14213 DeclContext *LookupDC = DC; 14214 while (LookupDC->isTransparentContext()) 14215 LookupDC = LookupDC->getParent(); 14216 14217 while (true) { 14218 LookupQualifiedName(Previous, LookupDC); 14219 14220 if (!Previous.empty()) { 14221 DC = LookupDC; 14222 break; 14223 } 14224 14225 if (isTemplateId) { 14226 if (isa<TranslationUnitDecl>(LookupDC)) break; 14227 } else { 14228 if (LookupDC->isFileContext()) break; 14229 } 14230 LookupDC = LookupDC->getParent(); 14231 } 14232 14233 DCScope = getScopeForDeclContext(S, DC); 14234 14235 // - There's a non-dependent scope specifier, in which case we 14236 // compute it and do a previous lookup there for a function 14237 // or function template. 14238 } else if (!SS.getScopeRep()->isDependent()) { 14239 DC = computeDeclContext(SS); 14240 if (!DC) return nullptr; 14241 14242 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14243 14244 LookupQualifiedName(Previous, DC); 14245 14246 // Ignore things found implicitly in the wrong scope. 14247 // TODO: better diagnostics for this case. Suggesting the right 14248 // qualified scope would be nice... 14249 LookupResult::Filter F = Previous.makeFilter(); 14250 while (F.hasNext()) { 14251 NamedDecl *D = F.next(); 14252 if (!DC->InEnclosingNamespaceSetOf( 14253 D->getDeclContext()->getRedeclContext())) 14254 F.erase(); 14255 } 14256 F.done(); 14257 14258 if (Previous.empty()) { 14259 D.setInvalidType(); 14260 Diag(Loc, diag::err_qualified_friend_not_found) 14261 << Name << TInfo->getType(); 14262 return nullptr; 14263 } 14264 14265 // C++ [class.friend]p1: A friend of a class is a function or 14266 // class that is not a member of the class . . . 14267 if (DC->Equals(CurContext)) 14268 Diag(DS.getFriendSpecLoc(), 14269 getLangOpts().CPlusPlus11 ? 14270 diag::warn_cxx98_compat_friend_is_member : 14271 diag::err_friend_is_member); 14272 14273 if (D.isFunctionDefinition()) { 14274 // C++ [class.friend]p6: 14275 // A function can be defined in a friend declaration of a class if and 14276 // only if the class is a non-local class (9.8), the function name is 14277 // unqualified, and the function has namespace scope. 14278 SemaDiagnosticBuilder DB 14279 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14280 14281 DB << SS.getScopeRep(); 14282 if (DC->isFileContext()) 14283 DB << FixItHint::CreateRemoval(SS.getRange()); 14284 SS.clear(); 14285 } 14286 14287 // - There's a scope specifier that does not match any template 14288 // parameter lists, in which case we use some arbitrary context, 14289 // create a method or method template, and wait for instantiation. 14290 // - There's a scope specifier that does match some template 14291 // parameter lists, which we don't handle right now. 14292 } else { 14293 if (D.isFunctionDefinition()) { 14294 // C++ [class.friend]p6: 14295 // A function can be defined in a friend declaration of a class if and 14296 // only if the class is a non-local class (9.8), the function name is 14297 // unqualified, and the function has namespace scope. 14298 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14299 << SS.getScopeRep(); 14300 } 14301 14302 DC = CurContext; 14303 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14304 } 14305 14306 if (!DC->isRecord()) { 14307 int DiagArg = -1; 14308 switch (D.getName().getKind()) { 14309 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14310 case UnqualifiedIdKind::IK_ConstructorName: 14311 DiagArg = 0; 14312 break; 14313 case UnqualifiedIdKind::IK_DestructorName: 14314 DiagArg = 1; 14315 break; 14316 case UnqualifiedIdKind::IK_ConversionFunctionId: 14317 DiagArg = 2; 14318 break; 14319 case UnqualifiedIdKind::IK_DeductionGuideName: 14320 DiagArg = 3; 14321 break; 14322 case UnqualifiedIdKind::IK_Identifier: 14323 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14324 case UnqualifiedIdKind::IK_LiteralOperatorId: 14325 case UnqualifiedIdKind::IK_OperatorFunctionId: 14326 case UnqualifiedIdKind::IK_TemplateId: 14327 break; 14328 } 14329 // This implies that it has to be an operator or function. 14330 if (DiagArg >= 0) { 14331 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14332 return nullptr; 14333 } 14334 } 14335 14336 // FIXME: This is an egregious hack to cope with cases where the scope stack 14337 // does not contain the declaration context, i.e., in an out-of-line 14338 // definition of a class. 14339 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14340 if (!DCScope) { 14341 FakeDCScope.setEntity(DC); 14342 DCScope = &FakeDCScope; 14343 } 14344 14345 bool AddToScope = true; 14346 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14347 TemplateParams, AddToScope); 14348 if (!ND) return nullptr; 14349 14350 assert(ND->getLexicalDeclContext() == CurContext); 14351 14352 // If we performed typo correction, we might have added a scope specifier 14353 // and changed the decl context. 14354 DC = ND->getDeclContext(); 14355 14356 // Add the function declaration to the appropriate lookup tables, 14357 // adjusting the redeclarations list as necessary. We don't 14358 // want to do this yet if the friending class is dependent. 14359 // 14360 // Also update the scope-based lookup if the target context's 14361 // lookup context is in lexical scope. 14362 if (!CurContext->isDependentContext()) { 14363 DC = DC->getRedeclContext(); 14364 DC->makeDeclVisibleInContext(ND); 14365 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14366 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14367 } 14368 14369 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14370 D.getIdentifierLoc(), ND, 14371 DS.getFriendSpecLoc()); 14372 FrD->setAccess(AS_public); 14373 CurContext->addDecl(FrD); 14374 14375 if (ND->isInvalidDecl()) { 14376 FrD->setInvalidDecl(); 14377 } else { 14378 if (DC->isRecord()) CheckFriendAccess(ND); 14379 14380 FunctionDecl *FD; 14381 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14382 FD = FTD->getTemplatedDecl(); 14383 else 14384 FD = cast<FunctionDecl>(ND); 14385 14386 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14387 // default argument expression, that declaration shall be a definition 14388 // and shall be the only declaration of the function or function 14389 // template in the translation unit. 14390 if (functionDeclHasDefaultArgument(FD)) { 14391 // We can't look at FD->getPreviousDecl() because it may not have been set 14392 // if we're in a dependent context. If the function is known to be a 14393 // redeclaration, we will have narrowed Previous down to the right decl. 14394 if (D.isRedeclaration()) { 14395 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14396 Diag(Previous.getRepresentativeDecl()->getLocation(), 14397 diag::note_previous_declaration); 14398 } else if (!D.isFunctionDefinition()) 14399 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14400 } 14401 14402 // Mark templated-scope function declarations as unsupported. 14403 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14404 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14405 << SS.getScopeRep() << SS.getRange() 14406 << cast<CXXRecordDecl>(CurContext); 14407 FrD->setUnsupportedFriend(true); 14408 } 14409 } 14410 14411 return ND; 14412 } 14413 14414 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14415 AdjustDeclIfTemplate(Dcl); 14416 14417 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14418 if (!Fn) { 14419 Diag(DelLoc, diag::err_deleted_non_function); 14420 return; 14421 } 14422 14423 // Deleted function does not have a body. 14424 Fn->setWillHaveBody(false); 14425 14426 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14427 // Don't consider the implicit declaration we generate for explicit 14428 // specializations. FIXME: Do not generate these implicit declarations. 14429 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14430 Prev->getPreviousDecl()) && 14431 !Prev->isDefined()) { 14432 Diag(DelLoc, diag::err_deleted_decl_not_first); 14433 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14434 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14435 : diag::note_previous_declaration); 14436 } 14437 // If the declaration wasn't the first, we delete the function anyway for 14438 // recovery. 14439 Fn = Fn->getCanonicalDecl(); 14440 } 14441 14442 // dllimport/dllexport cannot be deleted. 14443 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14444 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14445 Fn->setInvalidDecl(); 14446 } 14447 14448 if (Fn->isDeleted()) 14449 return; 14450 14451 // See if we're deleting a function which is already known to override a 14452 // non-deleted virtual function. 14453 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14454 bool IssuedDiagnostic = false; 14455 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14456 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14457 if (!IssuedDiagnostic) { 14458 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14459 IssuedDiagnostic = true; 14460 } 14461 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14462 } 14463 } 14464 // If this function was implicitly deleted because it was defaulted, 14465 // explain why it was deleted. 14466 if (IssuedDiagnostic && MD->isDefaulted()) 14467 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14468 /*Diagnose*/true); 14469 } 14470 14471 // C++11 [basic.start.main]p3: 14472 // A program that defines main as deleted [...] is ill-formed. 14473 if (Fn->isMain()) 14474 Diag(DelLoc, diag::err_deleted_main); 14475 14476 // C++11 [dcl.fct.def.delete]p4: 14477 // A deleted function is implicitly inline. 14478 Fn->setImplicitlyInline(); 14479 Fn->setDeletedAsWritten(); 14480 } 14481 14482 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14483 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14484 14485 if (MD) { 14486 if (MD->getParent()->isDependentType()) { 14487 MD->setDefaulted(); 14488 MD->setExplicitlyDefaulted(); 14489 return; 14490 } 14491 14492 CXXSpecialMember Member = getSpecialMember(MD); 14493 if (Member == CXXInvalid) { 14494 if (!MD->isInvalidDecl()) 14495 Diag(DefaultLoc, diag::err_default_special_members); 14496 return; 14497 } 14498 14499 MD->setDefaulted(); 14500 MD->setExplicitlyDefaulted(); 14501 14502 // Unset that we will have a body for this function. We might not, 14503 // if it turns out to be trivial, and we don't need this marking now 14504 // that we've marked it as defaulted. 14505 MD->setWillHaveBody(false); 14506 14507 // If this definition appears within the record, do the checking when 14508 // the record is complete. 14509 const FunctionDecl *Primary = MD; 14510 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14511 // Ask the template instantiation pattern that actually had the 14512 // '= default' on it. 14513 Primary = Pattern; 14514 14515 // If the method was defaulted on its first declaration, we will have 14516 // already performed the checking in CheckCompletedCXXClass. Such a 14517 // declaration doesn't trigger an implicit definition. 14518 if (Primary->getCanonicalDecl()->isDefaulted()) 14519 return; 14520 14521 CheckExplicitlyDefaultedSpecialMember(MD); 14522 14523 if (!MD->isInvalidDecl()) 14524 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14525 } else { 14526 Diag(DefaultLoc, diag::err_default_special_members); 14527 } 14528 } 14529 14530 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14531 for (Stmt *SubStmt : S->children()) { 14532 if (!SubStmt) 14533 continue; 14534 if (isa<ReturnStmt>(SubStmt)) 14535 Self.Diag(SubStmt->getLocStart(), 14536 diag::err_return_in_constructor_handler); 14537 if (!isa<Expr>(SubStmt)) 14538 SearchForReturnInStmt(Self, SubStmt); 14539 } 14540 } 14541 14542 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14543 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14544 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14545 SearchForReturnInStmt(*this, Handler); 14546 } 14547 } 14548 14549 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14550 const CXXMethodDecl *Old) { 14551 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14552 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14553 14554 if (OldFT->hasExtParameterInfos()) { 14555 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14556 // A parameter of the overriding method should be annotated with noescape 14557 // if the corresponding parameter of the overridden method is annotated. 14558 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14559 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14560 Diag(New->getParamDecl(I)->getLocation(), 14561 diag::warn_overriding_method_missing_noescape); 14562 Diag(Old->getParamDecl(I)->getLocation(), 14563 diag::note_overridden_marked_noescape); 14564 } 14565 } 14566 14567 // Virtual overrides must have the same code_seg. 14568 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14569 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14570 if ((NewCSA || OldCSA) && 14571 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14572 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14573 Diag(Old->getLocation(), diag::note_previous_declaration); 14574 return true; 14575 } 14576 14577 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14578 14579 // If the calling conventions match, everything is fine 14580 if (NewCC == OldCC) 14581 return false; 14582 14583 // If the calling conventions mismatch because the new function is static, 14584 // suppress the calling convention mismatch error; the error about static 14585 // function override (err_static_overrides_virtual from 14586 // Sema::CheckFunctionDeclaration) is more clear. 14587 if (New->getStorageClass() == SC_Static) 14588 return false; 14589 14590 Diag(New->getLocation(), 14591 diag::err_conflicting_overriding_cc_attributes) 14592 << New->getDeclName() << New->getType() << Old->getType(); 14593 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14594 return true; 14595 } 14596 14597 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14598 const CXXMethodDecl *Old) { 14599 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14600 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14601 14602 if (Context.hasSameType(NewTy, OldTy) || 14603 NewTy->isDependentType() || OldTy->isDependentType()) 14604 return false; 14605 14606 // Check if the return types are covariant 14607 QualType NewClassTy, OldClassTy; 14608 14609 /// Both types must be pointers or references to classes. 14610 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14611 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14612 NewClassTy = NewPT->getPointeeType(); 14613 OldClassTy = OldPT->getPointeeType(); 14614 } 14615 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14616 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14617 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14618 NewClassTy = NewRT->getPointeeType(); 14619 OldClassTy = OldRT->getPointeeType(); 14620 } 14621 } 14622 } 14623 14624 // The return types aren't either both pointers or references to a class type. 14625 if (NewClassTy.isNull()) { 14626 Diag(New->getLocation(), 14627 diag::err_different_return_type_for_overriding_virtual_function) 14628 << New->getDeclName() << NewTy << OldTy 14629 << New->getReturnTypeSourceRange(); 14630 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14631 << Old->getReturnTypeSourceRange(); 14632 14633 return true; 14634 } 14635 14636 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14637 // C++14 [class.virtual]p8: 14638 // If the class type in the covariant return type of D::f differs from 14639 // that of B::f, the class type in the return type of D::f shall be 14640 // complete at the point of declaration of D::f or shall be the class 14641 // type D. 14642 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14643 if (!RT->isBeingDefined() && 14644 RequireCompleteType(New->getLocation(), NewClassTy, 14645 diag::err_covariant_return_incomplete, 14646 New->getDeclName())) 14647 return true; 14648 } 14649 14650 // Check if the new class derives from the old class. 14651 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14652 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14653 << New->getDeclName() << NewTy << OldTy 14654 << New->getReturnTypeSourceRange(); 14655 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14656 << Old->getReturnTypeSourceRange(); 14657 return true; 14658 } 14659 14660 // Check if we the conversion from derived to base is valid. 14661 if (CheckDerivedToBaseConversion( 14662 NewClassTy, OldClassTy, 14663 diag::err_covariant_return_inaccessible_base, 14664 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14665 New->getLocation(), New->getReturnTypeSourceRange(), 14666 New->getDeclName(), nullptr)) { 14667 // FIXME: this note won't trigger for delayed access control 14668 // diagnostics, and it's impossible to get an undelayed error 14669 // here from access control during the original parse because 14670 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14671 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14672 << Old->getReturnTypeSourceRange(); 14673 return true; 14674 } 14675 } 14676 14677 // The qualifiers of the return types must be the same. 14678 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14679 Diag(New->getLocation(), 14680 diag::err_covariant_return_type_different_qualifications) 14681 << New->getDeclName() << NewTy << OldTy 14682 << New->getReturnTypeSourceRange(); 14683 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14684 << Old->getReturnTypeSourceRange(); 14685 return true; 14686 } 14687 14688 14689 // The new class type must have the same or less qualifiers as the old type. 14690 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14691 Diag(New->getLocation(), 14692 diag::err_covariant_return_type_class_type_more_qualified) 14693 << New->getDeclName() << NewTy << OldTy 14694 << New->getReturnTypeSourceRange(); 14695 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14696 << Old->getReturnTypeSourceRange(); 14697 return true; 14698 } 14699 14700 return false; 14701 } 14702 14703 /// Mark the given method pure. 14704 /// 14705 /// \param Method the method to be marked pure. 14706 /// 14707 /// \param InitRange the source range that covers the "0" initializer. 14708 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14709 SourceLocation EndLoc = InitRange.getEnd(); 14710 if (EndLoc.isValid()) 14711 Method->setRangeEnd(EndLoc); 14712 14713 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14714 Method->setPure(); 14715 return false; 14716 } 14717 14718 if (!Method->isInvalidDecl()) 14719 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14720 << Method->getDeclName() << InitRange; 14721 return true; 14722 } 14723 14724 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14725 if (D->getFriendObjectKind()) 14726 Diag(D->getLocation(), diag::err_pure_friend); 14727 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14728 CheckPureMethod(M, ZeroLoc); 14729 else 14730 Diag(D->getLocation(), diag::err_illegal_initializer); 14731 } 14732 14733 /// Determine whether the given declaration is a global variable or 14734 /// static data member. 14735 static bool isNonlocalVariable(const Decl *D) { 14736 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14737 return Var->hasGlobalStorage(); 14738 14739 return false; 14740 } 14741 14742 /// Invoked when we are about to parse an initializer for the declaration 14743 /// 'Dcl'. 14744 /// 14745 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14746 /// static data member of class X, names should be looked up in the scope of 14747 /// class X. If the declaration had a scope specifier, a scope will have 14748 /// been created and passed in for this purpose. Otherwise, S will be null. 14749 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14750 // If there is no declaration, there was an error parsing it. 14751 if (!D || D->isInvalidDecl()) 14752 return; 14753 14754 // We will always have a nested name specifier here, but this declaration 14755 // might not be out of line if the specifier names the current namespace: 14756 // extern int n; 14757 // int ::n = 0; 14758 if (S && D->isOutOfLine()) 14759 EnterDeclaratorContext(S, D->getDeclContext()); 14760 14761 // If we are parsing the initializer for a static data member, push a 14762 // new expression evaluation context that is associated with this static 14763 // data member. 14764 if (isNonlocalVariable(D)) 14765 PushExpressionEvaluationContext( 14766 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14767 } 14768 14769 /// Invoked after we are finished parsing an initializer for the declaration D. 14770 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14771 // If there is no declaration, there was an error parsing it. 14772 if (!D || D->isInvalidDecl()) 14773 return; 14774 14775 if (isNonlocalVariable(D)) 14776 PopExpressionEvaluationContext(); 14777 14778 if (S && D->isOutOfLine()) 14779 ExitDeclaratorContext(S); 14780 } 14781 14782 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14783 /// C++ if/switch/while/for statement. 14784 /// e.g: "if (int x = f()) {...}" 14785 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14786 // C++ 6.4p2: 14787 // The declarator shall not specify a function or an array. 14788 // The type-specifier-seq shall not contain typedef and shall not declare a 14789 // new class or enumeration. 14790 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14791 "Parser allowed 'typedef' as storage class of condition decl."); 14792 14793 Decl *Dcl = ActOnDeclarator(S, D); 14794 if (!Dcl) 14795 return true; 14796 14797 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14798 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14799 << D.getSourceRange(); 14800 return true; 14801 } 14802 14803 return Dcl; 14804 } 14805 14806 void Sema::LoadExternalVTableUses() { 14807 if (!ExternalSource) 14808 return; 14809 14810 SmallVector<ExternalVTableUse, 4> VTables; 14811 ExternalSource->ReadUsedVTables(VTables); 14812 SmallVector<VTableUse, 4> NewUses; 14813 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14814 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14815 = VTablesUsed.find(VTables[I].Record); 14816 // Even if a definition wasn't required before, it may be required now. 14817 if (Pos != VTablesUsed.end()) { 14818 if (!Pos->second && VTables[I].DefinitionRequired) 14819 Pos->second = true; 14820 continue; 14821 } 14822 14823 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14824 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14825 } 14826 14827 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14828 } 14829 14830 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14831 bool DefinitionRequired) { 14832 // Ignore any vtable uses in unevaluated operands or for classes that do 14833 // not have a vtable. 14834 if (!Class->isDynamicClass() || Class->isDependentContext() || 14835 CurContext->isDependentContext() || isUnevaluatedContext()) 14836 return; 14837 14838 // Try to insert this class into the map. 14839 LoadExternalVTableUses(); 14840 Class = Class->getCanonicalDecl(); 14841 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14842 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14843 if (!Pos.second) { 14844 // If we already had an entry, check to see if we are promoting this vtable 14845 // to require a definition. If so, we need to reappend to the VTableUses 14846 // list, since we may have already processed the first entry. 14847 if (DefinitionRequired && !Pos.first->second) { 14848 Pos.first->second = true; 14849 } else { 14850 // Otherwise, we can early exit. 14851 return; 14852 } 14853 } else { 14854 // The Microsoft ABI requires that we perform the destructor body 14855 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14856 // the deleting destructor is emitted with the vtable, not with the 14857 // destructor definition as in the Itanium ABI. 14858 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14859 CXXDestructorDecl *DD = Class->getDestructor(); 14860 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14861 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14862 // If this is an out-of-line declaration, marking it referenced will 14863 // not do anything. Manually call CheckDestructor to look up operator 14864 // delete(). 14865 ContextRAII SavedContext(*this, DD); 14866 CheckDestructor(DD); 14867 } else { 14868 MarkFunctionReferenced(Loc, Class->getDestructor()); 14869 } 14870 } 14871 } 14872 } 14873 14874 // Local classes need to have their virtual members marked 14875 // immediately. For all other classes, we mark their virtual members 14876 // at the end of the translation unit. 14877 if (Class->isLocalClass()) 14878 MarkVirtualMembersReferenced(Loc, Class); 14879 else 14880 VTableUses.push_back(std::make_pair(Class, Loc)); 14881 } 14882 14883 bool Sema::DefineUsedVTables() { 14884 LoadExternalVTableUses(); 14885 if (VTableUses.empty()) 14886 return false; 14887 14888 // Note: The VTableUses vector could grow as a result of marking 14889 // the members of a class as "used", so we check the size each 14890 // time through the loop and prefer indices (which are stable) to 14891 // iterators (which are not). 14892 bool DefinedAnything = false; 14893 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14894 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14895 if (!Class) 14896 continue; 14897 TemplateSpecializationKind ClassTSK = 14898 Class->getTemplateSpecializationKind(); 14899 14900 SourceLocation Loc = VTableUses[I].second; 14901 14902 bool DefineVTable = true; 14903 14904 // If this class has a key function, but that key function is 14905 // defined in another translation unit, we don't need to emit the 14906 // vtable even though we're using it. 14907 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14908 if (KeyFunction && !KeyFunction->hasBody()) { 14909 // The key function is in another translation unit. 14910 DefineVTable = false; 14911 TemplateSpecializationKind TSK = 14912 KeyFunction->getTemplateSpecializationKind(); 14913 assert(TSK != TSK_ExplicitInstantiationDefinition && 14914 TSK != TSK_ImplicitInstantiation && 14915 "Instantiations don't have key functions"); 14916 (void)TSK; 14917 } else if (!KeyFunction) { 14918 // If we have a class with no key function that is the subject 14919 // of an explicit instantiation declaration, suppress the 14920 // vtable; it will live with the explicit instantiation 14921 // definition. 14922 bool IsExplicitInstantiationDeclaration = 14923 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14924 for (auto R : Class->redecls()) { 14925 TemplateSpecializationKind TSK 14926 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14927 if (TSK == TSK_ExplicitInstantiationDeclaration) 14928 IsExplicitInstantiationDeclaration = true; 14929 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14930 IsExplicitInstantiationDeclaration = false; 14931 break; 14932 } 14933 } 14934 14935 if (IsExplicitInstantiationDeclaration) 14936 DefineVTable = false; 14937 } 14938 14939 // The exception specifications for all virtual members may be needed even 14940 // if we are not providing an authoritative form of the vtable in this TU. 14941 // We may choose to emit it available_externally anyway. 14942 if (!DefineVTable) { 14943 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14944 continue; 14945 } 14946 14947 // Mark all of the virtual members of this class as referenced, so 14948 // that we can build a vtable. Then, tell the AST consumer that a 14949 // vtable for this class is required. 14950 DefinedAnything = true; 14951 MarkVirtualMembersReferenced(Loc, Class); 14952 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 14953 if (VTablesUsed[Canonical]) 14954 Consumer.HandleVTable(Class); 14955 14956 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14957 // no key function or the key function is inlined. Don't warn in C++ ABIs 14958 // that lack key functions, since the user won't be able to make one. 14959 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14960 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14961 const FunctionDecl *KeyFunctionDef = nullptr; 14962 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14963 KeyFunctionDef->isInlined())) { 14964 Diag(Class->getLocation(), 14965 ClassTSK == TSK_ExplicitInstantiationDefinition 14966 ? diag::warn_weak_template_vtable 14967 : diag::warn_weak_vtable) 14968 << Class; 14969 } 14970 } 14971 } 14972 VTableUses.clear(); 14973 14974 return DefinedAnything; 14975 } 14976 14977 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14978 const CXXRecordDecl *RD) { 14979 for (const auto *I : RD->methods()) 14980 if (I->isVirtual() && !I->isPure()) 14981 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14982 } 14983 14984 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14985 const CXXRecordDecl *RD) { 14986 // Mark all functions which will appear in RD's vtable as used. 14987 CXXFinalOverriderMap FinalOverriders; 14988 RD->getFinalOverriders(FinalOverriders); 14989 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14990 E = FinalOverriders.end(); 14991 I != E; ++I) { 14992 for (OverridingMethods::const_iterator OI = I->second.begin(), 14993 OE = I->second.end(); 14994 OI != OE; ++OI) { 14995 assert(OI->second.size() > 0 && "no final overrider"); 14996 CXXMethodDecl *Overrider = OI->second.front().Method; 14997 14998 // C++ [basic.def.odr]p2: 14999 // [...] A virtual member function is used if it is not pure. [...] 15000 if (!Overrider->isPure()) 15001 MarkFunctionReferenced(Loc, Overrider); 15002 } 15003 } 15004 15005 // Only classes that have virtual bases need a VTT. 15006 if (RD->getNumVBases() == 0) 15007 return; 15008 15009 for (const auto &I : RD->bases()) { 15010 const CXXRecordDecl *Base = 15011 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15012 if (Base->getNumVBases() == 0) 15013 continue; 15014 MarkVirtualMembersReferenced(Loc, Base); 15015 } 15016 } 15017 15018 /// SetIvarInitializers - This routine builds initialization ASTs for the 15019 /// Objective-C implementation whose ivars need be initialized. 15020 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15021 if (!getLangOpts().CPlusPlus) 15022 return; 15023 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15024 SmallVector<ObjCIvarDecl*, 8> ivars; 15025 CollectIvarsToConstructOrDestruct(OID, ivars); 15026 if (ivars.empty()) 15027 return; 15028 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15029 for (unsigned i = 0; i < ivars.size(); i++) { 15030 FieldDecl *Field = ivars[i]; 15031 if (Field->isInvalidDecl()) 15032 continue; 15033 15034 CXXCtorInitializer *Member; 15035 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15036 InitializationKind InitKind = 15037 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15038 15039 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15040 ExprResult MemberInit = 15041 InitSeq.Perform(*this, InitEntity, InitKind, None); 15042 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15043 // Note, MemberInit could actually come back empty if no initialization 15044 // is required (e.g., because it would call a trivial default constructor) 15045 if (!MemberInit.get() || MemberInit.isInvalid()) 15046 continue; 15047 15048 Member = 15049 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15050 SourceLocation(), 15051 MemberInit.getAs<Expr>(), 15052 SourceLocation()); 15053 AllToInit.push_back(Member); 15054 15055 // Be sure that the destructor is accessible and is marked as referenced. 15056 if (const RecordType *RecordTy = 15057 Context.getBaseElementType(Field->getType()) 15058 ->getAs<RecordType>()) { 15059 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15060 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15061 MarkFunctionReferenced(Field->getLocation(), Destructor); 15062 CheckDestructorAccess(Field->getLocation(), Destructor, 15063 PDiag(diag::err_access_dtor_ivar) 15064 << Context.getBaseElementType(Field->getType())); 15065 } 15066 } 15067 } 15068 ObjCImplementation->setIvarInitializers(Context, 15069 AllToInit.data(), AllToInit.size()); 15070 } 15071 } 15072 15073 static 15074 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15075 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15076 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15077 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15078 Sema &S) { 15079 if (Ctor->isInvalidDecl()) 15080 return; 15081 15082 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15083 15084 // Target may not be determinable yet, for instance if this is a dependent 15085 // call in an uninstantiated template. 15086 if (Target) { 15087 const FunctionDecl *FNTarget = nullptr; 15088 (void)Target->hasBody(FNTarget); 15089 Target = const_cast<CXXConstructorDecl*>( 15090 cast_or_null<CXXConstructorDecl>(FNTarget)); 15091 } 15092 15093 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15094 // Avoid dereferencing a null pointer here. 15095 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15096 15097 if (!Current.insert(Canonical).second) 15098 return; 15099 15100 // We know that beyond here, we aren't chaining into a cycle. 15101 if (!Target || !Target->isDelegatingConstructor() || 15102 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15103 Valid.insert(Current.begin(), Current.end()); 15104 Current.clear(); 15105 // We've hit a cycle. 15106 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15107 Current.count(TCanonical)) { 15108 // If we haven't diagnosed this cycle yet, do so now. 15109 if (!Invalid.count(TCanonical)) { 15110 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15111 diag::warn_delegating_ctor_cycle) 15112 << Ctor; 15113 15114 // Don't add a note for a function delegating directly to itself. 15115 if (TCanonical != Canonical) 15116 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15117 15118 CXXConstructorDecl *C = Target; 15119 while (C->getCanonicalDecl() != Canonical) { 15120 const FunctionDecl *FNTarget = nullptr; 15121 (void)C->getTargetConstructor()->hasBody(FNTarget); 15122 assert(FNTarget && "Ctor cycle through bodiless function"); 15123 15124 C = const_cast<CXXConstructorDecl*>( 15125 cast<CXXConstructorDecl>(FNTarget)); 15126 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15127 } 15128 } 15129 15130 Invalid.insert(Current.begin(), Current.end()); 15131 Current.clear(); 15132 } else { 15133 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15134 } 15135 } 15136 15137 15138 void Sema::CheckDelegatingCtorCycles() { 15139 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15140 15141 for (DelegatingCtorDeclsType::iterator 15142 I = DelegatingCtorDecls.begin(ExternalSource), 15143 E = DelegatingCtorDecls.end(); 15144 I != E; ++I) 15145 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15146 15147 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15148 (*CI)->setInvalidDecl(); 15149 } 15150 15151 namespace { 15152 /// AST visitor that finds references to the 'this' expression. 15153 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15154 Sema &S; 15155 15156 public: 15157 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15158 15159 bool VisitCXXThisExpr(CXXThisExpr *E) { 15160 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15161 << E->isImplicit(); 15162 return false; 15163 } 15164 }; 15165 } 15166 15167 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15168 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15169 if (!TSInfo) 15170 return false; 15171 15172 TypeLoc TL = TSInfo->getTypeLoc(); 15173 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15174 if (!ProtoTL) 15175 return false; 15176 15177 // C++11 [expr.prim.general]p3: 15178 // [The expression this] shall not appear before the optional 15179 // cv-qualifier-seq and it shall not appear within the declaration of a 15180 // static member function (although its type and value category are defined 15181 // within a static member function as they are within a non-static member 15182 // function). [ Note: this is because declaration matching does not occur 15183 // until the complete declarator is known. - end note ] 15184 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15185 FindCXXThisExpr Finder(*this); 15186 15187 // If the return type came after the cv-qualifier-seq, check it now. 15188 if (Proto->hasTrailingReturn() && 15189 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15190 return true; 15191 15192 // Check the exception specification. 15193 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15194 return true; 15195 15196 return checkThisInStaticMemberFunctionAttributes(Method); 15197 } 15198 15199 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15200 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15201 if (!TSInfo) 15202 return false; 15203 15204 TypeLoc TL = TSInfo->getTypeLoc(); 15205 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15206 if (!ProtoTL) 15207 return false; 15208 15209 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15210 FindCXXThisExpr Finder(*this); 15211 15212 switch (Proto->getExceptionSpecType()) { 15213 case EST_Unparsed: 15214 case EST_Uninstantiated: 15215 case EST_Unevaluated: 15216 case EST_BasicNoexcept: 15217 case EST_DynamicNone: 15218 case EST_MSAny: 15219 case EST_None: 15220 break; 15221 15222 case EST_DependentNoexcept: 15223 case EST_NoexceptFalse: 15224 case EST_NoexceptTrue: 15225 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15226 return true; 15227 LLVM_FALLTHROUGH; 15228 15229 case EST_Dynamic: 15230 for (const auto &E : Proto->exceptions()) { 15231 if (!Finder.TraverseType(E)) 15232 return true; 15233 } 15234 break; 15235 } 15236 15237 return false; 15238 } 15239 15240 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15241 FindCXXThisExpr Finder(*this); 15242 15243 // Check attributes. 15244 for (const auto *A : Method->attrs()) { 15245 // FIXME: This should be emitted by tblgen. 15246 Expr *Arg = nullptr; 15247 ArrayRef<Expr *> Args; 15248 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15249 Arg = G->getArg(); 15250 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15251 Arg = G->getArg(); 15252 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15253 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15254 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15255 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15256 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15257 Arg = ETLF->getSuccessValue(); 15258 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15259 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15260 Arg = STLF->getSuccessValue(); 15261 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15262 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15263 Arg = LR->getArg(); 15264 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15265 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15266 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15267 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15268 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15269 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15270 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15271 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15272 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15273 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15274 15275 if (Arg && !Finder.TraverseStmt(Arg)) 15276 return true; 15277 15278 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15279 if (!Finder.TraverseStmt(Args[I])) 15280 return true; 15281 } 15282 } 15283 15284 return false; 15285 } 15286 15287 void Sema::checkExceptionSpecification( 15288 bool IsTopLevel, ExceptionSpecificationType EST, 15289 ArrayRef<ParsedType> DynamicExceptions, 15290 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15291 SmallVectorImpl<QualType> &Exceptions, 15292 FunctionProtoType::ExceptionSpecInfo &ESI) { 15293 Exceptions.clear(); 15294 ESI.Type = EST; 15295 if (EST == EST_Dynamic) { 15296 Exceptions.reserve(DynamicExceptions.size()); 15297 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15298 // FIXME: Preserve type source info. 15299 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15300 15301 if (IsTopLevel) { 15302 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15303 collectUnexpandedParameterPacks(ET, Unexpanded); 15304 if (!Unexpanded.empty()) { 15305 DiagnoseUnexpandedParameterPacks( 15306 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15307 Unexpanded); 15308 continue; 15309 } 15310 } 15311 15312 // Check that the type is valid for an exception spec, and 15313 // drop it if not. 15314 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15315 Exceptions.push_back(ET); 15316 } 15317 ESI.Exceptions = Exceptions; 15318 return; 15319 } 15320 15321 if (isComputedNoexcept(EST)) { 15322 assert((NoexceptExpr->isTypeDependent() || 15323 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15324 Context.BoolTy) && 15325 "Parser should have made sure that the expression is boolean"); 15326 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15327 ESI.Type = EST_BasicNoexcept; 15328 return; 15329 } 15330 15331 ESI.NoexceptExpr = NoexceptExpr; 15332 return; 15333 } 15334 } 15335 15336 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15337 ExceptionSpecificationType EST, 15338 SourceRange SpecificationRange, 15339 ArrayRef<ParsedType> DynamicExceptions, 15340 ArrayRef<SourceRange> DynamicExceptionRanges, 15341 Expr *NoexceptExpr) { 15342 if (!MethodD) 15343 return; 15344 15345 // Dig out the method we're referring to. 15346 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15347 MethodD = FunTmpl->getTemplatedDecl(); 15348 15349 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15350 if (!Method) 15351 return; 15352 15353 // Check the exception specification. 15354 llvm::SmallVector<QualType, 4> Exceptions; 15355 FunctionProtoType::ExceptionSpecInfo ESI; 15356 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15357 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15358 ESI); 15359 15360 // Update the exception specification on the function type. 15361 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15362 15363 if (Method->isStatic()) 15364 checkThisInStaticMemberFunctionExceptionSpec(Method); 15365 15366 if (Method->isVirtual()) { 15367 // Check overrides, which we previously had to delay. 15368 for (const CXXMethodDecl *O : Method->overridden_methods()) 15369 CheckOverridingFunctionExceptionSpec(Method, O); 15370 } 15371 } 15372 15373 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15374 /// 15375 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15376 SourceLocation DeclStart, Declarator &D, 15377 Expr *BitWidth, 15378 InClassInitStyle InitStyle, 15379 AccessSpecifier AS, 15380 const ParsedAttr &MSPropertyAttr) { 15381 IdentifierInfo *II = D.getIdentifier(); 15382 if (!II) { 15383 Diag(DeclStart, diag::err_anonymous_property); 15384 return nullptr; 15385 } 15386 SourceLocation Loc = D.getIdentifierLoc(); 15387 15388 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15389 QualType T = TInfo->getType(); 15390 if (getLangOpts().CPlusPlus) { 15391 CheckExtraCXXDefaultArguments(D); 15392 15393 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15394 UPPC_DataMemberType)) { 15395 D.setInvalidType(); 15396 T = Context.IntTy; 15397 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15398 } 15399 } 15400 15401 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15402 15403 if (D.getDeclSpec().isInlineSpecified()) 15404 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15405 << getLangOpts().CPlusPlus17; 15406 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15407 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15408 diag::err_invalid_thread) 15409 << DeclSpec::getSpecifierName(TSCS); 15410 15411 // Check to see if this name was declared as a member previously 15412 NamedDecl *PrevDecl = nullptr; 15413 LookupResult Previous(*this, II, Loc, LookupMemberName, 15414 ForVisibleRedeclaration); 15415 LookupName(Previous, S); 15416 switch (Previous.getResultKind()) { 15417 case LookupResult::Found: 15418 case LookupResult::FoundUnresolvedValue: 15419 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15420 break; 15421 15422 case LookupResult::FoundOverloaded: 15423 PrevDecl = Previous.getRepresentativeDecl(); 15424 break; 15425 15426 case LookupResult::NotFound: 15427 case LookupResult::NotFoundInCurrentInstantiation: 15428 case LookupResult::Ambiguous: 15429 break; 15430 } 15431 15432 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15433 // Maybe we will complain about the shadowed template parameter. 15434 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15435 // Just pretend that we didn't see the previous declaration. 15436 PrevDecl = nullptr; 15437 } 15438 15439 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15440 PrevDecl = nullptr; 15441 15442 SourceLocation TSSL = D.getLocStart(); 15443 const ParsedAttr::PropertyData &Data = MSPropertyAttr.getPropertyData(); 15444 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15445 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15446 ProcessDeclAttributes(TUScope, NewPD, D); 15447 NewPD->setAccess(AS); 15448 15449 if (NewPD->isInvalidDecl()) 15450 Record->setInvalidDecl(); 15451 15452 if (D.getDeclSpec().isModulePrivateSpecified()) 15453 NewPD->setModulePrivate(); 15454 15455 if (NewPD->isInvalidDecl() && PrevDecl) { 15456 // Don't introduce NewFD into scope; there's already something 15457 // with the same name in the same scope. 15458 } else if (II) { 15459 PushOnScopeChains(NewPD, S); 15460 } else 15461 Record->addDecl(NewPD); 15462 15463 return NewPD; 15464 } 15465