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 /// isCurrentClassName - Determine whether the identifier II is the 2063 /// name of the class type currently being defined. In the case of 2064 /// nested classes, this will only return true if II is the name of 2065 /// the innermost class. 2066 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2067 const CXXScopeSpec *SS) { 2068 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2069 2070 CXXRecordDecl *CurDecl; 2071 if (SS && SS->isSet() && !SS->isInvalid()) { 2072 DeclContext *DC = computeDeclContext(*SS, true); 2073 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2074 } else 2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2076 2077 if (CurDecl && CurDecl->getIdentifier()) 2078 return &II == CurDecl->getIdentifier(); 2079 return false; 2080 } 2081 2082 /// Determine whether the identifier II is a typo for the name of 2083 /// the class type currently being defined. If so, update it to the identifier 2084 /// that should have been used. 2085 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2086 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2087 2088 if (!getLangOpts().SpellChecking) 2089 return false; 2090 2091 CXXRecordDecl *CurDecl; 2092 if (SS && SS->isSet() && !SS->isInvalid()) { 2093 DeclContext *DC = computeDeclContext(*SS, true); 2094 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2095 } else 2096 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2097 2098 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2099 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2100 < II->getLength()) { 2101 II = CurDecl->getIdentifier(); 2102 return true; 2103 } 2104 2105 return false; 2106 } 2107 2108 /// Determine whether the given class is a base class of the given 2109 /// class, including looking at dependent bases. 2110 static bool findCircularInheritance(const CXXRecordDecl *Class, 2111 const CXXRecordDecl *Current) { 2112 SmallVector<const CXXRecordDecl*, 8> Queue; 2113 2114 Class = Class->getCanonicalDecl(); 2115 while (true) { 2116 for (const auto &I : Current->bases()) { 2117 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2118 if (!Base) 2119 continue; 2120 2121 Base = Base->getDefinition(); 2122 if (!Base) 2123 continue; 2124 2125 if (Base->getCanonicalDecl() == Class) 2126 return true; 2127 2128 Queue.push_back(Base); 2129 } 2130 2131 if (Queue.empty()) 2132 return false; 2133 2134 Current = Queue.pop_back_val(); 2135 } 2136 2137 return false; 2138 } 2139 2140 /// Check the validity of a C++ base class specifier. 2141 /// 2142 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2143 /// and returns NULL otherwise. 2144 CXXBaseSpecifier * 2145 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2146 SourceRange SpecifierRange, 2147 bool Virtual, AccessSpecifier Access, 2148 TypeSourceInfo *TInfo, 2149 SourceLocation EllipsisLoc) { 2150 QualType BaseType = TInfo->getType(); 2151 2152 // C++ [class.union]p1: 2153 // A union shall not have base classes. 2154 if (Class->isUnion()) { 2155 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2156 << SpecifierRange; 2157 return nullptr; 2158 } 2159 2160 if (EllipsisLoc.isValid() && 2161 !TInfo->getType()->containsUnexpandedParameterPack()) { 2162 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2163 << TInfo->getTypeLoc().getSourceRange(); 2164 EllipsisLoc = SourceLocation(); 2165 } 2166 2167 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2168 2169 if (BaseType->isDependentType()) { 2170 // Make sure that we don't have circular inheritance among our dependent 2171 // bases. For non-dependent bases, the check for completeness below handles 2172 // this. 2173 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2174 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2175 ((BaseDecl = BaseDecl->getDefinition()) && 2176 findCircularInheritance(Class, BaseDecl))) { 2177 Diag(BaseLoc, diag::err_circular_inheritance) 2178 << BaseType << Context.getTypeDeclType(Class); 2179 2180 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2181 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2182 << BaseType; 2183 2184 return nullptr; 2185 } 2186 } 2187 2188 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2189 Class->getTagKind() == TTK_Class, 2190 Access, TInfo, EllipsisLoc); 2191 } 2192 2193 // Base specifiers must be record types. 2194 if (!BaseType->isRecordType()) { 2195 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2196 return nullptr; 2197 } 2198 2199 // C++ [class.union]p1: 2200 // A union shall not be used as a base class. 2201 if (BaseType->isUnionType()) { 2202 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2203 return nullptr; 2204 } 2205 2206 // For the MS ABI, propagate DLL attributes to base class templates. 2207 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2208 if (Attr *ClassAttr = getDLLAttr(Class)) { 2209 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2210 BaseType->getAsCXXRecordDecl())) { 2211 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2212 BaseLoc); 2213 } 2214 } 2215 } 2216 2217 // C++ [class.derived]p2: 2218 // The class-name in a base-specifier shall not be an incompletely 2219 // defined class. 2220 if (RequireCompleteType(BaseLoc, BaseType, 2221 diag::err_incomplete_base_class, SpecifierRange)) { 2222 Class->setInvalidDecl(); 2223 return nullptr; 2224 } 2225 2226 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2227 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2228 assert(BaseDecl && "Record type has no declaration"); 2229 BaseDecl = BaseDecl->getDefinition(); 2230 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2231 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2232 assert(CXXBaseDecl && "Base type is not a C++ type"); 2233 2234 // A class which contains a flexible array member is not suitable for use as a 2235 // base class: 2236 // - If the layout determines that a base comes before another base, 2237 // the flexible array member would index into the subsequent base. 2238 // - If the layout determines that base comes before the derived class, 2239 // the flexible array member would index into the derived class. 2240 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2241 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2242 << CXXBaseDecl->getDeclName(); 2243 return nullptr; 2244 } 2245 2246 // C++ [class]p3: 2247 // If a class is marked final and it appears as a base-type-specifier in 2248 // base-clause, the program is ill-formed. 2249 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2250 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2251 << CXXBaseDecl->getDeclName() 2252 << FA->isSpelledAsSealed(); 2253 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2254 << CXXBaseDecl->getDeclName() << FA->getRange(); 2255 return nullptr; 2256 } 2257 2258 if (BaseDecl->isInvalidDecl()) 2259 Class->setInvalidDecl(); 2260 2261 // Create the base specifier. 2262 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2263 Class->getTagKind() == TTK_Class, 2264 Access, TInfo, EllipsisLoc); 2265 } 2266 2267 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2268 /// one entry in the base class list of a class specifier, for 2269 /// example: 2270 /// class foo : public bar, virtual private baz { 2271 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2272 BaseResult 2273 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2274 ParsedAttributes &Attributes, 2275 bool Virtual, AccessSpecifier Access, 2276 ParsedType basetype, SourceLocation BaseLoc, 2277 SourceLocation EllipsisLoc) { 2278 if (!classdecl) 2279 return true; 2280 2281 AdjustDeclIfTemplate(classdecl); 2282 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2283 if (!Class) 2284 return true; 2285 2286 // We haven't yet attached the base specifiers. 2287 Class->setIsParsingBaseSpecifiers(); 2288 2289 // We do not support any C++11 attributes on base-specifiers yet. 2290 // Diagnose any attributes we see. 2291 if (!Attributes.empty()) { 2292 for (AttributeList *Attr = Attributes.getList(); Attr; 2293 Attr = Attr->getNext()) { 2294 if (Attr->isInvalid() || 2295 Attr->getKind() == AttributeList::IgnoredAttribute) 2296 continue; 2297 Diag(Attr->getLoc(), 2298 Attr->getKind() == AttributeList::UnknownAttribute 2299 ? diag::warn_unknown_attribute_ignored 2300 : diag::err_base_specifier_attribute) 2301 << Attr->getName(); 2302 } 2303 } 2304 2305 TypeSourceInfo *TInfo = nullptr; 2306 GetTypeFromParser(basetype, &TInfo); 2307 2308 if (EllipsisLoc.isInvalid() && 2309 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2310 UPPC_BaseType)) 2311 return true; 2312 2313 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2314 Virtual, Access, TInfo, 2315 EllipsisLoc)) 2316 return BaseSpec; 2317 else 2318 Class->setInvalidDecl(); 2319 2320 return true; 2321 } 2322 2323 /// Use small set to collect indirect bases. As this is only used 2324 /// locally, there's no need to abstract the small size parameter. 2325 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2326 2327 /// Recursively add the bases of Type. Don't add Type itself. 2328 static void 2329 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2330 const QualType &Type) 2331 { 2332 // Even though the incoming type is a base, it might not be 2333 // a class -- it could be a template parm, for instance. 2334 if (auto Rec = Type->getAs<RecordType>()) { 2335 auto Decl = Rec->getAsCXXRecordDecl(); 2336 2337 // Iterate over its bases. 2338 for (const auto &BaseSpec : Decl->bases()) { 2339 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2340 .getUnqualifiedType(); 2341 if (Set.insert(Base).second) 2342 // If we've not already seen it, recurse. 2343 NoteIndirectBases(Context, Set, Base); 2344 } 2345 } 2346 } 2347 2348 /// Performs the actual work of attaching the given base class 2349 /// specifiers to a C++ class. 2350 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2351 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2352 if (Bases.empty()) 2353 return false; 2354 2355 // Used to keep track of which base types we have already seen, so 2356 // that we can properly diagnose redundant direct base types. Note 2357 // that the key is always the unqualified canonical type of the base 2358 // class. 2359 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2360 2361 // Used to track indirect bases so we can see if a direct base is 2362 // ambiguous. 2363 IndirectBaseSet IndirectBaseTypes; 2364 2365 // Copy non-redundant base specifiers into permanent storage. 2366 unsigned NumGoodBases = 0; 2367 bool Invalid = false; 2368 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2369 QualType NewBaseType 2370 = Context.getCanonicalType(Bases[idx]->getType()); 2371 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2372 2373 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2374 if (KnownBase) { 2375 // C++ [class.mi]p3: 2376 // A class shall not be specified as a direct base class of a 2377 // derived class more than once. 2378 Diag(Bases[idx]->getLocStart(), 2379 diag::err_duplicate_base_class) 2380 << KnownBase->getType() 2381 << Bases[idx]->getSourceRange(); 2382 2383 // Delete the duplicate base class specifier; we're going to 2384 // overwrite its pointer later. 2385 Context.Deallocate(Bases[idx]); 2386 2387 Invalid = true; 2388 } else { 2389 // Okay, add this new base class. 2390 KnownBase = Bases[idx]; 2391 Bases[NumGoodBases++] = Bases[idx]; 2392 2393 // Note this base's direct & indirect bases, if there could be ambiguity. 2394 if (Bases.size() > 1) 2395 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2396 2397 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2398 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2399 if (Class->isInterface() && 2400 (!RD->isInterfaceLike() || 2401 KnownBase->getAccessSpecifier() != AS_public)) { 2402 // The Microsoft extension __interface does not permit bases that 2403 // are not themselves public interfaces. 2404 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2405 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2406 << RD->getSourceRange(); 2407 Invalid = true; 2408 } 2409 if (RD->hasAttr<WeakAttr>()) 2410 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2411 } 2412 } 2413 } 2414 2415 // Attach the remaining base class specifiers to the derived class. 2416 Class->setBases(Bases.data(), NumGoodBases); 2417 2418 // Check that the only base classes that are duplicate are virtual. 2419 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2420 // Check whether this direct base is inaccessible due to ambiguity. 2421 QualType BaseType = Bases[idx]->getType(); 2422 2423 // Skip all dependent types in templates being used as base specifiers. 2424 // Checks below assume that the base specifier is a CXXRecord. 2425 if (BaseType->isDependentType()) 2426 continue; 2427 2428 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2429 .getUnqualifiedType(); 2430 2431 if (IndirectBaseTypes.count(CanonicalBase)) { 2432 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2433 /*DetectVirtual=*/true); 2434 bool found 2435 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2436 assert(found); 2437 (void)found; 2438 2439 if (Paths.isAmbiguous(CanonicalBase)) 2440 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2441 << BaseType << getAmbiguousPathsDisplayString(Paths) 2442 << Bases[idx]->getSourceRange(); 2443 else 2444 assert(Bases[idx]->isVirtual()); 2445 } 2446 2447 // Delete the base class specifier, since its data has been copied 2448 // into the CXXRecordDecl. 2449 Context.Deallocate(Bases[idx]); 2450 } 2451 2452 return Invalid; 2453 } 2454 2455 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2456 /// class, after checking whether there are any duplicate base 2457 /// classes. 2458 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2459 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2460 if (!ClassDecl || Bases.empty()) 2461 return; 2462 2463 AdjustDeclIfTemplate(ClassDecl); 2464 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2465 } 2466 2467 /// Determine whether the type \p Derived is a C++ class that is 2468 /// derived from the type \p Base. 2469 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2470 if (!getLangOpts().CPlusPlus) 2471 return false; 2472 2473 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2474 if (!DerivedRD) 2475 return false; 2476 2477 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2478 if (!BaseRD) 2479 return false; 2480 2481 // If either the base or the derived type is invalid, don't try to 2482 // check whether one is derived from the other. 2483 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2484 return false; 2485 2486 // FIXME: In a modules build, do we need the entire path to be visible for us 2487 // to be able to use the inheritance relationship? 2488 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2489 return false; 2490 2491 return DerivedRD->isDerivedFrom(BaseRD); 2492 } 2493 2494 /// Determine whether the type \p Derived is a C++ class that is 2495 /// derived from the type \p Base. 2496 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2497 CXXBasePaths &Paths) { 2498 if (!getLangOpts().CPlusPlus) 2499 return false; 2500 2501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2502 if (!DerivedRD) 2503 return false; 2504 2505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2506 if (!BaseRD) 2507 return false; 2508 2509 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2510 return false; 2511 2512 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2513 } 2514 2515 static void BuildBasePathArray(const CXXBasePath &Path, 2516 CXXCastPath &BasePathArray) { 2517 // We first go backward and check if we have a virtual base. 2518 // FIXME: It would be better if CXXBasePath had the base specifier for 2519 // the nearest virtual base. 2520 unsigned Start = 0; 2521 for (unsigned I = Path.size(); I != 0; --I) { 2522 if (Path[I - 1].Base->isVirtual()) { 2523 Start = I - 1; 2524 break; 2525 } 2526 } 2527 2528 // Now add all bases. 2529 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2530 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2531 } 2532 2533 2534 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2535 CXXCastPath &BasePathArray) { 2536 assert(BasePathArray.empty() && "Base path array must be empty!"); 2537 assert(Paths.isRecordingPaths() && "Must record paths!"); 2538 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2539 } 2540 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2541 /// conversion (where Derived and Base are class types) is 2542 /// well-formed, meaning that the conversion is unambiguous (and 2543 /// that all of the base classes are accessible). Returns true 2544 /// and emits a diagnostic if the code is ill-formed, returns false 2545 /// otherwise. Loc is the location where this routine should point to 2546 /// if there is an error, and Range is the source range to highlight 2547 /// if there is an error. 2548 /// 2549 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2550 /// diagnostic for the respective type of error will be suppressed, but the 2551 /// check for ill-formed code will still be performed. 2552 bool 2553 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2554 unsigned InaccessibleBaseID, 2555 unsigned AmbigiousBaseConvID, 2556 SourceLocation Loc, SourceRange Range, 2557 DeclarationName Name, 2558 CXXCastPath *BasePath, 2559 bool IgnoreAccess) { 2560 // First, determine whether the path from Derived to Base is 2561 // ambiguous. This is slightly more expensive than checking whether 2562 // the Derived to Base conversion exists, because here we need to 2563 // explore multiple paths to determine if there is an ambiguity. 2564 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2565 /*DetectVirtual=*/false); 2566 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2567 if (!DerivationOkay) 2568 return true; 2569 2570 const CXXBasePath *Path = nullptr; 2571 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2572 Path = &Paths.front(); 2573 2574 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2575 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2576 // user to access such bases. 2577 if (!Path && getLangOpts().MSVCCompat) { 2578 for (const CXXBasePath &PossiblePath : Paths) { 2579 if (PossiblePath.size() == 1) { 2580 Path = &PossiblePath; 2581 if (AmbigiousBaseConvID) 2582 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2583 << Base << Derived << Range; 2584 break; 2585 } 2586 } 2587 } 2588 2589 if (Path) { 2590 if (!IgnoreAccess) { 2591 // Check that the base class can be accessed. 2592 switch ( 2593 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2594 case AR_inaccessible: 2595 return true; 2596 case AR_accessible: 2597 case AR_dependent: 2598 case AR_delayed: 2599 break; 2600 } 2601 } 2602 2603 // Build a base path if necessary. 2604 if (BasePath) 2605 ::BuildBasePathArray(*Path, *BasePath); 2606 return false; 2607 } 2608 2609 if (AmbigiousBaseConvID) { 2610 // We know that the derived-to-base conversion is ambiguous, and 2611 // we're going to produce a diagnostic. Perform the derived-to-base 2612 // search just one more time to compute all of the possible paths so 2613 // that we can print them out. This is more expensive than any of 2614 // the previous derived-to-base checks we've done, but at this point 2615 // performance isn't as much of an issue. 2616 Paths.clear(); 2617 Paths.setRecordingPaths(true); 2618 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2619 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2620 (void)StillOkay; 2621 2622 // Build up a textual representation of the ambiguous paths, e.g., 2623 // D -> B -> A, that will be used to illustrate the ambiguous 2624 // conversions in the diagnostic. We only print one of the paths 2625 // to each base class subobject. 2626 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2627 2628 Diag(Loc, AmbigiousBaseConvID) 2629 << Derived << Base << PathDisplayStr << Range << Name; 2630 } 2631 return true; 2632 } 2633 2634 bool 2635 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2636 SourceLocation Loc, SourceRange Range, 2637 CXXCastPath *BasePath, 2638 bool IgnoreAccess) { 2639 return CheckDerivedToBaseConversion( 2640 Derived, Base, diag::err_upcast_to_inaccessible_base, 2641 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2642 BasePath, IgnoreAccess); 2643 } 2644 2645 2646 /// Builds a string representing ambiguous paths from a 2647 /// specific derived class to different subobjects of the same base 2648 /// class. 2649 /// 2650 /// This function builds a string that can be used in error messages 2651 /// to show the different paths that one can take through the 2652 /// inheritance hierarchy to go from the derived class to different 2653 /// subobjects of a base class. The result looks something like this: 2654 /// @code 2655 /// struct D -> struct B -> struct A 2656 /// struct D -> struct C -> struct A 2657 /// @endcode 2658 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2659 std::string PathDisplayStr; 2660 std::set<unsigned> DisplayedPaths; 2661 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2662 Path != Paths.end(); ++Path) { 2663 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2664 // We haven't displayed a path to this particular base 2665 // class subobject yet. 2666 PathDisplayStr += "\n "; 2667 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2668 for (CXXBasePath::const_iterator Element = Path->begin(); 2669 Element != Path->end(); ++Element) 2670 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2671 } 2672 } 2673 2674 return PathDisplayStr; 2675 } 2676 2677 //===----------------------------------------------------------------------===// 2678 // C++ class member Handling 2679 //===----------------------------------------------------------------------===// 2680 2681 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2682 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2683 SourceLocation ASLoc, 2684 SourceLocation ColonLoc, 2685 AttributeList *Attrs) { 2686 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2687 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2688 ASLoc, ColonLoc); 2689 CurContext->addHiddenDecl(ASDecl); 2690 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2691 } 2692 2693 /// CheckOverrideControl - Check C++11 override control semantics. 2694 void Sema::CheckOverrideControl(NamedDecl *D) { 2695 if (D->isInvalidDecl()) 2696 return; 2697 2698 // We only care about "override" and "final" declarations. 2699 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2700 return; 2701 2702 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2703 2704 // We can't check dependent instance methods. 2705 if (MD && MD->isInstance() && 2706 (MD->getParent()->hasAnyDependentBases() || 2707 MD->getType()->isDependentType())) 2708 return; 2709 2710 if (MD && !MD->isVirtual()) { 2711 // If we have a non-virtual method, check if if hides a virtual method. 2712 // (In that case, it's most likely the method has the wrong type.) 2713 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2714 FindHiddenVirtualMethods(MD, OverloadedMethods); 2715 2716 if (!OverloadedMethods.empty()) { 2717 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2718 Diag(OA->getLocation(), 2719 diag::override_keyword_hides_virtual_member_function) 2720 << "override" << (OverloadedMethods.size() > 1); 2721 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2722 Diag(FA->getLocation(), 2723 diag::override_keyword_hides_virtual_member_function) 2724 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2725 << (OverloadedMethods.size() > 1); 2726 } 2727 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2728 MD->setInvalidDecl(); 2729 return; 2730 } 2731 // Fall through into the general case diagnostic. 2732 // FIXME: We might want to attempt typo correction here. 2733 } 2734 2735 if (!MD || !MD->isVirtual()) { 2736 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2737 Diag(OA->getLocation(), 2738 diag::override_keyword_only_allowed_on_virtual_member_functions) 2739 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2740 D->dropAttr<OverrideAttr>(); 2741 } 2742 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2743 Diag(FA->getLocation(), 2744 diag::override_keyword_only_allowed_on_virtual_member_functions) 2745 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2746 << FixItHint::CreateRemoval(FA->getLocation()); 2747 D->dropAttr<FinalAttr>(); 2748 } 2749 return; 2750 } 2751 2752 // C++11 [class.virtual]p5: 2753 // If a function is marked with the virt-specifier override and 2754 // does not override a member function of a base class, the program is 2755 // ill-formed. 2756 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2757 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2758 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2759 << MD->getDeclName(); 2760 } 2761 2762 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2763 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2764 return; 2765 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2766 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2767 return; 2768 2769 SourceLocation Loc = MD->getLocation(); 2770 SourceLocation SpellingLoc = Loc; 2771 if (getSourceManager().isMacroArgExpansion(Loc)) 2772 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2773 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2774 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2775 return; 2776 2777 if (MD->size_overridden_methods() > 0) { 2778 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2779 ? diag::warn_destructor_marked_not_override_overriding 2780 : diag::warn_function_marked_not_override_overriding; 2781 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2782 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2783 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2784 } 2785 } 2786 2787 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2788 /// function overrides a virtual member function marked 'final', according to 2789 /// C++11 [class.virtual]p4. 2790 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2791 const CXXMethodDecl *Old) { 2792 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2793 if (!FA) 2794 return false; 2795 2796 Diag(New->getLocation(), diag::err_final_function_overridden) 2797 << New->getDeclName() 2798 << FA->isSpelledAsSealed(); 2799 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2800 return true; 2801 } 2802 2803 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2804 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2805 // FIXME: Destruction of ObjC lifetime types has side-effects. 2806 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2807 return !RD->isCompleteDefinition() || 2808 !RD->hasTrivialDefaultConstructor() || 2809 !RD->hasTrivialDestructor(); 2810 return false; 2811 } 2812 2813 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2814 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2815 if (it->isDeclspecPropertyAttribute()) 2816 return it; 2817 return nullptr; 2818 } 2819 2820 // Check if there is a field shadowing. 2821 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2822 DeclarationName FieldName, 2823 const CXXRecordDecl *RD) { 2824 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2825 return; 2826 2827 // To record a shadowed field in a base 2828 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2829 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2830 CXXBasePath &Path) { 2831 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2832 // Record an ambiguous path directly 2833 if (Bases.find(Base) != Bases.end()) 2834 return true; 2835 for (const auto Field : Base->lookup(FieldName)) { 2836 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2837 Field->getAccess() != AS_private) { 2838 assert(Field->getAccess() != AS_none); 2839 assert(Bases.find(Base) == Bases.end()); 2840 Bases[Base] = Field; 2841 return true; 2842 } 2843 } 2844 return false; 2845 }; 2846 2847 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2848 /*DetectVirtual=*/true); 2849 if (!RD->lookupInBases(FieldShadowed, Paths)) 2850 return; 2851 2852 for (const auto &P : Paths) { 2853 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2854 auto It = Bases.find(Base); 2855 // Skip duplicated bases 2856 if (It == Bases.end()) 2857 continue; 2858 auto BaseField = It->second; 2859 assert(BaseField->getAccess() != AS_private); 2860 if (AS_none != 2861 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2862 Diag(Loc, diag::warn_shadow_field) 2863 << FieldName << RD << Base; 2864 Diag(BaseField->getLocation(), diag::note_shadow_field); 2865 Bases.erase(It); 2866 } 2867 } 2868 } 2869 2870 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2871 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2872 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2873 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2874 /// present (but parsing it has been deferred). 2875 NamedDecl * 2876 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2877 MultiTemplateParamsArg TemplateParameterLists, 2878 Expr *BW, const VirtSpecifiers &VS, 2879 InClassInitStyle InitStyle) { 2880 const DeclSpec &DS = D.getDeclSpec(); 2881 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2882 DeclarationName Name = NameInfo.getName(); 2883 SourceLocation Loc = NameInfo.getLoc(); 2884 2885 // For anonymous bitfields, the location should point to the type. 2886 if (Loc.isInvalid()) 2887 Loc = D.getLocStart(); 2888 2889 Expr *BitWidth = static_cast<Expr*>(BW); 2890 2891 assert(isa<CXXRecordDecl>(CurContext)); 2892 assert(!DS.isFriendSpecified()); 2893 2894 bool isFunc = D.isDeclarationOfFunction(); 2895 AttributeList *MSPropertyAttr = 2896 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2897 2898 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2899 // The Microsoft extension __interface only permits public member functions 2900 // and prohibits constructors, destructors, operators, non-public member 2901 // functions, static methods and data members. 2902 unsigned InvalidDecl; 2903 bool ShowDeclName = true; 2904 if (!isFunc && 2905 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2906 InvalidDecl = 0; 2907 else if (!isFunc) 2908 InvalidDecl = 1; 2909 else if (AS != AS_public) 2910 InvalidDecl = 2; 2911 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2912 InvalidDecl = 3; 2913 else switch (Name.getNameKind()) { 2914 case DeclarationName::CXXConstructorName: 2915 InvalidDecl = 4; 2916 ShowDeclName = false; 2917 break; 2918 2919 case DeclarationName::CXXDestructorName: 2920 InvalidDecl = 5; 2921 ShowDeclName = false; 2922 break; 2923 2924 case DeclarationName::CXXOperatorName: 2925 case DeclarationName::CXXConversionFunctionName: 2926 InvalidDecl = 6; 2927 break; 2928 2929 default: 2930 InvalidDecl = 0; 2931 break; 2932 } 2933 2934 if (InvalidDecl) { 2935 if (ShowDeclName) 2936 Diag(Loc, diag::err_invalid_member_in_interface) 2937 << (InvalidDecl-1) << Name; 2938 else 2939 Diag(Loc, diag::err_invalid_member_in_interface) 2940 << (InvalidDecl-1) << ""; 2941 return nullptr; 2942 } 2943 } 2944 2945 // C++ 9.2p6: A member shall not be declared to have automatic storage 2946 // duration (auto, register) or with the extern storage-class-specifier. 2947 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2948 // data members and cannot be applied to names declared const or static, 2949 // and cannot be applied to reference members. 2950 switch (DS.getStorageClassSpec()) { 2951 case DeclSpec::SCS_unspecified: 2952 case DeclSpec::SCS_typedef: 2953 case DeclSpec::SCS_static: 2954 break; 2955 case DeclSpec::SCS_mutable: 2956 if (isFunc) { 2957 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2958 2959 // FIXME: It would be nicer if the keyword was ignored only for this 2960 // declarator. Otherwise we could get follow-up errors. 2961 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2962 } 2963 break; 2964 default: 2965 Diag(DS.getStorageClassSpecLoc(), 2966 diag::err_storageclass_invalid_for_member); 2967 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2968 break; 2969 } 2970 2971 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2972 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2973 !isFunc); 2974 2975 if (DS.isConstexprSpecified() && isInstField) { 2976 SemaDiagnosticBuilder B = 2977 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2978 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2979 if (InitStyle == ICIS_NoInit) { 2980 B << 0 << 0; 2981 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2982 B << FixItHint::CreateRemoval(ConstexprLoc); 2983 else { 2984 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2985 D.getMutableDeclSpec().ClearConstexprSpec(); 2986 const char *PrevSpec; 2987 unsigned DiagID; 2988 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2989 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2990 (void)Failed; 2991 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2992 } 2993 } else { 2994 B << 1; 2995 const char *PrevSpec; 2996 unsigned DiagID; 2997 if (D.getMutableDeclSpec().SetStorageClassSpec( 2998 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2999 Context.getPrintingPolicy())) { 3000 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3001 "This is the only DeclSpec that should fail to be applied"); 3002 B << 1; 3003 } else { 3004 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3005 isInstField = false; 3006 } 3007 } 3008 } 3009 3010 NamedDecl *Member; 3011 if (isInstField) { 3012 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3013 3014 // Data members must have identifiers for names. 3015 if (!Name.isIdentifier()) { 3016 Diag(Loc, diag::err_bad_variable_name) 3017 << Name; 3018 return nullptr; 3019 } 3020 3021 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3022 3023 // Member field could not be with "template" keyword. 3024 // So TemplateParameterLists should be empty in this case. 3025 if (TemplateParameterLists.size()) { 3026 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3027 if (TemplateParams->size()) { 3028 // There is no such thing as a member field template. 3029 Diag(D.getIdentifierLoc(), diag::err_template_member) 3030 << II 3031 << SourceRange(TemplateParams->getTemplateLoc(), 3032 TemplateParams->getRAngleLoc()); 3033 } else { 3034 // There is an extraneous 'template<>' for this member. 3035 Diag(TemplateParams->getTemplateLoc(), 3036 diag::err_template_member_noparams) 3037 << II 3038 << SourceRange(TemplateParams->getTemplateLoc(), 3039 TemplateParams->getRAngleLoc()); 3040 } 3041 return nullptr; 3042 } 3043 3044 if (SS.isSet() && !SS.isInvalid()) { 3045 // The user provided a superfluous scope specifier inside a class 3046 // definition: 3047 // 3048 // class X { 3049 // int X::member; 3050 // }; 3051 if (DeclContext *DC = computeDeclContext(SS, false)) 3052 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3053 D.getName().getKind() == 3054 UnqualifiedIdKind::IK_TemplateId); 3055 else 3056 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3057 << Name << SS.getRange(); 3058 3059 SS.clear(); 3060 } 3061 3062 if (MSPropertyAttr) { 3063 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3064 BitWidth, InitStyle, AS, MSPropertyAttr); 3065 if (!Member) 3066 return nullptr; 3067 isInstField = false; 3068 } else { 3069 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3070 BitWidth, InitStyle, AS); 3071 if (!Member) 3072 return nullptr; 3073 } 3074 3075 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3076 } else { 3077 Member = HandleDeclarator(S, D, TemplateParameterLists); 3078 if (!Member) 3079 return nullptr; 3080 3081 // Non-instance-fields can't have a bitfield. 3082 if (BitWidth) { 3083 if (Member->isInvalidDecl()) { 3084 // don't emit another diagnostic. 3085 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3086 // C++ 9.6p3: A bit-field shall not be a static member. 3087 // "static member 'A' cannot be a bit-field" 3088 Diag(Loc, diag::err_static_not_bitfield) 3089 << Name << BitWidth->getSourceRange(); 3090 } else if (isa<TypedefDecl>(Member)) { 3091 // "typedef member 'x' cannot be a bit-field" 3092 Diag(Loc, diag::err_typedef_not_bitfield) 3093 << Name << BitWidth->getSourceRange(); 3094 } else { 3095 // A function typedef ("typedef int f(); f a;"). 3096 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3097 Diag(Loc, diag::err_not_integral_type_bitfield) 3098 << Name << cast<ValueDecl>(Member)->getType() 3099 << BitWidth->getSourceRange(); 3100 } 3101 3102 BitWidth = nullptr; 3103 Member->setInvalidDecl(); 3104 } 3105 3106 NamedDecl *NonTemplateMember = Member; 3107 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3108 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3109 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3110 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3111 3112 Member->setAccess(AS); 3113 3114 // If we have declared a member function template or static data member 3115 // template, set the access of the templated declaration as well. 3116 if (NonTemplateMember != Member) 3117 NonTemplateMember->setAccess(AS); 3118 3119 // C++ [temp.deduct.guide]p3: 3120 // A deduction guide [...] for a member class template [shall be 3121 // declared] with the same access [as the template]. 3122 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3123 auto *TD = DG->getDeducedTemplate(); 3124 if (AS != TD->getAccess()) { 3125 Diag(DG->getLocStart(), diag::err_deduction_guide_wrong_access); 3126 Diag(TD->getLocStart(), diag::note_deduction_guide_template_access) 3127 << TD->getAccess(); 3128 const AccessSpecDecl *LastAccessSpec = nullptr; 3129 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3130 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3131 LastAccessSpec = AccessSpec; 3132 } 3133 assert(LastAccessSpec && "differing access with no access specifier"); 3134 Diag(LastAccessSpec->getLocStart(), diag::note_deduction_guide_access) 3135 << AS; 3136 } 3137 } 3138 } 3139 3140 if (VS.isOverrideSpecified()) 3141 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3142 if (VS.isFinalSpecified()) 3143 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3144 VS.isFinalSpelledSealed())); 3145 3146 if (VS.getLastLocation().isValid()) { 3147 // Update the end location of a method that has a virt-specifiers. 3148 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3149 MD->setRangeEnd(VS.getLastLocation()); 3150 } 3151 3152 CheckOverrideControl(Member); 3153 3154 assert((Name || isInstField) && "No identifier for non-field ?"); 3155 3156 if (isInstField) { 3157 FieldDecl *FD = cast<FieldDecl>(Member); 3158 FieldCollector->Add(FD); 3159 3160 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3161 // Remember all explicit private FieldDecls that have a name, no side 3162 // effects and are not part of a dependent type declaration. 3163 if (!FD->isImplicit() && FD->getDeclName() && 3164 FD->getAccess() == AS_private && 3165 !FD->hasAttr<UnusedAttr>() && 3166 !FD->getParent()->isDependentContext() && 3167 !InitializationHasSideEffects(*FD)) 3168 UnusedPrivateFields.insert(FD); 3169 } 3170 } 3171 3172 return Member; 3173 } 3174 3175 namespace { 3176 class UninitializedFieldVisitor 3177 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3178 Sema &S; 3179 // List of Decls to generate a warning on. Also remove Decls that become 3180 // initialized. 3181 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3182 // List of base classes of the record. Classes are removed after their 3183 // initializers. 3184 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3185 // Vector of decls to be removed from the Decl set prior to visiting the 3186 // nodes. These Decls may have been initialized in the prior initializer. 3187 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3188 // If non-null, add a note to the warning pointing back to the constructor. 3189 const CXXConstructorDecl *Constructor; 3190 // Variables to hold state when processing an initializer list. When 3191 // InitList is true, special case initialization of FieldDecls matching 3192 // InitListFieldDecl. 3193 bool InitList; 3194 FieldDecl *InitListFieldDecl; 3195 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3196 3197 public: 3198 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3199 UninitializedFieldVisitor(Sema &S, 3200 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3201 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3202 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3203 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3204 3205 // Returns true if the use of ME is not an uninitialized use. 3206 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3207 bool CheckReferenceOnly) { 3208 llvm::SmallVector<FieldDecl*, 4> Fields; 3209 bool ReferenceField = false; 3210 while (ME) { 3211 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3212 if (!FD) 3213 return false; 3214 Fields.push_back(FD); 3215 if (FD->getType()->isReferenceType()) 3216 ReferenceField = true; 3217 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3218 } 3219 3220 // Binding a reference to an unintialized field is not an 3221 // uninitialized use. 3222 if (CheckReferenceOnly && !ReferenceField) 3223 return true; 3224 3225 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3226 // Discard the first field since it is the field decl that is being 3227 // initialized. 3228 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3229 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3230 } 3231 3232 for (auto UsedIter = UsedFieldIndex.begin(), 3233 UsedEnd = UsedFieldIndex.end(), 3234 OrigIter = InitFieldIndex.begin(), 3235 OrigEnd = InitFieldIndex.end(); 3236 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3237 if (*UsedIter < *OrigIter) 3238 return true; 3239 if (*UsedIter > *OrigIter) 3240 break; 3241 } 3242 3243 return false; 3244 } 3245 3246 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3247 bool AddressOf) { 3248 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3249 return; 3250 3251 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3252 // or union. 3253 MemberExpr *FieldME = ME; 3254 3255 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3256 3257 Expr *Base = ME; 3258 while (MemberExpr *SubME = 3259 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3260 3261 if (isa<VarDecl>(SubME->getMemberDecl())) 3262 return; 3263 3264 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3265 if (!FD->isAnonymousStructOrUnion()) 3266 FieldME = SubME; 3267 3268 if (!FieldME->getType().isPODType(S.Context)) 3269 AllPODFields = false; 3270 3271 Base = SubME->getBase(); 3272 } 3273 3274 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3275 return; 3276 3277 if (AddressOf && AllPODFields) 3278 return; 3279 3280 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3281 3282 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3283 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3284 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3285 } 3286 3287 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3288 QualType T = BaseCast->getType(); 3289 if (T->isPointerType() && 3290 BaseClasses.count(T->getPointeeType())) { 3291 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3292 << T->getPointeeType() << FoundVD; 3293 } 3294 } 3295 } 3296 3297 if (!Decls.count(FoundVD)) 3298 return; 3299 3300 const bool IsReference = FoundVD->getType()->isReferenceType(); 3301 3302 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3303 // Special checking for initializer lists. 3304 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3305 return; 3306 } 3307 } else { 3308 // Prevent double warnings on use of unbounded references. 3309 if (CheckReferenceOnly && !IsReference) 3310 return; 3311 } 3312 3313 unsigned diag = IsReference 3314 ? diag::warn_reference_field_is_uninit 3315 : diag::warn_field_is_uninit; 3316 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3317 if (Constructor) 3318 S.Diag(Constructor->getLocation(), 3319 diag::note_uninit_in_this_constructor) 3320 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3321 3322 } 3323 3324 void HandleValue(Expr *E, bool AddressOf) { 3325 E = E->IgnoreParens(); 3326 3327 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3328 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3329 AddressOf /*AddressOf*/); 3330 return; 3331 } 3332 3333 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3334 Visit(CO->getCond()); 3335 HandleValue(CO->getTrueExpr(), AddressOf); 3336 HandleValue(CO->getFalseExpr(), AddressOf); 3337 return; 3338 } 3339 3340 if (BinaryConditionalOperator *BCO = 3341 dyn_cast<BinaryConditionalOperator>(E)) { 3342 Visit(BCO->getCond()); 3343 HandleValue(BCO->getFalseExpr(), AddressOf); 3344 return; 3345 } 3346 3347 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3348 HandleValue(OVE->getSourceExpr(), AddressOf); 3349 return; 3350 } 3351 3352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3353 switch (BO->getOpcode()) { 3354 default: 3355 break; 3356 case(BO_PtrMemD): 3357 case(BO_PtrMemI): 3358 HandleValue(BO->getLHS(), AddressOf); 3359 Visit(BO->getRHS()); 3360 return; 3361 case(BO_Comma): 3362 Visit(BO->getLHS()); 3363 HandleValue(BO->getRHS(), AddressOf); 3364 return; 3365 } 3366 } 3367 3368 Visit(E); 3369 } 3370 3371 void CheckInitListExpr(InitListExpr *ILE) { 3372 InitFieldIndex.push_back(0); 3373 for (auto Child : ILE->children()) { 3374 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3375 CheckInitListExpr(SubList); 3376 } else { 3377 Visit(Child); 3378 } 3379 ++InitFieldIndex.back(); 3380 } 3381 InitFieldIndex.pop_back(); 3382 } 3383 3384 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3385 FieldDecl *Field, const Type *BaseClass) { 3386 // Remove Decls that may have been initialized in the previous 3387 // initializer. 3388 for (ValueDecl* VD : DeclsToRemove) 3389 Decls.erase(VD); 3390 DeclsToRemove.clear(); 3391 3392 Constructor = FieldConstructor; 3393 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3394 3395 if (ILE && Field) { 3396 InitList = true; 3397 InitListFieldDecl = Field; 3398 InitFieldIndex.clear(); 3399 CheckInitListExpr(ILE); 3400 } else { 3401 InitList = false; 3402 Visit(E); 3403 } 3404 3405 if (Field) 3406 Decls.erase(Field); 3407 if (BaseClass) 3408 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3409 } 3410 3411 void VisitMemberExpr(MemberExpr *ME) { 3412 // All uses of unbounded reference fields will warn. 3413 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3414 } 3415 3416 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3417 if (E->getCastKind() == CK_LValueToRValue) { 3418 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3419 return; 3420 } 3421 3422 Inherited::VisitImplicitCastExpr(E); 3423 } 3424 3425 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3426 if (E->getConstructor()->isCopyConstructor()) { 3427 Expr *ArgExpr = E->getArg(0); 3428 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3429 if (ILE->getNumInits() == 1) 3430 ArgExpr = ILE->getInit(0); 3431 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3432 if (ICE->getCastKind() == CK_NoOp) 3433 ArgExpr = ICE->getSubExpr(); 3434 HandleValue(ArgExpr, false /*AddressOf*/); 3435 return; 3436 } 3437 Inherited::VisitCXXConstructExpr(E); 3438 } 3439 3440 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3441 Expr *Callee = E->getCallee(); 3442 if (isa<MemberExpr>(Callee)) { 3443 HandleValue(Callee, false /*AddressOf*/); 3444 for (auto Arg : E->arguments()) 3445 Visit(Arg); 3446 return; 3447 } 3448 3449 Inherited::VisitCXXMemberCallExpr(E); 3450 } 3451 3452 void VisitCallExpr(CallExpr *E) { 3453 // Treat std::move as a use. 3454 if (E->isCallToStdMove()) { 3455 HandleValue(E->getArg(0), /*AddressOf=*/false); 3456 return; 3457 } 3458 3459 Inherited::VisitCallExpr(E); 3460 } 3461 3462 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3463 Expr *Callee = E->getCallee(); 3464 3465 if (isa<UnresolvedLookupExpr>(Callee)) 3466 return Inherited::VisitCXXOperatorCallExpr(E); 3467 3468 Visit(Callee); 3469 for (auto Arg : E->arguments()) 3470 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3471 } 3472 3473 void VisitBinaryOperator(BinaryOperator *E) { 3474 // If a field assignment is detected, remove the field from the 3475 // uninitiailized field set. 3476 if (E->getOpcode() == BO_Assign) 3477 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3478 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3479 if (!FD->getType()->isReferenceType()) 3480 DeclsToRemove.push_back(FD); 3481 3482 if (E->isCompoundAssignmentOp()) { 3483 HandleValue(E->getLHS(), false /*AddressOf*/); 3484 Visit(E->getRHS()); 3485 return; 3486 } 3487 3488 Inherited::VisitBinaryOperator(E); 3489 } 3490 3491 void VisitUnaryOperator(UnaryOperator *E) { 3492 if (E->isIncrementDecrementOp()) { 3493 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3494 return; 3495 } 3496 if (E->getOpcode() == UO_AddrOf) { 3497 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3498 HandleValue(ME->getBase(), true /*AddressOf*/); 3499 return; 3500 } 3501 } 3502 3503 Inherited::VisitUnaryOperator(E); 3504 } 3505 }; 3506 3507 // Diagnose value-uses of fields to initialize themselves, e.g. 3508 // foo(foo) 3509 // where foo is not also a parameter to the constructor. 3510 // Also diagnose across field uninitialized use such as 3511 // x(y), y(x) 3512 // TODO: implement -Wuninitialized and fold this into that framework. 3513 static void DiagnoseUninitializedFields( 3514 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3515 3516 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3517 Constructor->getLocation())) { 3518 return; 3519 } 3520 3521 if (Constructor->isInvalidDecl()) 3522 return; 3523 3524 const CXXRecordDecl *RD = Constructor->getParent(); 3525 3526 if (RD->getDescribedClassTemplate()) 3527 return; 3528 3529 // Holds fields that are uninitialized. 3530 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3531 3532 // At the beginning, all fields are uninitialized. 3533 for (auto *I : RD->decls()) { 3534 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3535 UninitializedFields.insert(FD); 3536 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3537 UninitializedFields.insert(IFD->getAnonField()); 3538 } 3539 } 3540 3541 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3542 for (auto I : RD->bases()) 3543 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3544 3545 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3546 return; 3547 3548 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3549 UninitializedFields, 3550 UninitializedBaseClasses); 3551 3552 for (const auto *FieldInit : Constructor->inits()) { 3553 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3554 break; 3555 3556 Expr *InitExpr = FieldInit->getInit(); 3557 if (!InitExpr) 3558 continue; 3559 3560 if (CXXDefaultInitExpr *Default = 3561 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3562 InitExpr = Default->getExpr(); 3563 if (!InitExpr) 3564 continue; 3565 // In class initializers will point to the constructor. 3566 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3567 FieldInit->getAnyMember(), 3568 FieldInit->getBaseClass()); 3569 } else { 3570 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3571 FieldInit->getAnyMember(), 3572 FieldInit->getBaseClass()); 3573 } 3574 } 3575 } 3576 } // namespace 3577 3578 /// Enter a new C++ default initializer scope. After calling this, the 3579 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3580 /// parsing or instantiating the initializer failed. 3581 void Sema::ActOnStartCXXInClassMemberInitializer() { 3582 // Create a synthetic function scope to represent the call to the constructor 3583 // that notionally surrounds a use of this initializer. 3584 PushFunctionScope(); 3585 } 3586 3587 /// This is invoked after parsing an in-class initializer for a 3588 /// non-static C++ class member, and after instantiating an in-class initializer 3589 /// in a class template. Such actions are deferred until the class is complete. 3590 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3591 SourceLocation InitLoc, 3592 Expr *InitExpr) { 3593 // Pop the notional constructor scope we created earlier. 3594 PopFunctionScopeInfo(nullptr, D); 3595 3596 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3597 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3598 "must set init style when field is created"); 3599 3600 if (!InitExpr) { 3601 D->setInvalidDecl(); 3602 if (FD) 3603 FD->removeInClassInitializer(); 3604 return; 3605 } 3606 3607 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3608 FD->setInvalidDecl(); 3609 FD->removeInClassInitializer(); 3610 return; 3611 } 3612 3613 ExprResult Init = InitExpr; 3614 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3615 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3616 InitializationKind Kind = 3617 FD->getInClassInitStyle() == ICIS_ListInit 3618 ? InitializationKind::CreateDirectList(InitExpr->getLocStart(), 3619 InitExpr->getLocStart(), 3620 InitExpr->getLocEnd()) 3621 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3622 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3623 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3624 if (Init.isInvalid()) { 3625 FD->setInvalidDecl(); 3626 return; 3627 } 3628 } 3629 3630 // C++11 [class.base.init]p7: 3631 // The initialization of each base and member constitutes a 3632 // full-expression. 3633 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3634 if (Init.isInvalid()) { 3635 FD->setInvalidDecl(); 3636 return; 3637 } 3638 3639 InitExpr = Init.get(); 3640 3641 FD->setInClassInitializer(InitExpr); 3642 } 3643 3644 /// Find the direct and/or virtual base specifiers that 3645 /// correspond to the given base type, for use in base initialization 3646 /// within a constructor. 3647 static bool FindBaseInitializer(Sema &SemaRef, 3648 CXXRecordDecl *ClassDecl, 3649 QualType BaseType, 3650 const CXXBaseSpecifier *&DirectBaseSpec, 3651 const CXXBaseSpecifier *&VirtualBaseSpec) { 3652 // First, check for a direct base class. 3653 DirectBaseSpec = nullptr; 3654 for (const auto &Base : ClassDecl->bases()) { 3655 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3656 // We found a direct base of this type. That's what we're 3657 // initializing. 3658 DirectBaseSpec = &Base; 3659 break; 3660 } 3661 } 3662 3663 // Check for a virtual base class. 3664 // FIXME: We might be able to short-circuit this if we know in advance that 3665 // there are no virtual bases. 3666 VirtualBaseSpec = nullptr; 3667 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3668 // We haven't found a base yet; search the class hierarchy for a 3669 // virtual base class. 3670 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3671 /*DetectVirtual=*/false); 3672 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3673 SemaRef.Context.getTypeDeclType(ClassDecl), 3674 BaseType, Paths)) { 3675 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3676 Path != Paths.end(); ++Path) { 3677 if (Path->back().Base->isVirtual()) { 3678 VirtualBaseSpec = Path->back().Base; 3679 break; 3680 } 3681 } 3682 } 3683 } 3684 3685 return DirectBaseSpec || VirtualBaseSpec; 3686 } 3687 3688 /// Handle a C++ member initializer using braced-init-list syntax. 3689 MemInitResult 3690 Sema::ActOnMemInitializer(Decl *ConstructorD, 3691 Scope *S, 3692 CXXScopeSpec &SS, 3693 IdentifierInfo *MemberOrBase, 3694 ParsedType TemplateTypeTy, 3695 const DeclSpec &DS, 3696 SourceLocation IdLoc, 3697 Expr *InitList, 3698 SourceLocation EllipsisLoc) { 3699 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3700 DS, IdLoc, InitList, 3701 EllipsisLoc); 3702 } 3703 3704 /// Handle a C++ member initializer using parentheses syntax. 3705 MemInitResult 3706 Sema::ActOnMemInitializer(Decl *ConstructorD, 3707 Scope *S, 3708 CXXScopeSpec &SS, 3709 IdentifierInfo *MemberOrBase, 3710 ParsedType TemplateTypeTy, 3711 const DeclSpec &DS, 3712 SourceLocation IdLoc, 3713 SourceLocation LParenLoc, 3714 ArrayRef<Expr *> Args, 3715 SourceLocation RParenLoc, 3716 SourceLocation EllipsisLoc) { 3717 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3718 Args, RParenLoc); 3719 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3720 DS, IdLoc, List, EllipsisLoc); 3721 } 3722 3723 namespace { 3724 3725 // Callback to only accept typo corrections that can be a valid C++ member 3726 // intializer: either a non-static field member or a base class. 3727 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3728 public: 3729 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3730 : ClassDecl(ClassDecl) {} 3731 3732 bool ValidateCandidate(const TypoCorrection &candidate) override { 3733 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3734 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3735 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3736 return isa<TypeDecl>(ND); 3737 } 3738 return false; 3739 } 3740 3741 private: 3742 CXXRecordDecl *ClassDecl; 3743 }; 3744 3745 } 3746 3747 /// Handle a C++ member initializer. 3748 MemInitResult 3749 Sema::BuildMemInitializer(Decl *ConstructorD, 3750 Scope *S, 3751 CXXScopeSpec &SS, 3752 IdentifierInfo *MemberOrBase, 3753 ParsedType TemplateTypeTy, 3754 const DeclSpec &DS, 3755 SourceLocation IdLoc, 3756 Expr *Init, 3757 SourceLocation EllipsisLoc) { 3758 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3759 if (!Res.isUsable()) 3760 return true; 3761 Init = Res.get(); 3762 3763 if (!ConstructorD) 3764 return true; 3765 3766 AdjustDeclIfTemplate(ConstructorD); 3767 3768 CXXConstructorDecl *Constructor 3769 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3770 if (!Constructor) { 3771 // The user wrote a constructor initializer on a function that is 3772 // not a C++ constructor. Ignore the error for now, because we may 3773 // have more member initializers coming; we'll diagnose it just 3774 // once in ActOnMemInitializers. 3775 return true; 3776 } 3777 3778 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3779 3780 // C++ [class.base.init]p2: 3781 // Names in a mem-initializer-id are looked up in the scope of the 3782 // constructor's class and, if not found in that scope, are looked 3783 // up in the scope containing the constructor's definition. 3784 // [Note: if the constructor's class contains a member with the 3785 // same name as a direct or virtual base class of the class, a 3786 // mem-initializer-id naming the member or base class and composed 3787 // of a single identifier refers to the class member. A 3788 // mem-initializer-id for the hidden base class may be specified 3789 // using a qualified name. ] 3790 if (!SS.getScopeRep() && !TemplateTypeTy) { 3791 // Look for a member, first. 3792 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3793 if (!Result.empty()) { 3794 ValueDecl *Member; 3795 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3796 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3797 if (EllipsisLoc.isValid()) 3798 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3799 << MemberOrBase 3800 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3801 3802 return BuildMemberInitializer(Member, Init, IdLoc); 3803 } 3804 } 3805 } 3806 // It didn't name a member, so see if it names a class. 3807 QualType BaseType; 3808 TypeSourceInfo *TInfo = nullptr; 3809 3810 if (TemplateTypeTy) { 3811 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3812 } else if (DS.getTypeSpecType() == TST_decltype) { 3813 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3814 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3815 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3816 return true; 3817 } else { 3818 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3819 LookupParsedName(R, S, &SS); 3820 3821 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3822 if (!TyD) { 3823 if (R.isAmbiguous()) return true; 3824 3825 // We don't want access-control diagnostics here. 3826 R.suppressDiagnostics(); 3827 3828 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3829 bool NotUnknownSpecialization = false; 3830 DeclContext *DC = computeDeclContext(SS, false); 3831 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3832 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3833 3834 if (!NotUnknownSpecialization) { 3835 // When the scope specifier can refer to a member of an unknown 3836 // specialization, we take it as a type name. 3837 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3838 SS.getWithLocInContext(Context), 3839 *MemberOrBase, IdLoc); 3840 if (BaseType.isNull()) 3841 return true; 3842 3843 TInfo = Context.CreateTypeSourceInfo(BaseType); 3844 DependentNameTypeLoc TL = 3845 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3846 if (!TL.isNull()) { 3847 TL.setNameLoc(IdLoc); 3848 TL.setElaboratedKeywordLoc(SourceLocation()); 3849 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3850 } 3851 3852 R.clear(); 3853 R.setLookupName(MemberOrBase); 3854 } 3855 } 3856 3857 // If no results were found, try to correct typos. 3858 TypoCorrection Corr; 3859 if (R.empty() && BaseType.isNull() && 3860 (Corr = CorrectTypo( 3861 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3862 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3863 CTK_ErrorRecovery, ClassDecl))) { 3864 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3865 // We have found a non-static data member with a similar 3866 // name to what was typed; complain and initialize that 3867 // member. 3868 diagnoseTypo(Corr, 3869 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3870 << MemberOrBase << true); 3871 return BuildMemberInitializer(Member, Init, IdLoc); 3872 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3873 const CXXBaseSpecifier *DirectBaseSpec; 3874 const CXXBaseSpecifier *VirtualBaseSpec; 3875 if (FindBaseInitializer(*this, ClassDecl, 3876 Context.getTypeDeclType(Type), 3877 DirectBaseSpec, VirtualBaseSpec)) { 3878 // We have found a direct or virtual base class with a 3879 // similar name to what was typed; complain and initialize 3880 // that base class. 3881 diagnoseTypo(Corr, 3882 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3883 << MemberOrBase << false, 3884 PDiag() /*Suppress note, we provide our own.*/); 3885 3886 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3887 : VirtualBaseSpec; 3888 Diag(BaseSpec->getLocStart(), 3889 diag::note_base_class_specified_here) 3890 << BaseSpec->getType() 3891 << BaseSpec->getSourceRange(); 3892 3893 TyD = Type; 3894 } 3895 } 3896 } 3897 3898 if (!TyD && BaseType.isNull()) { 3899 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3900 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3901 return true; 3902 } 3903 } 3904 3905 if (BaseType.isNull()) { 3906 BaseType = Context.getTypeDeclType(TyD); 3907 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3908 if (SS.isSet()) { 3909 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3910 BaseType); 3911 TInfo = Context.CreateTypeSourceInfo(BaseType); 3912 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3913 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3914 TL.setElaboratedKeywordLoc(SourceLocation()); 3915 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3916 } 3917 } 3918 } 3919 3920 if (!TInfo) 3921 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3922 3923 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3924 } 3925 3926 /// Checks a member initializer expression for cases where reference (or 3927 /// pointer) members are bound to by-value parameters (or their addresses). 3928 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3929 Expr *Init, 3930 SourceLocation IdLoc) { 3931 QualType MemberTy = Member->getType(); 3932 3933 // We only handle pointers and references currently. 3934 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3935 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3936 return; 3937 3938 const bool IsPointer = MemberTy->isPointerType(); 3939 if (IsPointer) { 3940 if (const UnaryOperator *Op 3941 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3942 // The only case we're worried about with pointers requires taking the 3943 // address. 3944 if (Op->getOpcode() != UO_AddrOf) 3945 return; 3946 3947 Init = Op->getSubExpr(); 3948 } else { 3949 // We only handle address-of expression initializers for pointers. 3950 return; 3951 } 3952 } 3953 3954 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3955 // We only warn when referring to a non-reference parameter declaration. 3956 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3957 if (!Parameter || Parameter->getType()->isReferenceType()) 3958 return; 3959 3960 S.Diag(Init->getExprLoc(), 3961 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3962 : diag::warn_bind_ref_member_to_parameter) 3963 << Member << Parameter << Init->getSourceRange(); 3964 } else { 3965 // Other initializers are fine. 3966 return; 3967 } 3968 3969 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3970 << (unsigned)IsPointer; 3971 } 3972 3973 MemInitResult 3974 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3975 SourceLocation IdLoc) { 3976 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3977 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3978 assert((DirectMember || IndirectMember) && 3979 "Member must be a FieldDecl or IndirectFieldDecl"); 3980 3981 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3982 return true; 3983 3984 if (Member->isInvalidDecl()) 3985 return true; 3986 3987 MultiExprArg Args; 3988 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3989 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3990 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3991 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3992 } else { 3993 // Template instantiation doesn't reconstruct ParenListExprs for us. 3994 Args = Init; 3995 } 3996 3997 SourceRange InitRange = Init->getSourceRange(); 3998 3999 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4000 // Can't check initialization for a member of dependent type or when 4001 // any of the arguments are type-dependent expressions. 4002 DiscardCleanupsInEvaluationContext(); 4003 } else { 4004 bool InitList = false; 4005 if (isa<InitListExpr>(Init)) { 4006 InitList = true; 4007 Args = Init; 4008 } 4009 4010 // Initialize the member. 4011 InitializedEntity MemberEntity = 4012 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4013 : InitializedEntity::InitializeMember(IndirectMember, 4014 nullptr); 4015 InitializationKind Kind = 4016 InitList ? InitializationKind::CreateDirectList( 4017 IdLoc, Init->getLocStart(), Init->getLocEnd()) 4018 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4019 InitRange.getEnd()); 4020 4021 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4022 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4023 nullptr); 4024 if (MemberInit.isInvalid()) 4025 return true; 4026 4027 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 4028 4029 // C++11 [class.base.init]p7: 4030 // The initialization of each base and member constitutes a 4031 // full-expression. 4032 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 4033 if (MemberInit.isInvalid()) 4034 return true; 4035 4036 Init = MemberInit.get(); 4037 } 4038 4039 if (DirectMember) { 4040 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4041 InitRange.getBegin(), Init, 4042 InitRange.getEnd()); 4043 } else { 4044 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4045 InitRange.getBegin(), Init, 4046 InitRange.getEnd()); 4047 } 4048 } 4049 4050 MemInitResult 4051 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4052 CXXRecordDecl *ClassDecl) { 4053 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4054 if (!LangOpts.CPlusPlus11) 4055 return Diag(NameLoc, diag::err_delegating_ctor) 4056 << TInfo->getTypeLoc().getLocalSourceRange(); 4057 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4058 4059 bool InitList = true; 4060 MultiExprArg Args = Init; 4061 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4062 InitList = false; 4063 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4064 } 4065 4066 SourceRange InitRange = Init->getSourceRange(); 4067 // Initialize the object. 4068 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4069 QualType(ClassDecl->getTypeForDecl(), 0)); 4070 InitializationKind Kind = 4071 InitList ? InitializationKind::CreateDirectList( 4072 NameLoc, Init->getLocStart(), Init->getLocEnd()) 4073 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4074 InitRange.getEnd()); 4075 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4076 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4077 Args, nullptr); 4078 if (DelegationInit.isInvalid()) 4079 return true; 4080 4081 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4082 "Delegating constructor with no target?"); 4083 4084 // C++11 [class.base.init]p7: 4085 // The initialization of each base and member constitutes a 4086 // full-expression. 4087 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4088 InitRange.getBegin()); 4089 if (DelegationInit.isInvalid()) 4090 return true; 4091 4092 // If we are in a dependent context, template instantiation will 4093 // perform this type-checking again. Just save the arguments that we 4094 // received in a ParenListExpr. 4095 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4096 // of the information that we have about the base 4097 // initializer. However, deconstructing the ASTs is a dicey process, 4098 // and this approach is far more likely to get the corner cases right. 4099 if (CurContext->isDependentContext()) 4100 DelegationInit = Init; 4101 4102 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4103 DelegationInit.getAs<Expr>(), 4104 InitRange.getEnd()); 4105 } 4106 4107 MemInitResult 4108 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4109 Expr *Init, CXXRecordDecl *ClassDecl, 4110 SourceLocation EllipsisLoc) { 4111 SourceLocation BaseLoc 4112 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4113 4114 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4115 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4116 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4117 4118 // C++ [class.base.init]p2: 4119 // [...] Unless the mem-initializer-id names a nonstatic data 4120 // member of the constructor's class or a direct or virtual base 4121 // of that class, the mem-initializer is ill-formed. A 4122 // mem-initializer-list can initialize a base class using any 4123 // name that denotes that base class type. 4124 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4125 4126 SourceRange InitRange = Init->getSourceRange(); 4127 if (EllipsisLoc.isValid()) { 4128 // This is a pack expansion. 4129 if (!BaseType->containsUnexpandedParameterPack()) { 4130 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4131 << SourceRange(BaseLoc, InitRange.getEnd()); 4132 4133 EllipsisLoc = SourceLocation(); 4134 } 4135 } else { 4136 // Check for any unexpanded parameter packs. 4137 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4138 return true; 4139 4140 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4141 return true; 4142 } 4143 4144 // Check for direct and virtual base classes. 4145 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4146 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4147 if (!Dependent) { 4148 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4149 BaseType)) 4150 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4151 4152 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4153 VirtualBaseSpec); 4154 4155 // C++ [base.class.init]p2: 4156 // Unless the mem-initializer-id names a nonstatic data member of the 4157 // constructor's class or a direct or virtual base of that class, the 4158 // mem-initializer is ill-formed. 4159 if (!DirectBaseSpec && !VirtualBaseSpec) { 4160 // If the class has any dependent bases, then it's possible that 4161 // one of those types will resolve to the same type as 4162 // BaseType. Therefore, just treat this as a dependent base 4163 // class initialization. FIXME: Should we try to check the 4164 // initialization anyway? It seems odd. 4165 if (ClassDecl->hasAnyDependentBases()) 4166 Dependent = true; 4167 else 4168 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4169 << BaseType << Context.getTypeDeclType(ClassDecl) 4170 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4171 } 4172 } 4173 4174 if (Dependent) { 4175 DiscardCleanupsInEvaluationContext(); 4176 4177 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4178 /*IsVirtual=*/false, 4179 InitRange.getBegin(), Init, 4180 InitRange.getEnd(), EllipsisLoc); 4181 } 4182 4183 // C++ [base.class.init]p2: 4184 // If a mem-initializer-id is ambiguous because it designates both 4185 // a direct non-virtual base class and an inherited virtual base 4186 // class, the mem-initializer is ill-formed. 4187 if (DirectBaseSpec && VirtualBaseSpec) 4188 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4189 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4190 4191 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4192 if (!BaseSpec) 4193 BaseSpec = VirtualBaseSpec; 4194 4195 // Initialize the base. 4196 bool InitList = true; 4197 MultiExprArg Args = Init; 4198 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4199 InitList = false; 4200 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4201 } 4202 4203 InitializedEntity BaseEntity = 4204 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4205 InitializationKind Kind = 4206 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4207 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4208 InitRange.getEnd()); 4209 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4210 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4211 if (BaseInit.isInvalid()) 4212 return true; 4213 4214 // C++11 [class.base.init]p7: 4215 // The initialization of each base and member constitutes a 4216 // full-expression. 4217 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4218 if (BaseInit.isInvalid()) 4219 return true; 4220 4221 // If we are in a dependent context, template instantiation will 4222 // perform this type-checking again. Just save the arguments that we 4223 // received in a ParenListExpr. 4224 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4225 // of the information that we have about the base 4226 // initializer. However, deconstructing the ASTs is a dicey process, 4227 // and this approach is far more likely to get the corner cases right. 4228 if (CurContext->isDependentContext()) 4229 BaseInit = Init; 4230 4231 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4232 BaseSpec->isVirtual(), 4233 InitRange.getBegin(), 4234 BaseInit.getAs<Expr>(), 4235 InitRange.getEnd(), EllipsisLoc); 4236 } 4237 4238 // Create a static_cast\<T&&>(expr). 4239 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4240 if (T.isNull()) T = E->getType(); 4241 QualType TargetType = SemaRef.BuildReferenceType( 4242 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4243 SourceLocation ExprLoc = E->getLocStart(); 4244 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4245 TargetType, ExprLoc); 4246 4247 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4248 SourceRange(ExprLoc, ExprLoc), 4249 E->getSourceRange()).get(); 4250 } 4251 4252 /// ImplicitInitializerKind - How an implicit base or member initializer should 4253 /// initialize its base or member. 4254 enum ImplicitInitializerKind { 4255 IIK_Default, 4256 IIK_Copy, 4257 IIK_Move, 4258 IIK_Inherit 4259 }; 4260 4261 static bool 4262 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4263 ImplicitInitializerKind ImplicitInitKind, 4264 CXXBaseSpecifier *BaseSpec, 4265 bool IsInheritedVirtualBase, 4266 CXXCtorInitializer *&CXXBaseInit) { 4267 InitializedEntity InitEntity 4268 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4269 IsInheritedVirtualBase); 4270 4271 ExprResult BaseInit; 4272 4273 switch (ImplicitInitKind) { 4274 case IIK_Inherit: 4275 case IIK_Default: { 4276 InitializationKind InitKind 4277 = InitializationKind::CreateDefault(Constructor->getLocation()); 4278 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4279 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4280 break; 4281 } 4282 4283 case IIK_Move: 4284 case IIK_Copy: { 4285 bool Moving = ImplicitInitKind == IIK_Move; 4286 ParmVarDecl *Param = Constructor->getParamDecl(0); 4287 QualType ParamType = Param->getType().getNonReferenceType(); 4288 4289 Expr *CopyCtorArg = 4290 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4291 SourceLocation(), Param, false, 4292 Constructor->getLocation(), ParamType, 4293 VK_LValue, nullptr); 4294 4295 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4296 4297 // Cast to the base class to avoid ambiguities. 4298 QualType ArgTy = 4299 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4300 ParamType.getQualifiers()); 4301 4302 if (Moving) { 4303 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4304 } 4305 4306 CXXCastPath BasePath; 4307 BasePath.push_back(BaseSpec); 4308 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4309 CK_UncheckedDerivedToBase, 4310 Moving ? VK_XValue : VK_LValue, 4311 &BasePath).get(); 4312 4313 InitializationKind InitKind 4314 = InitializationKind::CreateDirect(Constructor->getLocation(), 4315 SourceLocation(), SourceLocation()); 4316 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4317 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4318 break; 4319 } 4320 } 4321 4322 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4323 if (BaseInit.isInvalid()) 4324 return true; 4325 4326 CXXBaseInit = 4327 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4328 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4329 SourceLocation()), 4330 BaseSpec->isVirtual(), 4331 SourceLocation(), 4332 BaseInit.getAs<Expr>(), 4333 SourceLocation(), 4334 SourceLocation()); 4335 4336 return false; 4337 } 4338 4339 static bool RefersToRValueRef(Expr *MemRef) { 4340 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4341 return Referenced->getType()->isRValueReferenceType(); 4342 } 4343 4344 static bool 4345 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4346 ImplicitInitializerKind ImplicitInitKind, 4347 FieldDecl *Field, IndirectFieldDecl *Indirect, 4348 CXXCtorInitializer *&CXXMemberInit) { 4349 if (Field->isInvalidDecl()) 4350 return true; 4351 4352 SourceLocation Loc = Constructor->getLocation(); 4353 4354 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4355 bool Moving = ImplicitInitKind == IIK_Move; 4356 ParmVarDecl *Param = Constructor->getParamDecl(0); 4357 QualType ParamType = Param->getType().getNonReferenceType(); 4358 4359 // Suppress copying zero-width bitfields. 4360 if (Field->isZeroLengthBitField(SemaRef.Context)) 4361 return false; 4362 4363 Expr *MemberExprBase = 4364 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4365 SourceLocation(), Param, false, 4366 Loc, ParamType, VK_LValue, nullptr); 4367 4368 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4369 4370 if (Moving) { 4371 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4372 } 4373 4374 // Build a reference to this field within the parameter. 4375 CXXScopeSpec SS; 4376 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4377 Sema::LookupMemberName); 4378 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4379 : cast<ValueDecl>(Field), AS_public); 4380 MemberLookup.resolveKind(); 4381 ExprResult CtorArg 4382 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4383 ParamType, Loc, 4384 /*IsArrow=*/false, 4385 SS, 4386 /*TemplateKWLoc=*/SourceLocation(), 4387 /*FirstQualifierInScope=*/nullptr, 4388 MemberLookup, 4389 /*TemplateArgs=*/nullptr, 4390 /*S*/nullptr); 4391 if (CtorArg.isInvalid()) 4392 return true; 4393 4394 // C++11 [class.copy]p15: 4395 // - if a member m has rvalue reference type T&&, it is direct-initialized 4396 // with static_cast<T&&>(x.m); 4397 if (RefersToRValueRef(CtorArg.get())) { 4398 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4399 } 4400 4401 InitializedEntity Entity = 4402 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4403 /*Implicit*/ true) 4404 : InitializedEntity::InitializeMember(Field, nullptr, 4405 /*Implicit*/ true); 4406 4407 // Direct-initialize to use the copy constructor. 4408 InitializationKind InitKind = 4409 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4410 4411 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4412 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4413 ExprResult MemberInit = 4414 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4415 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4416 if (MemberInit.isInvalid()) 4417 return true; 4418 4419 if (Indirect) 4420 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4421 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4422 else 4423 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4424 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4425 return false; 4426 } 4427 4428 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4429 "Unhandled implicit init kind!"); 4430 4431 QualType FieldBaseElementType = 4432 SemaRef.Context.getBaseElementType(Field->getType()); 4433 4434 if (FieldBaseElementType->isRecordType()) { 4435 InitializedEntity InitEntity = 4436 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4437 /*Implicit*/ true) 4438 : InitializedEntity::InitializeMember(Field, nullptr, 4439 /*Implicit*/ true); 4440 InitializationKind InitKind = 4441 InitializationKind::CreateDefault(Loc); 4442 4443 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4444 ExprResult MemberInit = 4445 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4446 4447 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4448 if (MemberInit.isInvalid()) 4449 return true; 4450 4451 if (Indirect) 4452 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4453 Indirect, Loc, 4454 Loc, 4455 MemberInit.get(), 4456 Loc); 4457 else 4458 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4459 Field, Loc, Loc, 4460 MemberInit.get(), 4461 Loc); 4462 return false; 4463 } 4464 4465 if (!Field->getParent()->isUnion()) { 4466 if (FieldBaseElementType->isReferenceType()) { 4467 SemaRef.Diag(Constructor->getLocation(), 4468 diag::err_uninitialized_member_in_ctor) 4469 << (int)Constructor->isImplicit() 4470 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4471 << 0 << Field->getDeclName(); 4472 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4473 return true; 4474 } 4475 4476 if (FieldBaseElementType.isConstQualified()) { 4477 SemaRef.Diag(Constructor->getLocation(), 4478 diag::err_uninitialized_member_in_ctor) 4479 << (int)Constructor->isImplicit() 4480 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4481 << 1 << Field->getDeclName(); 4482 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4483 return true; 4484 } 4485 } 4486 4487 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4488 // ARC and Weak: 4489 // Default-initialize Objective-C pointers to NULL. 4490 CXXMemberInit 4491 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4492 Loc, Loc, 4493 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4494 Loc); 4495 return false; 4496 } 4497 4498 // Nothing to initialize. 4499 CXXMemberInit = nullptr; 4500 return false; 4501 } 4502 4503 namespace { 4504 struct BaseAndFieldInfo { 4505 Sema &S; 4506 CXXConstructorDecl *Ctor; 4507 bool AnyErrorsInInits; 4508 ImplicitInitializerKind IIK; 4509 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4510 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4511 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4512 4513 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4514 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4515 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4516 if (Ctor->getInheritedConstructor()) 4517 IIK = IIK_Inherit; 4518 else if (Generated && Ctor->isCopyConstructor()) 4519 IIK = IIK_Copy; 4520 else if (Generated && Ctor->isMoveConstructor()) 4521 IIK = IIK_Move; 4522 else 4523 IIK = IIK_Default; 4524 } 4525 4526 bool isImplicitCopyOrMove() const { 4527 switch (IIK) { 4528 case IIK_Copy: 4529 case IIK_Move: 4530 return true; 4531 4532 case IIK_Default: 4533 case IIK_Inherit: 4534 return false; 4535 } 4536 4537 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4538 } 4539 4540 bool addFieldInitializer(CXXCtorInitializer *Init) { 4541 AllToInit.push_back(Init); 4542 4543 // Check whether this initializer makes the field "used". 4544 if (Init->getInit()->HasSideEffects(S.Context)) 4545 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4546 4547 return false; 4548 } 4549 4550 bool isInactiveUnionMember(FieldDecl *Field) { 4551 RecordDecl *Record = Field->getParent(); 4552 if (!Record->isUnion()) 4553 return false; 4554 4555 if (FieldDecl *Active = 4556 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4557 return Active != Field->getCanonicalDecl(); 4558 4559 // In an implicit copy or move constructor, ignore any in-class initializer. 4560 if (isImplicitCopyOrMove()) 4561 return true; 4562 4563 // If there's no explicit initialization, the field is active only if it 4564 // has an in-class initializer... 4565 if (Field->hasInClassInitializer()) 4566 return false; 4567 // ... or it's an anonymous struct or union whose class has an in-class 4568 // initializer. 4569 if (!Field->isAnonymousStructOrUnion()) 4570 return true; 4571 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4572 return !FieldRD->hasInClassInitializer(); 4573 } 4574 4575 /// Determine whether the given field is, or is within, a union member 4576 /// that is inactive (because there was an initializer given for a different 4577 /// member of the union, or because the union was not initialized at all). 4578 bool isWithinInactiveUnionMember(FieldDecl *Field, 4579 IndirectFieldDecl *Indirect) { 4580 if (!Indirect) 4581 return isInactiveUnionMember(Field); 4582 4583 for (auto *C : Indirect->chain()) { 4584 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4585 if (Field && isInactiveUnionMember(Field)) 4586 return true; 4587 } 4588 return false; 4589 } 4590 }; 4591 } 4592 4593 /// Determine whether the given type is an incomplete or zero-lenfgth 4594 /// array type. 4595 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4596 if (T->isIncompleteArrayType()) 4597 return true; 4598 4599 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4600 if (!ArrayT->getSize()) 4601 return true; 4602 4603 T = ArrayT->getElementType(); 4604 } 4605 4606 return false; 4607 } 4608 4609 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4610 FieldDecl *Field, 4611 IndirectFieldDecl *Indirect = nullptr) { 4612 if (Field->isInvalidDecl()) 4613 return false; 4614 4615 // Overwhelmingly common case: we have a direct initializer for this field. 4616 if (CXXCtorInitializer *Init = 4617 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4618 return Info.addFieldInitializer(Init); 4619 4620 // C++11 [class.base.init]p8: 4621 // if the entity is a non-static data member that has a 4622 // brace-or-equal-initializer and either 4623 // -- the constructor's class is a union and no other variant member of that 4624 // union is designated by a mem-initializer-id or 4625 // -- the constructor's class is not a union, and, if the entity is a member 4626 // of an anonymous union, no other member of that union is designated by 4627 // a mem-initializer-id, 4628 // the entity is initialized as specified in [dcl.init]. 4629 // 4630 // We also apply the same rules to handle anonymous structs within anonymous 4631 // unions. 4632 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4633 return false; 4634 4635 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4636 ExprResult DIE = 4637 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4638 if (DIE.isInvalid()) 4639 return true; 4640 CXXCtorInitializer *Init; 4641 if (Indirect) 4642 Init = new (SemaRef.Context) 4643 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4644 SourceLocation(), DIE.get(), SourceLocation()); 4645 else 4646 Init = new (SemaRef.Context) 4647 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4648 SourceLocation(), DIE.get(), SourceLocation()); 4649 return Info.addFieldInitializer(Init); 4650 } 4651 4652 // Don't initialize incomplete or zero-length arrays. 4653 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4654 return false; 4655 4656 // Don't try to build an implicit initializer if there were semantic 4657 // errors in any of the initializers (and therefore we might be 4658 // missing some that the user actually wrote). 4659 if (Info.AnyErrorsInInits) 4660 return false; 4661 4662 CXXCtorInitializer *Init = nullptr; 4663 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4664 Indirect, Init)) 4665 return true; 4666 4667 if (!Init) 4668 return false; 4669 4670 return Info.addFieldInitializer(Init); 4671 } 4672 4673 bool 4674 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4675 CXXCtorInitializer *Initializer) { 4676 assert(Initializer->isDelegatingInitializer()); 4677 Constructor->setNumCtorInitializers(1); 4678 CXXCtorInitializer **initializer = 4679 new (Context) CXXCtorInitializer*[1]; 4680 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4681 Constructor->setCtorInitializers(initializer); 4682 4683 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4684 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4685 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4686 } 4687 4688 DelegatingCtorDecls.push_back(Constructor); 4689 4690 DiagnoseUninitializedFields(*this, Constructor); 4691 4692 return false; 4693 } 4694 4695 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4696 ArrayRef<CXXCtorInitializer *> Initializers) { 4697 if (Constructor->isDependentContext()) { 4698 // Just store the initializers as written, they will be checked during 4699 // instantiation. 4700 if (!Initializers.empty()) { 4701 Constructor->setNumCtorInitializers(Initializers.size()); 4702 CXXCtorInitializer **baseOrMemberInitializers = 4703 new (Context) CXXCtorInitializer*[Initializers.size()]; 4704 memcpy(baseOrMemberInitializers, Initializers.data(), 4705 Initializers.size() * sizeof(CXXCtorInitializer*)); 4706 Constructor->setCtorInitializers(baseOrMemberInitializers); 4707 } 4708 4709 // Let template instantiation know whether we had errors. 4710 if (AnyErrors) 4711 Constructor->setInvalidDecl(); 4712 4713 return false; 4714 } 4715 4716 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4717 4718 // We need to build the initializer AST according to order of construction 4719 // and not what user specified in the Initializers list. 4720 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4721 if (!ClassDecl) 4722 return true; 4723 4724 bool HadError = false; 4725 4726 for (unsigned i = 0; i < Initializers.size(); i++) { 4727 CXXCtorInitializer *Member = Initializers[i]; 4728 4729 if (Member->isBaseInitializer()) 4730 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4731 else { 4732 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4733 4734 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4735 for (auto *C : F->chain()) { 4736 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4737 if (FD && FD->getParent()->isUnion()) 4738 Info.ActiveUnionMember.insert(std::make_pair( 4739 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4740 } 4741 } else if (FieldDecl *FD = Member->getMember()) { 4742 if (FD->getParent()->isUnion()) 4743 Info.ActiveUnionMember.insert(std::make_pair( 4744 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4745 } 4746 } 4747 } 4748 4749 // Keep track of the direct virtual bases. 4750 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4751 for (auto &I : ClassDecl->bases()) { 4752 if (I.isVirtual()) 4753 DirectVBases.insert(&I); 4754 } 4755 4756 // Push virtual bases before others. 4757 for (auto &VBase : ClassDecl->vbases()) { 4758 if (CXXCtorInitializer *Value 4759 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4760 // [class.base.init]p7, per DR257: 4761 // A mem-initializer where the mem-initializer-id names a virtual base 4762 // class is ignored during execution of a constructor of any class that 4763 // is not the most derived class. 4764 if (ClassDecl->isAbstract()) { 4765 // FIXME: Provide a fixit to remove the base specifier. This requires 4766 // tracking the location of the associated comma for a base specifier. 4767 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4768 << VBase.getType() << ClassDecl; 4769 DiagnoseAbstractType(ClassDecl); 4770 } 4771 4772 Info.AllToInit.push_back(Value); 4773 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4774 // [class.base.init]p8, per DR257: 4775 // If a given [...] base class is not named by a mem-initializer-id 4776 // [...] and the entity is not a virtual base class of an abstract 4777 // class, then [...] the entity is default-initialized. 4778 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4779 CXXCtorInitializer *CXXBaseInit; 4780 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4781 &VBase, IsInheritedVirtualBase, 4782 CXXBaseInit)) { 4783 HadError = true; 4784 continue; 4785 } 4786 4787 Info.AllToInit.push_back(CXXBaseInit); 4788 } 4789 } 4790 4791 // Non-virtual bases. 4792 for (auto &Base : ClassDecl->bases()) { 4793 // Virtuals are in the virtual base list and already constructed. 4794 if (Base.isVirtual()) 4795 continue; 4796 4797 if (CXXCtorInitializer *Value 4798 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4799 Info.AllToInit.push_back(Value); 4800 } else if (!AnyErrors) { 4801 CXXCtorInitializer *CXXBaseInit; 4802 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4803 &Base, /*IsInheritedVirtualBase=*/false, 4804 CXXBaseInit)) { 4805 HadError = true; 4806 continue; 4807 } 4808 4809 Info.AllToInit.push_back(CXXBaseInit); 4810 } 4811 } 4812 4813 // Fields. 4814 for (auto *Mem : ClassDecl->decls()) { 4815 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4816 // C++ [class.bit]p2: 4817 // A declaration for a bit-field that omits the identifier declares an 4818 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4819 // initialized. 4820 if (F->isUnnamedBitfield()) 4821 continue; 4822 4823 // If we're not generating the implicit copy/move constructor, then we'll 4824 // handle anonymous struct/union fields based on their individual 4825 // indirect fields. 4826 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4827 continue; 4828 4829 if (CollectFieldInitializer(*this, Info, F)) 4830 HadError = true; 4831 continue; 4832 } 4833 4834 // Beyond this point, we only consider default initialization. 4835 if (Info.isImplicitCopyOrMove()) 4836 continue; 4837 4838 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4839 if (F->getType()->isIncompleteArrayType()) { 4840 assert(ClassDecl->hasFlexibleArrayMember() && 4841 "Incomplete array type is not valid"); 4842 continue; 4843 } 4844 4845 // Initialize each field of an anonymous struct individually. 4846 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4847 HadError = true; 4848 4849 continue; 4850 } 4851 } 4852 4853 unsigned NumInitializers = Info.AllToInit.size(); 4854 if (NumInitializers > 0) { 4855 Constructor->setNumCtorInitializers(NumInitializers); 4856 CXXCtorInitializer **baseOrMemberInitializers = 4857 new (Context) CXXCtorInitializer*[NumInitializers]; 4858 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4859 NumInitializers * sizeof(CXXCtorInitializer*)); 4860 Constructor->setCtorInitializers(baseOrMemberInitializers); 4861 4862 // Constructors implicitly reference the base and member 4863 // destructors. 4864 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4865 Constructor->getParent()); 4866 } 4867 4868 return HadError; 4869 } 4870 4871 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4872 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4873 const RecordDecl *RD = RT->getDecl(); 4874 if (RD->isAnonymousStructOrUnion()) { 4875 for (auto *Field : RD->fields()) 4876 PopulateKeysForFields(Field, IdealInits); 4877 return; 4878 } 4879 } 4880 IdealInits.push_back(Field->getCanonicalDecl()); 4881 } 4882 4883 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4884 return Context.getCanonicalType(BaseType).getTypePtr(); 4885 } 4886 4887 static const void *GetKeyForMember(ASTContext &Context, 4888 CXXCtorInitializer *Member) { 4889 if (!Member->isAnyMemberInitializer()) 4890 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4891 4892 return Member->getAnyMember()->getCanonicalDecl(); 4893 } 4894 4895 static void DiagnoseBaseOrMemInitializerOrder( 4896 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4897 ArrayRef<CXXCtorInitializer *> Inits) { 4898 if (Constructor->getDeclContext()->isDependentContext()) 4899 return; 4900 4901 // Don't check initializers order unless the warning is enabled at the 4902 // location of at least one initializer. 4903 bool ShouldCheckOrder = false; 4904 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4905 CXXCtorInitializer *Init = Inits[InitIndex]; 4906 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4907 Init->getSourceLocation())) { 4908 ShouldCheckOrder = true; 4909 break; 4910 } 4911 } 4912 if (!ShouldCheckOrder) 4913 return; 4914 4915 // Build the list of bases and members in the order that they'll 4916 // actually be initialized. The explicit initializers should be in 4917 // this same order but may be missing things. 4918 SmallVector<const void*, 32> IdealInitKeys; 4919 4920 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4921 4922 // 1. Virtual bases. 4923 for (const auto &VBase : ClassDecl->vbases()) 4924 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4925 4926 // 2. Non-virtual bases. 4927 for (const auto &Base : ClassDecl->bases()) { 4928 if (Base.isVirtual()) 4929 continue; 4930 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4931 } 4932 4933 // 3. Direct fields. 4934 for (auto *Field : ClassDecl->fields()) { 4935 if (Field->isUnnamedBitfield()) 4936 continue; 4937 4938 PopulateKeysForFields(Field, IdealInitKeys); 4939 } 4940 4941 unsigned NumIdealInits = IdealInitKeys.size(); 4942 unsigned IdealIndex = 0; 4943 4944 CXXCtorInitializer *PrevInit = nullptr; 4945 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4946 CXXCtorInitializer *Init = Inits[InitIndex]; 4947 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4948 4949 // Scan forward to try to find this initializer in the idealized 4950 // initializers list. 4951 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4952 if (InitKey == IdealInitKeys[IdealIndex]) 4953 break; 4954 4955 // If we didn't find this initializer, it must be because we 4956 // scanned past it on a previous iteration. That can only 4957 // happen if we're out of order; emit a warning. 4958 if (IdealIndex == NumIdealInits && PrevInit) { 4959 Sema::SemaDiagnosticBuilder D = 4960 SemaRef.Diag(PrevInit->getSourceLocation(), 4961 diag::warn_initializer_out_of_order); 4962 4963 if (PrevInit->isAnyMemberInitializer()) 4964 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4965 else 4966 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4967 4968 if (Init->isAnyMemberInitializer()) 4969 D << 0 << Init->getAnyMember()->getDeclName(); 4970 else 4971 D << 1 << Init->getTypeSourceInfo()->getType(); 4972 4973 // Move back to the initializer's location in the ideal list. 4974 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4975 if (InitKey == IdealInitKeys[IdealIndex]) 4976 break; 4977 4978 assert(IdealIndex < NumIdealInits && 4979 "initializer not found in initializer list"); 4980 } 4981 4982 PrevInit = Init; 4983 } 4984 } 4985 4986 namespace { 4987 bool CheckRedundantInit(Sema &S, 4988 CXXCtorInitializer *Init, 4989 CXXCtorInitializer *&PrevInit) { 4990 if (!PrevInit) { 4991 PrevInit = Init; 4992 return false; 4993 } 4994 4995 if (FieldDecl *Field = Init->getAnyMember()) 4996 S.Diag(Init->getSourceLocation(), 4997 diag::err_multiple_mem_initialization) 4998 << Field->getDeclName() 4999 << Init->getSourceRange(); 5000 else { 5001 const Type *BaseClass = Init->getBaseClass(); 5002 assert(BaseClass && "neither field nor base"); 5003 S.Diag(Init->getSourceLocation(), 5004 diag::err_multiple_base_initialization) 5005 << QualType(BaseClass, 0) 5006 << Init->getSourceRange(); 5007 } 5008 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5009 << 0 << PrevInit->getSourceRange(); 5010 5011 return true; 5012 } 5013 5014 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5015 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5016 5017 bool CheckRedundantUnionInit(Sema &S, 5018 CXXCtorInitializer *Init, 5019 RedundantUnionMap &Unions) { 5020 FieldDecl *Field = Init->getAnyMember(); 5021 RecordDecl *Parent = Field->getParent(); 5022 NamedDecl *Child = Field; 5023 5024 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5025 if (Parent->isUnion()) { 5026 UnionEntry &En = Unions[Parent]; 5027 if (En.first && En.first != Child) { 5028 S.Diag(Init->getSourceLocation(), 5029 diag::err_multiple_mem_union_initialization) 5030 << Field->getDeclName() 5031 << Init->getSourceRange(); 5032 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5033 << 0 << En.second->getSourceRange(); 5034 return true; 5035 } 5036 if (!En.first) { 5037 En.first = Child; 5038 En.second = Init; 5039 } 5040 if (!Parent->isAnonymousStructOrUnion()) 5041 return false; 5042 } 5043 5044 Child = Parent; 5045 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5046 } 5047 5048 return false; 5049 } 5050 } 5051 5052 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5053 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5054 SourceLocation ColonLoc, 5055 ArrayRef<CXXCtorInitializer*> MemInits, 5056 bool AnyErrors) { 5057 if (!ConstructorDecl) 5058 return; 5059 5060 AdjustDeclIfTemplate(ConstructorDecl); 5061 5062 CXXConstructorDecl *Constructor 5063 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5064 5065 if (!Constructor) { 5066 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5067 return; 5068 } 5069 5070 // Mapping for the duplicate initializers check. 5071 // For member initializers, this is keyed with a FieldDecl*. 5072 // For base initializers, this is keyed with a Type*. 5073 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5074 5075 // Mapping for the inconsistent anonymous-union initializers check. 5076 RedundantUnionMap MemberUnions; 5077 5078 bool HadError = false; 5079 for (unsigned i = 0; i < MemInits.size(); i++) { 5080 CXXCtorInitializer *Init = MemInits[i]; 5081 5082 // Set the source order index. 5083 Init->setSourceOrder(i); 5084 5085 if (Init->isAnyMemberInitializer()) { 5086 const void *Key = GetKeyForMember(Context, Init); 5087 if (CheckRedundantInit(*this, Init, Members[Key]) || 5088 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5089 HadError = true; 5090 } else if (Init->isBaseInitializer()) { 5091 const void *Key = GetKeyForMember(Context, Init); 5092 if (CheckRedundantInit(*this, Init, Members[Key])) 5093 HadError = true; 5094 } else { 5095 assert(Init->isDelegatingInitializer()); 5096 // This must be the only initializer 5097 if (MemInits.size() != 1) { 5098 Diag(Init->getSourceLocation(), 5099 diag::err_delegating_initializer_alone) 5100 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5101 // We will treat this as being the only initializer. 5102 } 5103 SetDelegatingInitializer(Constructor, MemInits[i]); 5104 // Return immediately as the initializer is set. 5105 return; 5106 } 5107 } 5108 5109 if (HadError) 5110 return; 5111 5112 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5113 5114 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5115 5116 DiagnoseUninitializedFields(*this, Constructor); 5117 } 5118 5119 void 5120 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5121 CXXRecordDecl *ClassDecl) { 5122 // Ignore dependent contexts. Also ignore unions, since their members never 5123 // have destructors implicitly called. 5124 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5125 return; 5126 5127 // FIXME: all the access-control diagnostics are positioned on the 5128 // field/base declaration. That's probably good; that said, the 5129 // user might reasonably want to know why the destructor is being 5130 // emitted, and we currently don't say. 5131 5132 // Non-static data members. 5133 for (auto *Field : ClassDecl->fields()) { 5134 if (Field->isInvalidDecl()) 5135 continue; 5136 5137 // Don't destroy incomplete or zero-length arrays. 5138 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5139 continue; 5140 5141 QualType FieldType = Context.getBaseElementType(Field->getType()); 5142 5143 const RecordType* RT = FieldType->getAs<RecordType>(); 5144 if (!RT) 5145 continue; 5146 5147 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5148 if (FieldClassDecl->isInvalidDecl()) 5149 continue; 5150 if (FieldClassDecl->hasIrrelevantDestructor()) 5151 continue; 5152 // The destructor for an implicit anonymous union member is never invoked. 5153 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5154 continue; 5155 5156 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5157 assert(Dtor && "No dtor found for FieldClassDecl!"); 5158 CheckDestructorAccess(Field->getLocation(), Dtor, 5159 PDiag(diag::err_access_dtor_field) 5160 << Field->getDeclName() 5161 << FieldType); 5162 5163 MarkFunctionReferenced(Location, Dtor); 5164 DiagnoseUseOfDecl(Dtor, Location); 5165 } 5166 5167 // We only potentially invoke the destructors of potentially constructed 5168 // subobjects. 5169 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5170 5171 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5172 5173 // Bases. 5174 for (const auto &Base : ClassDecl->bases()) { 5175 // Bases are always records in a well-formed non-dependent class. 5176 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5177 5178 // Remember direct virtual bases. 5179 if (Base.isVirtual()) { 5180 if (!VisitVirtualBases) 5181 continue; 5182 DirectVirtualBases.insert(RT); 5183 } 5184 5185 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5186 // If our base class is invalid, we probably can't get its dtor anyway. 5187 if (BaseClassDecl->isInvalidDecl()) 5188 continue; 5189 if (BaseClassDecl->hasIrrelevantDestructor()) 5190 continue; 5191 5192 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5193 assert(Dtor && "No dtor found for BaseClassDecl!"); 5194 5195 // FIXME: caret should be on the start of the class name 5196 CheckDestructorAccess(Base.getLocStart(), Dtor, 5197 PDiag(diag::err_access_dtor_base) 5198 << Base.getType() 5199 << Base.getSourceRange(), 5200 Context.getTypeDeclType(ClassDecl)); 5201 5202 MarkFunctionReferenced(Location, Dtor); 5203 DiagnoseUseOfDecl(Dtor, Location); 5204 } 5205 5206 if (!VisitVirtualBases) 5207 return; 5208 5209 // Virtual bases. 5210 for (const auto &VBase : ClassDecl->vbases()) { 5211 // Bases are always records in a well-formed non-dependent class. 5212 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5213 5214 // Ignore direct virtual bases. 5215 if (DirectVirtualBases.count(RT)) 5216 continue; 5217 5218 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5219 // If our base class is invalid, we probably can't get its dtor anyway. 5220 if (BaseClassDecl->isInvalidDecl()) 5221 continue; 5222 if (BaseClassDecl->hasIrrelevantDestructor()) 5223 continue; 5224 5225 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5226 assert(Dtor && "No dtor found for BaseClassDecl!"); 5227 if (CheckDestructorAccess( 5228 ClassDecl->getLocation(), Dtor, 5229 PDiag(diag::err_access_dtor_vbase) 5230 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5231 Context.getTypeDeclType(ClassDecl)) == 5232 AR_accessible) { 5233 CheckDerivedToBaseConversion( 5234 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5235 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5236 SourceRange(), DeclarationName(), nullptr); 5237 } 5238 5239 MarkFunctionReferenced(Location, Dtor); 5240 DiagnoseUseOfDecl(Dtor, Location); 5241 } 5242 } 5243 5244 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5245 if (!CDtorDecl) 5246 return; 5247 5248 if (CXXConstructorDecl *Constructor 5249 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5250 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5251 DiagnoseUninitializedFields(*this, Constructor); 5252 } 5253 } 5254 5255 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5256 if (!getLangOpts().CPlusPlus) 5257 return false; 5258 5259 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5260 if (!RD) 5261 return false; 5262 5263 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5264 // class template specialization here, but doing so breaks a lot of code. 5265 5266 // We can't answer whether something is abstract until it has a 5267 // definition. If it's currently being defined, we'll walk back 5268 // over all the declarations when we have a full definition. 5269 const CXXRecordDecl *Def = RD->getDefinition(); 5270 if (!Def || Def->isBeingDefined()) 5271 return false; 5272 5273 return RD->isAbstract(); 5274 } 5275 5276 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5277 TypeDiagnoser &Diagnoser) { 5278 if (!isAbstractType(Loc, T)) 5279 return false; 5280 5281 T = Context.getBaseElementType(T); 5282 Diagnoser.diagnose(*this, Loc, T); 5283 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5284 return true; 5285 } 5286 5287 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5288 // Check if we've already emitted the list of pure virtual functions 5289 // for this class. 5290 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5291 return; 5292 5293 // If the diagnostic is suppressed, don't emit the notes. We're only 5294 // going to emit them once, so try to attach them to a diagnostic we're 5295 // actually going to show. 5296 if (Diags.isLastDiagnosticIgnored()) 5297 return; 5298 5299 CXXFinalOverriderMap FinalOverriders; 5300 RD->getFinalOverriders(FinalOverriders); 5301 5302 // Keep a set of seen pure methods so we won't diagnose the same method 5303 // more than once. 5304 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5305 5306 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5307 MEnd = FinalOverriders.end(); 5308 M != MEnd; 5309 ++M) { 5310 for (OverridingMethods::iterator SO = M->second.begin(), 5311 SOEnd = M->second.end(); 5312 SO != SOEnd; ++SO) { 5313 // C++ [class.abstract]p4: 5314 // A class is abstract if it contains or inherits at least one 5315 // pure virtual function for which the final overrider is pure 5316 // virtual. 5317 5318 // 5319 if (SO->second.size() != 1) 5320 continue; 5321 5322 if (!SO->second.front().Method->isPure()) 5323 continue; 5324 5325 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5326 continue; 5327 5328 Diag(SO->second.front().Method->getLocation(), 5329 diag::note_pure_virtual_function) 5330 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5331 } 5332 } 5333 5334 if (!PureVirtualClassDiagSet) 5335 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5336 PureVirtualClassDiagSet->insert(RD); 5337 } 5338 5339 namespace { 5340 struct AbstractUsageInfo { 5341 Sema &S; 5342 CXXRecordDecl *Record; 5343 CanQualType AbstractType; 5344 bool Invalid; 5345 5346 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5347 : S(S), Record(Record), 5348 AbstractType(S.Context.getCanonicalType( 5349 S.Context.getTypeDeclType(Record))), 5350 Invalid(false) {} 5351 5352 void DiagnoseAbstractType() { 5353 if (Invalid) return; 5354 S.DiagnoseAbstractType(Record); 5355 Invalid = true; 5356 } 5357 5358 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5359 }; 5360 5361 struct CheckAbstractUsage { 5362 AbstractUsageInfo &Info; 5363 const NamedDecl *Ctx; 5364 5365 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5366 : Info(Info), Ctx(Ctx) {} 5367 5368 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5369 switch (TL.getTypeLocClass()) { 5370 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5371 #define TYPELOC(CLASS, PARENT) \ 5372 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5373 #include "clang/AST/TypeLocNodes.def" 5374 } 5375 } 5376 5377 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5378 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5379 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5380 if (!TL.getParam(I)) 5381 continue; 5382 5383 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5384 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5385 } 5386 } 5387 5388 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5389 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5390 } 5391 5392 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5393 // Visit the type parameters from a permissive context. 5394 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5395 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5396 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5397 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5398 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5399 // TODO: other template argument types? 5400 } 5401 } 5402 5403 // Visit pointee types from a permissive context. 5404 #define CheckPolymorphic(Type) \ 5405 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5406 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5407 } 5408 CheckPolymorphic(PointerTypeLoc) 5409 CheckPolymorphic(ReferenceTypeLoc) 5410 CheckPolymorphic(MemberPointerTypeLoc) 5411 CheckPolymorphic(BlockPointerTypeLoc) 5412 CheckPolymorphic(AtomicTypeLoc) 5413 5414 /// Handle all the types we haven't given a more specific 5415 /// implementation for above. 5416 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5417 // Every other kind of type that we haven't called out already 5418 // that has an inner type is either (1) sugar or (2) contains that 5419 // inner type in some way as a subobject. 5420 if (TypeLoc Next = TL.getNextTypeLoc()) 5421 return Visit(Next, Sel); 5422 5423 // If there's no inner type and we're in a permissive context, 5424 // don't diagnose. 5425 if (Sel == Sema::AbstractNone) return; 5426 5427 // Check whether the type matches the abstract type. 5428 QualType T = TL.getType(); 5429 if (T->isArrayType()) { 5430 Sel = Sema::AbstractArrayType; 5431 T = Info.S.Context.getBaseElementType(T); 5432 } 5433 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5434 if (CT != Info.AbstractType) return; 5435 5436 // It matched; do some magic. 5437 if (Sel == Sema::AbstractArrayType) { 5438 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5439 << T << TL.getSourceRange(); 5440 } else { 5441 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5442 << Sel << T << TL.getSourceRange(); 5443 } 5444 Info.DiagnoseAbstractType(); 5445 } 5446 }; 5447 5448 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5449 Sema::AbstractDiagSelID Sel) { 5450 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5451 } 5452 5453 } 5454 5455 /// Check for invalid uses of an abstract type in a method declaration. 5456 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5457 CXXMethodDecl *MD) { 5458 // No need to do the check on definitions, which require that 5459 // the return/param types be complete. 5460 if (MD->doesThisDeclarationHaveABody()) 5461 return; 5462 5463 // For safety's sake, just ignore it if we don't have type source 5464 // information. This should never happen for non-implicit methods, 5465 // but... 5466 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5467 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5468 } 5469 5470 /// Check for invalid uses of an abstract type within a class definition. 5471 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5472 CXXRecordDecl *RD) { 5473 for (auto *D : RD->decls()) { 5474 if (D->isImplicit()) continue; 5475 5476 // Methods and method templates. 5477 if (isa<CXXMethodDecl>(D)) { 5478 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5479 } else if (isa<FunctionTemplateDecl>(D)) { 5480 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5481 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5482 5483 // Fields and static variables. 5484 } else if (isa<FieldDecl>(D)) { 5485 FieldDecl *FD = cast<FieldDecl>(D); 5486 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5487 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5488 } else if (isa<VarDecl>(D)) { 5489 VarDecl *VD = cast<VarDecl>(D); 5490 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5491 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5492 5493 // Nested classes and class templates. 5494 } else if (isa<CXXRecordDecl>(D)) { 5495 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5496 } else if (isa<ClassTemplateDecl>(D)) { 5497 CheckAbstractClassUsage(Info, 5498 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5499 } 5500 } 5501 } 5502 5503 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5504 Attr *ClassAttr = getDLLAttr(Class); 5505 if (!ClassAttr) 5506 return; 5507 5508 assert(ClassAttr->getKind() == attr::DLLExport); 5509 5510 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5511 5512 if (TSK == TSK_ExplicitInstantiationDeclaration) 5513 // Don't go any further if this is just an explicit instantiation 5514 // declaration. 5515 return; 5516 5517 for (Decl *Member : Class->decls()) { 5518 // Defined static variables that are members of an exported base 5519 // class must be marked export too. 5520 auto *VD = dyn_cast<VarDecl>(Member); 5521 if (VD && Member->getAttr<DLLExportAttr>() && 5522 VD->getStorageClass() == SC_Static && 5523 TSK == TSK_ImplicitInstantiation) 5524 S.MarkVariableReferenced(VD->getLocation(), VD); 5525 5526 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5527 if (!MD) 5528 continue; 5529 5530 if (Member->getAttr<DLLExportAttr>()) { 5531 if (MD->isUserProvided()) { 5532 // Instantiate non-default class member functions ... 5533 5534 // .. except for certain kinds of template specializations. 5535 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5536 continue; 5537 5538 S.MarkFunctionReferenced(Class->getLocation(), MD); 5539 5540 // The function will be passed to the consumer when its definition is 5541 // encountered. 5542 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5543 MD->isCopyAssignmentOperator() || 5544 MD->isMoveAssignmentOperator()) { 5545 // Synthesize and instantiate non-trivial implicit methods, explicitly 5546 // defaulted methods, and the copy and move assignment operators. The 5547 // latter are exported even if they are trivial, because the address of 5548 // an operator can be taken and should compare equal across libraries. 5549 DiagnosticErrorTrap Trap(S.Diags); 5550 S.MarkFunctionReferenced(Class->getLocation(), MD); 5551 if (Trap.hasErrorOccurred()) { 5552 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5553 << Class << !S.getLangOpts().CPlusPlus11; 5554 break; 5555 } 5556 5557 // There is no later point when we will see the definition of this 5558 // function, so pass it to the consumer now. 5559 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5560 } 5561 } 5562 } 5563 } 5564 5565 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5566 CXXRecordDecl *Class) { 5567 // Only the MS ABI has default constructor closures, so we don't need to do 5568 // this semantic checking anywhere else. 5569 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5570 return; 5571 5572 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5573 for (Decl *Member : Class->decls()) { 5574 // Look for exported default constructors. 5575 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5576 if (!CD || !CD->isDefaultConstructor()) 5577 continue; 5578 auto *Attr = CD->getAttr<DLLExportAttr>(); 5579 if (!Attr) 5580 continue; 5581 5582 // If the class is non-dependent, mark the default arguments as ODR-used so 5583 // that we can properly codegen the constructor closure. 5584 if (!Class->isDependentContext()) { 5585 for (ParmVarDecl *PD : CD->parameters()) { 5586 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5587 S.DiscardCleanupsInEvaluationContext(); 5588 } 5589 } 5590 5591 if (LastExportedDefaultCtor) { 5592 S.Diag(LastExportedDefaultCtor->getLocation(), 5593 diag::err_attribute_dll_ambiguous_default_ctor) 5594 << Class; 5595 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5596 << CD->getDeclName(); 5597 return; 5598 } 5599 LastExportedDefaultCtor = CD; 5600 } 5601 } 5602 5603 /// Check class-level dllimport/dllexport attribute. 5604 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5605 Attr *ClassAttr = getDLLAttr(Class); 5606 5607 // MSVC inherits DLL attributes to partial class template specializations. 5608 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5609 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5610 if (Attr *TemplateAttr = 5611 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5612 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5613 A->setInherited(true); 5614 ClassAttr = A; 5615 } 5616 } 5617 } 5618 5619 if (!ClassAttr) 5620 return; 5621 5622 if (!Class->isExternallyVisible()) { 5623 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5624 << Class << ClassAttr; 5625 return; 5626 } 5627 5628 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5629 !ClassAttr->isInherited()) { 5630 // Diagnose dll attributes on members of class with dll attribute. 5631 for (Decl *Member : Class->decls()) { 5632 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5633 continue; 5634 InheritableAttr *MemberAttr = getDLLAttr(Member); 5635 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5636 continue; 5637 5638 Diag(MemberAttr->getLocation(), 5639 diag::err_attribute_dll_member_of_dll_class) 5640 << MemberAttr << ClassAttr; 5641 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5642 Member->setInvalidDecl(); 5643 } 5644 } 5645 5646 if (Class->getDescribedClassTemplate()) 5647 // Don't inherit dll attribute until the template is instantiated. 5648 return; 5649 5650 // The class is either imported or exported. 5651 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5652 5653 // Check if this was a dllimport attribute propagated from a derived class to 5654 // a base class template specialization. We don't apply these attributes to 5655 // static data members. 5656 const bool PropagatedImport = 5657 !ClassExported && 5658 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5659 5660 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5661 5662 // Ignore explicit dllexport on explicit class template instantiation declarations. 5663 if (ClassExported && !ClassAttr->isInherited() && 5664 TSK == TSK_ExplicitInstantiationDeclaration) { 5665 Class->dropAttr<DLLExportAttr>(); 5666 return; 5667 } 5668 5669 // Force declaration of implicit members so they can inherit the attribute. 5670 ForceDeclarationOfImplicitMembers(Class); 5671 5672 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5673 // seem to be true in practice? 5674 5675 for (Decl *Member : Class->decls()) { 5676 VarDecl *VD = dyn_cast<VarDecl>(Member); 5677 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5678 5679 // Only methods and static fields inherit the attributes. 5680 if (!VD && !MD) 5681 continue; 5682 5683 if (MD) { 5684 // Don't process deleted methods. 5685 if (MD->isDeleted()) 5686 continue; 5687 5688 if (MD->isInlined()) { 5689 // MinGW does not import or export inline methods. 5690 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5691 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5692 continue; 5693 5694 // MSVC versions before 2015 don't export the move assignment operators 5695 // and move constructor, so don't attempt to import/export them if 5696 // we have a definition. 5697 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5698 if ((MD->isMoveAssignmentOperator() || 5699 (Ctor && Ctor->isMoveConstructor())) && 5700 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5701 continue; 5702 5703 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5704 // operator is exported anyway. 5705 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5706 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5707 continue; 5708 } 5709 } 5710 5711 // Don't apply dllimport attributes to static data members of class template 5712 // instantiations when the attribute is propagated from a derived class. 5713 if (VD && PropagatedImport) 5714 continue; 5715 5716 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5717 continue; 5718 5719 if (!getDLLAttr(Member)) { 5720 auto *NewAttr = 5721 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5722 NewAttr->setInherited(true); 5723 Member->addAttr(NewAttr); 5724 5725 if (MD) { 5726 // Propagate DLLAttr to friend re-declarations of MD that have already 5727 // been constructed. 5728 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5729 FD = FD->getPreviousDecl()) { 5730 if (FD->getFriendObjectKind() == Decl::FOK_None) 5731 continue; 5732 assert(!getDLLAttr(FD) && 5733 "friend re-decl should not already have a DLLAttr"); 5734 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5735 NewAttr->setInherited(true); 5736 FD->addAttr(NewAttr); 5737 } 5738 } 5739 } 5740 } 5741 5742 if (ClassExported) 5743 DelayedDllExportClasses.push_back(Class); 5744 } 5745 5746 /// Perform propagation of DLL attributes from a derived class to a 5747 /// templated base class for MS compatibility. 5748 void Sema::propagateDLLAttrToBaseClassTemplate( 5749 CXXRecordDecl *Class, Attr *ClassAttr, 5750 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5751 if (getDLLAttr( 5752 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5753 // If the base class template has a DLL attribute, don't try to change it. 5754 return; 5755 } 5756 5757 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5758 if (!getDLLAttr(BaseTemplateSpec) && 5759 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5760 TSK == TSK_ImplicitInstantiation)) { 5761 // The template hasn't been instantiated yet (or it has, but only as an 5762 // explicit instantiation declaration or implicit instantiation, which means 5763 // we haven't codegenned any members yet), so propagate the attribute. 5764 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5765 NewAttr->setInherited(true); 5766 BaseTemplateSpec->addAttr(NewAttr); 5767 5768 // If this was an import, mark that we propagated it from a derived class to 5769 // a base class template specialization. 5770 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5771 ImportAttr->setPropagatedToBaseTemplate(); 5772 5773 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5774 // needs to be run again to work see the new attribute. Otherwise this will 5775 // get run whenever the template is instantiated. 5776 if (TSK != TSK_Undeclared) 5777 checkClassLevelDLLAttribute(BaseTemplateSpec); 5778 5779 return; 5780 } 5781 5782 if (getDLLAttr(BaseTemplateSpec)) { 5783 // The template has already been specialized or instantiated with an 5784 // attribute, explicitly or through propagation. We should not try to change 5785 // it. 5786 return; 5787 } 5788 5789 // The template was previously instantiated or explicitly specialized without 5790 // a dll attribute, It's too late for us to add an attribute, so warn that 5791 // this is unsupported. 5792 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5793 << BaseTemplateSpec->isExplicitSpecialization(); 5794 Diag(ClassAttr->getLocation(), diag::note_attribute); 5795 if (BaseTemplateSpec->isExplicitSpecialization()) { 5796 Diag(BaseTemplateSpec->getLocation(), 5797 diag::note_template_class_explicit_specialization_was_here) 5798 << BaseTemplateSpec; 5799 } else { 5800 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5801 diag::note_template_class_instantiation_was_here) 5802 << BaseTemplateSpec; 5803 } 5804 } 5805 5806 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5807 SourceLocation DefaultLoc) { 5808 switch (S.getSpecialMember(MD)) { 5809 case Sema::CXXDefaultConstructor: 5810 S.DefineImplicitDefaultConstructor(DefaultLoc, 5811 cast<CXXConstructorDecl>(MD)); 5812 break; 5813 case Sema::CXXCopyConstructor: 5814 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5815 break; 5816 case Sema::CXXCopyAssignment: 5817 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5818 break; 5819 case Sema::CXXDestructor: 5820 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5821 break; 5822 case Sema::CXXMoveConstructor: 5823 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5824 break; 5825 case Sema::CXXMoveAssignment: 5826 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5827 break; 5828 case Sema::CXXInvalid: 5829 llvm_unreachable("Invalid special member."); 5830 } 5831 } 5832 5833 /// Determine whether a type is permitted to be passed or returned in 5834 /// registers, per C++ [class.temporary]p3. 5835 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 5836 TargetInfo::CallingConvKind CCK) { 5837 if (D->isDependentType() || D->isInvalidDecl()) 5838 return false; 5839 5840 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5841 // The PS4 platform ABI follows the behavior of Clang 3.2. 5842 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5843 return !D->hasNonTrivialDestructorForCall() && 5844 !D->hasNonTrivialCopyConstructorForCall(); 5845 5846 if (CCK == TargetInfo::CCK_MicrosoftX86_64) { 5847 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5848 bool DtorIsTrivialForCall = false; 5849 5850 // If a class has at least one non-deleted, trivial copy constructor, it 5851 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5852 // 5853 // Note: This permits classes with non-trivial copy or move ctors to be 5854 // passed in registers, so long as they *also* have a trivial copy ctor, 5855 // which is non-conforming. 5856 if (D->needsImplicitCopyConstructor()) { 5857 if (!D->defaultedCopyConstructorIsDeleted()) { 5858 if (D->hasTrivialCopyConstructor()) 5859 CopyCtorIsTrivial = true; 5860 if (D->hasTrivialCopyConstructorForCall()) 5861 CopyCtorIsTrivialForCall = true; 5862 } 5863 } else { 5864 for (const CXXConstructorDecl *CD : D->ctors()) { 5865 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5866 if (CD->isTrivial()) 5867 CopyCtorIsTrivial = true; 5868 if (CD->isTrivialForCall()) 5869 CopyCtorIsTrivialForCall = true; 5870 } 5871 } 5872 } 5873 5874 if (D->needsImplicitDestructor()) { 5875 if (!D->defaultedDestructorIsDeleted() && 5876 D->hasTrivialDestructorForCall()) 5877 DtorIsTrivialForCall = true; 5878 } else if (const auto *DD = D->getDestructor()) { 5879 if (!DD->isDeleted() && DD->isTrivialForCall()) 5880 DtorIsTrivialForCall = true; 5881 } 5882 5883 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5884 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5885 return true; 5886 5887 // If a class has a destructor, we'd really like to pass it indirectly 5888 // because it allows us to elide copies. Unfortunately, MSVC makes that 5889 // impossible for small types, which it will pass in a single register or 5890 // stack slot. Most objects with dtors are large-ish, so handle that early. 5891 // We can't call out all large objects as being indirect because there are 5892 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5893 // how we pass large POD types. 5894 5895 // Note: This permits small classes with nontrivial destructors to be 5896 // passed in registers, which is non-conforming. 5897 if (CopyCtorIsTrivial && 5898 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64) 5899 return true; 5900 return false; 5901 } 5902 5903 // Per C++ [class.temporary]p3, the relevant condition is: 5904 // each copy constructor, move constructor, and destructor of X is 5905 // either trivial or deleted, and X has at least one non-deleted copy 5906 // or move constructor 5907 bool HasNonDeletedCopyOrMove = false; 5908 5909 if (D->needsImplicitCopyConstructor() && 5910 !D->defaultedCopyConstructorIsDeleted()) { 5911 if (!D->hasTrivialCopyConstructorForCall()) 5912 return false; 5913 HasNonDeletedCopyOrMove = true; 5914 } 5915 5916 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5917 !D->defaultedMoveConstructorIsDeleted()) { 5918 if (!D->hasTrivialMoveConstructorForCall()) 5919 return false; 5920 HasNonDeletedCopyOrMove = true; 5921 } 5922 5923 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5924 !D->hasTrivialDestructorForCall()) 5925 return false; 5926 5927 for (const CXXMethodDecl *MD : D->methods()) { 5928 if (MD->isDeleted()) 5929 continue; 5930 5931 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5932 if (CD && CD->isCopyOrMoveConstructor()) 5933 HasNonDeletedCopyOrMove = true; 5934 else if (!isa<CXXDestructorDecl>(MD)) 5935 continue; 5936 5937 if (!MD->isTrivialForCall()) 5938 return false; 5939 } 5940 5941 return HasNonDeletedCopyOrMove; 5942 } 5943 5944 /// Perform semantic checks on a class definition that has been 5945 /// completing, introducing implicitly-declared members, checking for 5946 /// abstract types, etc. 5947 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5948 if (!Record) 5949 return; 5950 5951 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5952 AbstractUsageInfo Info(*this, Record); 5953 CheckAbstractClassUsage(Info, Record); 5954 } 5955 5956 // If this is not an aggregate type and has no user-declared constructor, 5957 // complain about any non-static data members of reference or const scalar 5958 // type, since they will never get initializers. 5959 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5960 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5961 !Record->isLambda()) { 5962 bool Complained = false; 5963 for (const auto *F : Record->fields()) { 5964 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5965 continue; 5966 5967 if (F->getType()->isReferenceType() || 5968 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5969 if (!Complained) { 5970 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5971 << Record->getTagKind() << Record; 5972 Complained = true; 5973 } 5974 5975 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5976 << F->getType()->isReferenceType() 5977 << F->getDeclName(); 5978 } 5979 } 5980 } 5981 5982 if (Record->getIdentifier()) { 5983 // C++ [class.mem]p13: 5984 // If T is the name of a class, then each of the following shall have a 5985 // name different from T: 5986 // - every member of every anonymous union that is a member of class T. 5987 // 5988 // C++ [class.mem]p14: 5989 // In addition, if class T has a user-declared constructor (12.1), every 5990 // non-static data member of class T shall have a name different from T. 5991 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5992 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5993 ++I) { 5994 NamedDecl *D = *I; 5995 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5996 isa<IndirectFieldDecl>(D)) { 5997 Diag(D->getLocation(), diag::err_member_name_of_class) 5998 << D->getDeclName(); 5999 break; 6000 } 6001 } 6002 } 6003 6004 // Warn if the class has virtual methods but non-virtual public destructor. 6005 if (Record->isPolymorphic() && !Record->isDependentType()) { 6006 CXXDestructorDecl *dtor = Record->getDestructor(); 6007 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6008 !Record->hasAttr<FinalAttr>()) 6009 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6010 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6011 } 6012 6013 if (Record->isAbstract()) { 6014 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6015 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6016 << FA->isSpelledAsSealed(); 6017 DiagnoseAbstractType(Record); 6018 } 6019 } 6020 6021 // See if trivial_abi has to be dropped. 6022 if (Record->hasAttr<TrivialABIAttr>()) 6023 checkIllFormedTrivialABIStruct(*Record); 6024 6025 // Set HasTrivialSpecialMemberForCall if the record has attribute 6026 // "trivial_abi". 6027 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6028 6029 if (HasTrivialABI) 6030 Record->setHasTrivialSpecialMemberForCall(); 6031 6032 bool HasMethodWithOverrideControl = false, 6033 HasOverridingMethodWithoutOverrideControl = false; 6034 if (!Record->isDependentType()) { 6035 for (auto *M : Record->methods()) { 6036 // See if a method overloads virtual methods in a base 6037 // class without overriding any. 6038 if (!M->isStatic()) 6039 DiagnoseHiddenVirtualMethods(M); 6040 if (M->hasAttr<OverrideAttr>()) 6041 HasMethodWithOverrideControl = true; 6042 else if (M->size_overridden_methods() > 0) 6043 HasOverridingMethodWithoutOverrideControl = true; 6044 // Check whether the explicitly-defaulted special members are valid. 6045 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6046 CheckExplicitlyDefaultedSpecialMember(M); 6047 6048 // For an explicitly defaulted or deleted special member, we defer 6049 // determining triviality until the class is complete. That time is now! 6050 CXXSpecialMember CSM = getSpecialMember(M); 6051 if (!M->isImplicit() && !M->isUserProvided()) { 6052 if (CSM != CXXInvalid) { 6053 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6054 // Inform the class that we've finished declaring this member. 6055 Record->finishedDefaultedOrDeletedMember(M); 6056 M->setTrivialForCall( 6057 HasTrivialABI || 6058 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6059 Record->setTrivialForCallFlags(M); 6060 } 6061 } 6062 6063 // Set triviality for the purpose of calls if this is a user-provided 6064 // copy/move constructor or destructor. 6065 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6066 CSM == CXXDestructor) && M->isUserProvided()) { 6067 M->setTrivialForCall(HasTrivialABI); 6068 Record->setTrivialForCallFlags(M); 6069 } 6070 6071 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6072 M->hasAttr<DLLExportAttr>()) { 6073 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6074 M->isTrivial() && 6075 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6076 CSM == CXXDestructor)) 6077 M->dropAttr<DLLExportAttr>(); 6078 6079 if (M->hasAttr<DLLExportAttr>()) { 6080 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6081 ActOnFinishInlineFunctionDef(M); 6082 } 6083 } 6084 } 6085 } 6086 6087 if (HasMethodWithOverrideControl && 6088 HasOverridingMethodWithoutOverrideControl) { 6089 // At least one method has the 'override' control declared. 6090 // Diagnose all other overridden methods which do not have 'override' specified on them. 6091 for (auto *M : Record->methods()) 6092 DiagnoseAbsenceOfOverrideControl(M); 6093 } 6094 6095 // ms_struct is a request to use the same ABI rules as MSVC. Check 6096 // whether this class uses any C++ features that are implemented 6097 // completely differently in MSVC, and if so, emit a diagnostic. 6098 // That diagnostic defaults to an error, but we allow projects to 6099 // map it down to a warning (or ignore it). It's a fairly common 6100 // practice among users of the ms_struct pragma to mass-annotate 6101 // headers, sweeping up a bunch of types that the project doesn't 6102 // really rely on MSVC-compatible layout for. We must therefore 6103 // support "ms_struct except for C++ stuff" as a secondary ABI. 6104 if (Record->isMsStruct(Context) && 6105 (Record->isPolymorphic() || Record->getNumBases())) { 6106 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6107 } 6108 6109 checkClassLevelDLLAttribute(Record); 6110 6111 bool ClangABICompat4 = 6112 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6113 TargetInfo::CallingConvKind CCK = 6114 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6115 bool CanPass = canPassInRegisters(*this, Record, CCK); 6116 6117 // Do not change ArgPassingRestrictions if it has already been set to 6118 // APK_CanNeverPassInRegs. 6119 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6120 Record->setArgPassingRestrictions(CanPass 6121 ? RecordDecl::APK_CanPassInRegs 6122 : RecordDecl::APK_CannotPassInRegs); 6123 6124 // If canPassInRegisters returns true despite the record having a non-trivial 6125 // destructor, the record is destructed in the callee. This happens only when 6126 // the record or one of its subobjects has a field annotated with trivial_abi 6127 // or a field qualified with ObjC __strong/__weak. 6128 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6129 Record->setParamDestroyedInCallee(true); 6130 else if (Record->hasNonTrivialDestructor()) 6131 Record->setParamDestroyedInCallee(CanPass); 6132 6133 if (getLangOpts().ForceEmitVTables) { 6134 // If we want to emit all the vtables, we need to mark it as used. This 6135 // is especially required for cases like vtable assumption loads. 6136 MarkVTableUsed(Record->getInnerLocStart(), Record); 6137 } 6138 } 6139 6140 /// Look up the special member function that would be called by a special 6141 /// member function for a subobject of class type. 6142 /// 6143 /// \param Class The class type of the subobject. 6144 /// \param CSM The kind of special member function. 6145 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6146 /// \param ConstRHS True if this is a copy operation with a const object 6147 /// on its RHS, that is, if the argument to the outer special member 6148 /// function is 'const' and this is not a field marked 'mutable'. 6149 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6150 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6151 unsigned FieldQuals, bool ConstRHS) { 6152 unsigned LHSQuals = 0; 6153 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6154 LHSQuals = FieldQuals; 6155 6156 unsigned RHSQuals = FieldQuals; 6157 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6158 RHSQuals = 0; 6159 else if (ConstRHS) 6160 RHSQuals |= Qualifiers::Const; 6161 6162 return S.LookupSpecialMember(Class, CSM, 6163 RHSQuals & Qualifiers::Const, 6164 RHSQuals & Qualifiers::Volatile, 6165 false, 6166 LHSQuals & Qualifiers::Const, 6167 LHSQuals & Qualifiers::Volatile); 6168 } 6169 6170 class Sema::InheritedConstructorInfo { 6171 Sema &S; 6172 SourceLocation UseLoc; 6173 6174 /// A mapping from the base classes through which the constructor was 6175 /// inherited to the using shadow declaration in that base class (or a null 6176 /// pointer if the constructor was declared in that base class). 6177 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6178 InheritedFromBases; 6179 6180 public: 6181 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6182 ConstructorUsingShadowDecl *Shadow) 6183 : S(S), UseLoc(UseLoc) { 6184 bool DiagnosedMultipleConstructedBases = false; 6185 CXXRecordDecl *ConstructedBase = nullptr; 6186 UsingDecl *ConstructedBaseUsing = nullptr; 6187 6188 // Find the set of such base class subobjects and check that there's a 6189 // unique constructed subobject. 6190 for (auto *D : Shadow->redecls()) { 6191 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6192 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6193 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6194 6195 InheritedFromBases.insert( 6196 std::make_pair(DNominatedBase->getCanonicalDecl(), 6197 DShadow->getNominatedBaseClassShadowDecl())); 6198 if (DShadow->constructsVirtualBase()) 6199 InheritedFromBases.insert( 6200 std::make_pair(DConstructedBase->getCanonicalDecl(), 6201 DShadow->getConstructedBaseClassShadowDecl())); 6202 else 6203 assert(DNominatedBase == DConstructedBase); 6204 6205 // [class.inhctor.init]p2: 6206 // If the constructor was inherited from multiple base class subobjects 6207 // of type B, the program is ill-formed. 6208 if (!ConstructedBase) { 6209 ConstructedBase = DConstructedBase; 6210 ConstructedBaseUsing = D->getUsingDecl(); 6211 } else if (ConstructedBase != DConstructedBase && 6212 !Shadow->isInvalidDecl()) { 6213 if (!DiagnosedMultipleConstructedBases) { 6214 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6215 << Shadow->getTargetDecl(); 6216 S.Diag(ConstructedBaseUsing->getLocation(), 6217 diag::note_ambiguous_inherited_constructor_using) 6218 << ConstructedBase; 6219 DiagnosedMultipleConstructedBases = true; 6220 } 6221 S.Diag(D->getUsingDecl()->getLocation(), 6222 diag::note_ambiguous_inherited_constructor_using) 6223 << DConstructedBase; 6224 } 6225 } 6226 6227 if (DiagnosedMultipleConstructedBases) 6228 Shadow->setInvalidDecl(); 6229 } 6230 6231 /// Find the constructor to use for inherited construction of a base class, 6232 /// and whether that base class constructor inherits the constructor from a 6233 /// virtual base class (in which case it won't actually invoke it). 6234 std::pair<CXXConstructorDecl *, bool> 6235 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6236 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6237 if (It == InheritedFromBases.end()) 6238 return std::make_pair(nullptr, false); 6239 6240 // This is an intermediary class. 6241 if (It->second) 6242 return std::make_pair( 6243 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6244 It->second->constructsVirtualBase()); 6245 6246 // This is the base class from which the constructor was inherited. 6247 return std::make_pair(Ctor, false); 6248 } 6249 }; 6250 6251 /// Is the special member function which would be selected to perform the 6252 /// specified operation on the specified class type a constexpr constructor? 6253 static bool 6254 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6255 Sema::CXXSpecialMember CSM, unsigned Quals, 6256 bool ConstRHS, 6257 CXXConstructorDecl *InheritedCtor = nullptr, 6258 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6259 // If we're inheriting a constructor, see if we need to call it for this base 6260 // class. 6261 if (InheritedCtor) { 6262 assert(CSM == Sema::CXXDefaultConstructor); 6263 auto BaseCtor = 6264 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6265 if (BaseCtor) 6266 return BaseCtor->isConstexpr(); 6267 } 6268 6269 if (CSM == Sema::CXXDefaultConstructor) 6270 return ClassDecl->hasConstexprDefaultConstructor(); 6271 6272 Sema::SpecialMemberOverloadResult SMOR = 6273 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6274 if (!SMOR.getMethod()) 6275 // A constructor we wouldn't select can't be "involved in initializing" 6276 // anything. 6277 return true; 6278 return SMOR.getMethod()->isConstexpr(); 6279 } 6280 6281 /// Determine whether the specified special member function would be constexpr 6282 /// if it were implicitly defined. 6283 static bool defaultedSpecialMemberIsConstexpr( 6284 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6285 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6286 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6287 if (!S.getLangOpts().CPlusPlus11) 6288 return false; 6289 6290 // C++11 [dcl.constexpr]p4: 6291 // In the definition of a constexpr constructor [...] 6292 bool Ctor = true; 6293 switch (CSM) { 6294 case Sema::CXXDefaultConstructor: 6295 if (Inherited) 6296 break; 6297 // Since default constructor lookup is essentially trivial (and cannot 6298 // involve, for instance, template instantiation), we compute whether a 6299 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6300 // 6301 // This is important for performance; we need to know whether the default 6302 // constructor is constexpr to determine whether the type is a literal type. 6303 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6304 6305 case Sema::CXXCopyConstructor: 6306 case Sema::CXXMoveConstructor: 6307 // For copy or move constructors, we need to perform overload resolution. 6308 break; 6309 6310 case Sema::CXXCopyAssignment: 6311 case Sema::CXXMoveAssignment: 6312 if (!S.getLangOpts().CPlusPlus14) 6313 return false; 6314 // In C++1y, we need to perform overload resolution. 6315 Ctor = false; 6316 break; 6317 6318 case Sema::CXXDestructor: 6319 case Sema::CXXInvalid: 6320 return false; 6321 } 6322 6323 // -- if the class is a non-empty union, or for each non-empty anonymous 6324 // union member of a non-union class, exactly one non-static data member 6325 // shall be initialized; [DR1359] 6326 // 6327 // If we squint, this is guaranteed, since exactly one non-static data member 6328 // will be initialized (if the constructor isn't deleted), we just don't know 6329 // which one. 6330 if (Ctor && ClassDecl->isUnion()) 6331 return CSM == Sema::CXXDefaultConstructor 6332 ? ClassDecl->hasInClassInitializer() || 6333 !ClassDecl->hasVariantMembers() 6334 : true; 6335 6336 // -- the class shall not have any virtual base classes; 6337 if (Ctor && ClassDecl->getNumVBases()) 6338 return false; 6339 6340 // C++1y [class.copy]p26: 6341 // -- [the class] is a literal type, and 6342 if (!Ctor && !ClassDecl->isLiteral()) 6343 return false; 6344 6345 // -- every constructor involved in initializing [...] base class 6346 // sub-objects shall be a constexpr constructor; 6347 // -- the assignment operator selected to copy/move each direct base 6348 // class is a constexpr function, and 6349 for (const auto &B : ClassDecl->bases()) { 6350 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6351 if (!BaseType) continue; 6352 6353 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6354 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6355 InheritedCtor, Inherited)) 6356 return false; 6357 } 6358 6359 // -- every constructor involved in initializing non-static data members 6360 // [...] shall be a constexpr constructor; 6361 // -- every non-static data member and base class sub-object shall be 6362 // initialized 6363 // -- for each non-static data member of X that is of class type (or array 6364 // thereof), the assignment operator selected to copy/move that member is 6365 // a constexpr function 6366 for (const auto *F : ClassDecl->fields()) { 6367 if (F->isInvalidDecl()) 6368 continue; 6369 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6370 continue; 6371 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6372 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6373 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6374 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6375 BaseType.getCVRQualifiers(), 6376 ConstArg && !F->isMutable())) 6377 return false; 6378 } else if (CSM == Sema::CXXDefaultConstructor) { 6379 return false; 6380 } 6381 } 6382 6383 // All OK, it's constexpr! 6384 return true; 6385 } 6386 6387 static Sema::ImplicitExceptionSpecification 6388 ComputeDefaultedSpecialMemberExceptionSpec( 6389 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6390 Sema::InheritedConstructorInfo *ICI); 6391 6392 static Sema::ImplicitExceptionSpecification 6393 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6394 auto CSM = S.getSpecialMember(MD); 6395 if (CSM != Sema::CXXInvalid) 6396 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6397 6398 auto *CD = cast<CXXConstructorDecl>(MD); 6399 assert(CD->getInheritedConstructor() && 6400 "only special members have implicit exception specs"); 6401 Sema::InheritedConstructorInfo ICI( 6402 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6403 return ComputeDefaultedSpecialMemberExceptionSpec( 6404 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6405 } 6406 6407 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6408 CXXMethodDecl *MD) { 6409 FunctionProtoType::ExtProtoInfo EPI; 6410 6411 // Build an exception specification pointing back at this member. 6412 EPI.ExceptionSpec.Type = EST_Unevaluated; 6413 EPI.ExceptionSpec.SourceDecl = MD; 6414 6415 // Set the calling convention to the default for C++ instance methods. 6416 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6417 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6418 /*IsCXXMethod=*/true)); 6419 return EPI; 6420 } 6421 6422 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6423 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6424 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6425 return; 6426 6427 // Evaluate the exception specification. 6428 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6429 auto ESI = IES.getExceptionSpec(); 6430 6431 // Update the type of the special member to use it. 6432 UpdateExceptionSpec(MD, ESI); 6433 6434 // A user-provided destructor can be defined outside the class. When that 6435 // happens, be sure to update the exception specification on both 6436 // declarations. 6437 const FunctionProtoType *CanonicalFPT = 6438 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6439 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6440 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6441 } 6442 6443 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6444 CXXRecordDecl *RD = MD->getParent(); 6445 CXXSpecialMember CSM = getSpecialMember(MD); 6446 6447 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6448 "not an explicitly-defaulted special member"); 6449 6450 // Whether this was the first-declared instance of the constructor. 6451 // This affects whether we implicitly add an exception spec and constexpr. 6452 bool First = MD == MD->getCanonicalDecl(); 6453 6454 bool HadError = false; 6455 6456 // C++11 [dcl.fct.def.default]p1: 6457 // A function that is explicitly defaulted shall 6458 // -- be a special member function (checked elsewhere), 6459 // -- have the same type (except for ref-qualifiers, and except that a 6460 // copy operation can take a non-const reference) as an implicit 6461 // declaration, and 6462 // -- not have default arguments. 6463 unsigned ExpectedParams = 1; 6464 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6465 ExpectedParams = 0; 6466 if (MD->getNumParams() != ExpectedParams) { 6467 // This also checks for default arguments: a copy or move constructor with a 6468 // default argument is classified as a default constructor, and assignment 6469 // operations and destructors can't have default arguments. 6470 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6471 << CSM << MD->getSourceRange(); 6472 HadError = true; 6473 } else if (MD->isVariadic()) { 6474 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6475 << CSM << MD->getSourceRange(); 6476 HadError = true; 6477 } 6478 6479 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6480 6481 bool CanHaveConstParam = false; 6482 if (CSM == CXXCopyConstructor) 6483 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6484 else if (CSM == CXXCopyAssignment) 6485 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6486 6487 QualType ReturnType = Context.VoidTy; 6488 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6489 // Check for return type matching. 6490 ReturnType = Type->getReturnType(); 6491 QualType ExpectedReturnType = 6492 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6493 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6494 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6495 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6496 HadError = true; 6497 } 6498 6499 // A defaulted special member cannot have cv-qualifiers. 6500 if (Type->getTypeQuals()) { 6501 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6502 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6503 HadError = true; 6504 } 6505 } 6506 6507 // Check for parameter type matching. 6508 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6509 bool HasConstParam = false; 6510 if (ExpectedParams && ArgType->isReferenceType()) { 6511 // Argument must be reference to possibly-const T. 6512 QualType ReferentType = ArgType->getPointeeType(); 6513 HasConstParam = ReferentType.isConstQualified(); 6514 6515 if (ReferentType.isVolatileQualified()) { 6516 Diag(MD->getLocation(), 6517 diag::err_defaulted_special_member_volatile_param) << CSM; 6518 HadError = true; 6519 } 6520 6521 if (HasConstParam && !CanHaveConstParam) { 6522 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6523 Diag(MD->getLocation(), 6524 diag::err_defaulted_special_member_copy_const_param) 6525 << (CSM == CXXCopyAssignment); 6526 // FIXME: Explain why this special member can't be const. 6527 } else { 6528 Diag(MD->getLocation(), 6529 diag::err_defaulted_special_member_move_const_param) 6530 << (CSM == CXXMoveAssignment); 6531 } 6532 HadError = true; 6533 } 6534 } else if (ExpectedParams) { 6535 // A copy assignment operator can take its argument by value, but a 6536 // defaulted one cannot. 6537 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6538 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6539 HadError = true; 6540 } 6541 6542 // C++11 [dcl.fct.def.default]p2: 6543 // An explicitly-defaulted function may be declared constexpr only if it 6544 // would have been implicitly declared as constexpr, 6545 // Do not apply this rule to members of class templates, since core issue 1358 6546 // makes such functions always instantiate to constexpr functions. For 6547 // functions which cannot be constexpr (for non-constructors in C++11 and for 6548 // destructors in C++1y), this is checked elsewhere. 6549 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6550 HasConstParam); 6551 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6552 : isa<CXXConstructorDecl>(MD)) && 6553 MD->isConstexpr() && !Constexpr && 6554 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6555 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6556 // FIXME: Explain why the special member can't be constexpr. 6557 HadError = true; 6558 } 6559 6560 // and may have an explicit exception-specification only if it is compatible 6561 // with the exception-specification on the implicit declaration. 6562 if (Type->hasExceptionSpec()) { 6563 // Delay the check if this is the first declaration of the special member, 6564 // since we may not have parsed some necessary in-class initializers yet. 6565 if (First) { 6566 // If the exception specification needs to be instantiated, do so now, 6567 // before we clobber it with an EST_Unevaluated specification below. 6568 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6569 InstantiateExceptionSpec(MD->getLocStart(), MD); 6570 Type = MD->getType()->getAs<FunctionProtoType>(); 6571 } 6572 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6573 } else 6574 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6575 } 6576 6577 // If a function is explicitly defaulted on its first declaration, 6578 if (First) { 6579 // -- it is implicitly considered to be constexpr if the implicit 6580 // definition would be, 6581 MD->setConstexpr(Constexpr); 6582 6583 // -- it is implicitly considered to have the same exception-specification 6584 // as if it had been implicitly declared, 6585 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6586 EPI.ExceptionSpec.Type = EST_Unevaluated; 6587 EPI.ExceptionSpec.SourceDecl = MD; 6588 MD->setType(Context.getFunctionType(ReturnType, 6589 llvm::makeArrayRef(&ArgType, 6590 ExpectedParams), 6591 EPI)); 6592 } 6593 6594 if (ShouldDeleteSpecialMember(MD, CSM)) { 6595 if (First) { 6596 SetDeclDeleted(MD, MD->getLocation()); 6597 } else { 6598 // C++11 [dcl.fct.def.default]p4: 6599 // [For a] user-provided explicitly-defaulted function [...] if such a 6600 // function is implicitly defined as deleted, the program is ill-formed. 6601 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6602 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6603 HadError = true; 6604 } 6605 } 6606 6607 if (HadError) 6608 MD->setInvalidDecl(); 6609 } 6610 6611 /// Check whether the exception specification provided for an 6612 /// explicitly-defaulted special member matches the exception specification 6613 /// that would have been generated for an implicit special member, per 6614 /// C++11 [dcl.fct.def.default]p2. 6615 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6616 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6617 // If the exception specification was explicitly specified but hadn't been 6618 // parsed when the method was defaulted, grab it now. 6619 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6620 SpecifiedType = 6621 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6622 6623 // Compute the implicit exception specification. 6624 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6625 /*IsCXXMethod=*/true); 6626 FunctionProtoType::ExtProtoInfo EPI(CC); 6627 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6628 EPI.ExceptionSpec = IES.getExceptionSpec(); 6629 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6630 Context.getFunctionType(Context.VoidTy, None, EPI)); 6631 6632 // Ensure that it matches. 6633 CheckEquivalentExceptionSpec( 6634 PDiag(diag::err_incorrect_defaulted_exception_spec) 6635 << getSpecialMember(MD), PDiag(), 6636 ImplicitType, SourceLocation(), 6637 SpecifiedType, MD->getLocation()); 6638 } 6639 6640 void Sema::CheckDelayedMemberExceptionSpecs() { 6641 decltype(DelayedExceptionSpecChecks) Checks; 6642 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6643 6644 std::swap(Checks, DelayedExceptionSpecChecks); 6645 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6646 6647 // Perform any deferred checking of exception specifications for virtual 6648 // destructors. 6649 for (auto &Check : Checks) 6650 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6651 6652 // Check that any explicitly-defaulted methods have exception specifications 6653 // compatible with their implicit exception specifications. 6654 for (auto &Spec : Specs) 6655 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6656 } 6657 6658 namespace { 6659 /// CRTP base class for visiting operations performed by a special member 6660 /// function (or inherited constructor). 6661 template<typename Derived> 6662 struct SpecialMemberVisitor { 6663 Sema &S; 6664 CXXMethodDecl *MD; 6665 Sema::CXXSpecialMember CSM; 6666 Sema::InheritedConstructorInfo *ICI; 6667 6668 // Properties of the special member, computed for convenience. 6669 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6670 6671 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6672 Sema::InheritedConstructorInfo *ICI) 6673 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6674 switch (CSM) { 6675 case Sema::CXXDefaultConstructor: 6676 case Sema::CXXCopyConstructor: 6677 case Sema::CXXMoveConstructor: 6678 IsConstructor = true; 6679 break; 6680 case Sema::CXXCopyAssignment: 6681 case Sema::CXXMoveAssignment: 6682 IsAssignment = true; 6683 break; 6684 case Sema::CXXDestructor: 6685 break; 6686 case Sema::CXXInvalid: 6687 llvm_unreachable("invalid special member kind"); 6688 } 6689 6690 if (MD->getNumParams()) { 6691 if (const ReferenceType *RT = 6692 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6693 ConstArg = RT->getPointeeType().isConstQualified(); 6694 } 6695 } 6696 6697 Derived &getDerived() { return static_cast<Derived&>(*this); } 6698 6699 /// Is this a "move" special member? 6700 bool isMove() const { 6701 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6702 } 6703 6704 /// Look up the corresponding special member in the given class. 6705 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6706 unsigned Quals, bool IsMutable) { 6707 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6708 ConstArg && !IsMutable); 6709 } 6710 6711 /// Look up the constructor for the specified base class to see if it's 6712 /// overridden due to this being an inherited constructor. 6713 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6714 if (!ICI) 6715 return {}; 6716 assert(CSM == Sema::CXXDefaultConstructor); 6717 auto *BaseCtor = 6718 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6719 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6720 return MD; 6721 return {}; 6722 } 6723 6724 /// A base or member subobject. 6725 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6726 6727 /// Get the location to use for a subobject in diagnostics. 6728 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6729 // FIXME: For an indirect virtual base, the direct base leading to 6730 // the indirect virtual base would be a more useful choice. 6731 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6732 return B->getBaseTypeLoc(); 6733 else 6734 return Subobj.get<FieldDecl*>()->getLocation(); 6735 } 6736 6737 enum BasesToVisit { 6738 /// Visit all non-virtual (direct) bases. 6739 VisitNonVirtualBases, 6740 /// Visit all direct bases, virtual or not. 6741 VisitDirectBases, 6742 /// Visit all non-virtual bases, and all virtual bases if the class 6743 /// is not abstract. 6744 VisitPotentiallyConstructedBases, 6745 /// Visit all direct or virtual bases. 6746 VisitAllBases 6747 }; 6748 6749 // Visit the bases and members of the class. 6750 bool visit(BasesToVisit Bases) { 6751 CXXRecordDecl *RD = MD->getParent(); 6752 6753 if (Bases == VisitPotentiallyConstructedBases) 6754 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6755 6756 for (auto &B : RD->bases()) 6757 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6758 getDerived().visitBase(&B)) 6759 return true; 6760 6761 if (Bases == VisitAllBases) 6762 for (auto &B : RD->vbases()) 6763 if (getDerived().visitBase(&B)) 6764 return true; 6765 6766 for (auto *F : RD->fields()) 6767 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6768 getDerived().visitField(F)) 6769 return true; 6770 6771 return false; 6772 } 6773 }; 6774 } 6775 6776 namespace { 6777 struct SpecialMemberDeletionInfo 6778 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6779 bool Diagnose; 6780 6781 SourceLocation Loc; 6782 6783 bool AllFieldsAreConst; 6784 6785 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6786 Sema::CXXSpecialMember CSM, 6787 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6788 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6789 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6790 6791 bool inUnion() const { return MD->getParent()->isUnion(); } 6792 6793 Sema::CXXSpecialMember getEffectiveCSM() { 6794 return ICI ? Sema::CXXInvalid : CSM; 6795 } 6796 6797 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6798 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6799 6800 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6801 bool shouldDeleteForField(FieldDecl *FD); 6802 bool shouldDeleteForAllConstMembers(); 6803 6804 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6805 unsigned Quals); 6806 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6807 Sema::SpecialMemberOverloadResult SMOR, 6808 bool IsDtorCallInCtor); 6809 6810 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6811 }; 6812 } 6813 6814 /// Is the given special member inaccessible when used on the given 6815 /// sub-object. 6816 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6817 CXXMethodDecl *target) { 6818 /// If we're operating on a base class, the object type is the 6819 /// type of this special member. 6820 QualType objectTy; 6821 AccessSpecifier access = target->getAccess(); 6822 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6823 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6824 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6825 6826 // If we're operating on a field, the object type is the type of the field. 6827 } else { 6828 objectTy = S.Context.getTypeDeclType(target->getParent()); 6829 } 6830 6831 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6832 } 6833 6834 /// Check whether we should delete a special member due to the implicit 6835 /// definition containing a call to a special member of a subobject. 6836 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6837 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6838 bool IsDtorCallInCtor) { 6839 CXXMethodDecl *Decl = SMOR.getMethod(); 6840 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6841 6842 int DiagKind = -1; 6843 6844 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6845 DiagKind = !Decl ? 0 : 1; 6846 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6847 DiagKind = 2; 6848 else if (!isAccessible(Subobj, Decl)) 6849 DiagKind = 3; 6850 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6851 !Decl->isTrivial()) { 6852 // A member of a union must have a trivial corresponding special member. 6853 // As a weird special case, a destructor call from a union's constructor 6854 // must be accessible and non-deleted, but need not be trivial. Such a 6855 // destructor is never actually called, but is semantically checked as 6856 // if it were. 6857 DiagKind = 4; 6858 } 6859 6860 if (DiagKind == -1) 6861 return false; 6862 6863 if (Diagnose) { 6864 if (Field) { 6865 S.Diag(Field->getLocation(), 6866 diag::note_deleted_special_member_class_subobject) 6867 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6868 << Field << DiagKind << IsDtorCallInCtor; 6869 } else { 6870 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6871 S.Diag(Base->getLocStart(), 6872 diag::note_deleted_special_member_class_subobject) 6873 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6874 << Base->getType() << DiagKind << IsDtorCallInCtor; 6875 } 6876 6877 if (DiagKind == 1) 6878 S.NoteDeletedFunction(Decl); 6879 // FIXME: Explain inaccessibility if DiagKind == 3. 6880 } 6881 6882 return true; 6883 } 6884 6885 /// Check whether we should delete a special member function due to having a 6886 /// direct or virtual base class or non-static data member of class type M. 6887 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6888 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6889 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6890 bool IsMutable = Field && Field->isMutable(); 6891 6892 // C++11 [class.ctor]p5: 6893 // -- any direct or virtual base class, or non-static data member with no 6894 // brace-or-equal-initializer, has class type M (or array thereof) and 6895 // either M has no default constructor or overload resolution as applied 6896 // to M's default constructor results in an ambiguity or in a function 6897 // that is deleted or inaccessible 6898 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6899 // -- a direct or virtual base class B that cannot be copied/moved because 6900 // overload resolution, as applied to B's corresponding special member, 6901 // results in an ambiguity or a function that is deleted or inaccessible 6902 // from the defaulted special member 6903 // C++11 [class.dtor]p5: 6904 // -- any direct or virtual base class [...] has a type with a destructor 6905 // that is deleted or inaccessible 6906 if (!(CSM == Sema::CXXDefaultConstructor && 6907 Field && Field->hasInClassInitializer()) && 6908 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6909 false)) 6910 return true; 6911 6912 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6913 // -- any direct or virtual base class or non-static data member has a 6914 // type with a destructor that is deleted or inaccessible 6915 if (IsConstructor) { 6916 Sema::SpecialMemberOverloadResult SMOR = 6917 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6918 false, false, false, false, false); 6919 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6920 return true; 6921 } 6922 6923 return false; 6924 } 6925 6926 /// Check whether we should delete a special member function due to the class 6927 /// having a particular direct or virtual base class. 6928 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6929 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6930 // If program is correct, BaseClass cannot be null, but if it is, the error 6931 // must be reported elsewhere. 6932 if (!BaseClass) 6933 return false; 6934 // If we have an inheriting constructor, check whether we're calling an 6935 // inherited constructor instead of a default constructor. 6936 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6937 if (auto *BaseCtor = SMOR.getMethod()) { 6938 // Note that we do not check access along this path; other than that, 6939 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6940 // FIXME: Check that the base has a usable destructor! Sink this into 6941 // shouldDeleteForClassSubobject. 6942 if (BaseCtor->isDeleted() && Diagnose) { 6943 S.Diag(Base->getLocStart(), 6944 diag::note_deleted_special_member_class_subobject) 6945 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6946 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6947 S.NoteDeletedFunction(BaseCtor); 6948 } 6949 return BaseCtor->isDeleted(); 6950 } 6951 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6952 } 6953 6954 /// Check whether we should delete a special member function due to the class 6955 /// having a particular non-static data member. 6956 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6957 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6958 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6959 6960 if (CSM == Sema::CXXDefaultConstructor) { 6961 // For a default constructor, all references must be initialized in-class 6962 // and, if a union, it must have a non-const member. 6963 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6964 if (Diagnose) 6965 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6966 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6967 return true; 6968 } 6969 // C++11 [class.ctor]p5: any non-variant non-static data member of 6970 // const-qualified type (or array thereof) with no 6971 // brace-or-equal-initializer does not have a user-provided default 6972 // constructor. 6973 if (!inUnion() && FieldType.isConstQualified() && 6974 !FD->hasInClassInitializer() && 6975 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6976 if (Diagnose) 6977 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6978 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6979 return true; 6980 } 6981 6982 if (inUnion() && !FieldType.isConstQualified()) 6983 AllFieldsAreConst = false; 6984 } else if (CSM == Sema::CXXCopyConstructor) { 6985 // For a copy constructor, data members must not be of rvalue reference 6986 // type. 6987 if (FieldType->isRValueReferenceType()) { 6988 if (Diagnose) 6989 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6990 << MD->getParent() << FD << FieldType; 6991 return true; 6992 } 6993 } else if (IsAssignment) { 6994 // For an assignment operator, data members must not be of reference type. 6995 if (FieldType->isReferenceType()) { 6996 if (Diagnose) 6997 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6998 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6999 return true; 7000 } 7001 if (!FieldRecord && FieldType.isConstQualified()) { 7002 // C++11 [class.copy]p23: 7003 // -- a non-static data member of const non-class type (or array thereof) 7004 if (Diagnose) 7005 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7006 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7007 return true; 7008 } 7009 } 7010 7011 if (FieldRecord) { 7012 // Some additional restrictions exist on the variant members. 7013 if (!inUnion() && FieldRecord->isUnion() && 7014 FieldRecord->isAnonymousStructOrUnion()) { 7015 bool AllVariantFieldsAreConst = true; 7016 7017 // FIXME: Handle anonymous unions declared within anonymous unions. 7018 for (auto *UI : FieldRecord->fields()) { 7019 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7020 7021 if (!UnionFieldType.isConstQualified()) 7022 AllVariantFieldsAreConst = false; 7023 7024 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7025 if (UnionFieldRecord && 7026 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7027 UnionFieldType.getCVRQualifiers())) 7028 return true; 7029 } 7030 7031 // At least one member in each anonymous union must be non-const 7032 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7033 !FieldRecord->field_empty()) { 7034 if (Diagnose) 7035 S.Diag(FieldRecord->getLocation(), 7036 diag::note_deleted_default_ctor_all_const) 7037 << !!ICI << MD->getParent() << /*anonymous union*/1; 7038 return true; 7039 } 7040 7041 // Don't check the implicit member of the anonymous union type. 7042 // This is technically non-conformant, but sanity demands it. 7043 return false; 7044 } 7045 7046 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7047 FieldType.getCVRQualifiers())) 7048 return true; 7049 } 7050 7051 return false; 7052 } 7053 7054 /// C++11 [class.ctor] p5: 7055 /// A defaulted default constructor for a class X is defined as deleted if 7056 /// X is a union and all of its variant members are of const-qualified type. 7057 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7058 // This is a silly definition, because it gives an empty union a deleted 7059 // default constructor. Don't do that. 7060 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7061 bool AnyFields = false; 7062 for (auto *F : MD->getParent()->fields()) 7063 if ((AnyFields = !F->isUnnamedBitfield())) 7064 break; 7065 if (!AnyFields) 7066 return false; 7067 if (Diagnose) 7068 S.Diag(MD->getParent()->getLocation(), 7069 diag::note_deleted_default_ctor_all_const) 7070 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7071 return true; 7072 } 7073 return false; 7074 } 7075 7076 /// Determine whether a defaulted special member function should be defined as 7077 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7078 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7079 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7080 InheritedConstructorInfo *ICI, 7081 bool Diagnose) { 7082 if (MD->isInvalidDecl()) 7083 return false; 7084 CXXRecordDecl *RD = MD->getParent(); 7085 assert(!RD->isDependentType() && "do deletion after instantiation"); 7086 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7087 return false; 7088 7089 // C++11 [expr.lambda.prim]p19: 7090 // The closure type associated with a lambda-expression has a 7091 // deleted (8.4.3) default constructor and a deleted copy 7092 // assignment operator. 7093 if (RD->isLambda() && 7094 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7095 if (Diagnose) 7096 Diag(RD->getLocation(), diag::note_lambda_decl); 7097 return true; 7098 } 7099 7100 // For an anonymous struct or union, the copy and assignment special members 7101 // will never be used, so skip the check. For an anonymous union declared at 7102 // namespace scope, the constructor and destructor are used. 7103 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7104 RD->isAnonymousStructOrUnion()) 7105 return false; 7106 7107 // C++11 [class.copy]p7, p18: 7108 // If the class definition declares a move constructor or move assignment 7109 // operator, an implicitly declared copy constructor or copy assignment 7110 // operator is defined as deleted. 7111 if (MD->isImplicit() && 7112 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7113 CXXMethodDecl *UserDeclaredMove = nullptr; 7114 7115 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7116 // deletion of the corresponding copy operation, not both copy operations. 7117 // MSVC 2015 has adopted the standards conforming behavior. 7118 bool DeletesOnlyMatchingCopy = 7119 getLangOpts().MSVCCompat && 7120 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7121 7122 if (RD->hasUserDeclaredMoveConstructor() && 7123 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7124 if (!Diagnose) return true; 7125 7126 // Find any user-declared move constructor. 7127 for (auto *I : RD->ctors()) { 7128 if (I->isMoveConstructor()) { 7129 UserDeclaredMove = I; 7130 break; 7131 } 7132 } 7133 assert(UserDeclaredMove); 7134 } else if (RD->hasUserDeclaredMoveAssignment() && 7135 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7136 if (!Diagnose) return true; 7137 7138 // Find any user-declared move assignment operator. 7139 for (auto *I : RD->methods()) { 7140 if (I->isMoveAssignmentOperator()) { 7141 UserDeclaredMove = I; 7142 break; 7143 } 7144 } 7145 assert(UserDeclaredMove); 7146 } 7147 7148 if (UserDeclaredMove) { 7149 Diag(UserDeclaredMove->getLocation(), 7150 diag::note_deleted_copy_user_declared_move) 7151 << (CSM == CXXCopyAssignment) << RD 7152 << UserDeclaredMove->isMoveAssignmentOperator(); 7153 return true; 7154 } 7155 } 7156 7157 // Do access control from the special member function 7158 ContextRAII MethodContext(*this, MD); 7159 7160 // C++11 [class.dtor]p5: 7161 // -- for a virtual destructor, lookup of the non-array deallocation function 7162 // results in an ambiguity or in a function that is deleted or inaccessible 7163 if (CSM == CXXDestructor && MD->isVirtual()) { 7164 FunctionDecl *OperatorDelete = nullptr; 7165 DeclarationName Name = 7166 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7167 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7168 OperatorDelete, /*Diagnose*/false)) { 7169 if (Diagnose) 7170 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7171 return true; 7172 } 7173 } 7174 7175 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7176 7177 // Per DR1611, do not consider virtual bases of constructors of abstract 7178 // classes, since we are not going to construct them. 7179 // Per DR1658, do not consider virtual bases of destructors of abstract 7180 // classes either. 7181 // Per DR2180, for assignment operators we only assign (and thus only 7182 // consider) direct bases. 7183 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7184 : SMI.VisitPotentiallyConstructedBases)) 7185 return true; 7186 7187 if (SMI.shouldDeleteForAllConstMembers()) 7188 return true; 7189 7190 if (getLangOpts().CUDA) { 7191 // We should delete the special member in CUDA mode if target inference 7192 // failed. 7193 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7194 Diagnose); 7195 } 7196 7197 return false; 7198 } 7199 7200 /// Perform lookup for a special member of the specified kind, and determine 7201 /// whether it is trivial. If the triviality can be determined without the 7202 /// lookup, skip it. This is intended for use when determining whether a 7203 /// special member of a containing object is trivial, and thus does not ever 7204 /// perform overload resolution for default constructors. 7205 /// 7206 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7207 /// member that was most likely to be intended to be trivial, if any. 7208 /// 7209 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7210 /// determine whether the special member is trivial. 7211 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7212 Sema::CXXSpecialMember CSM, unsigned Quals, 7213 bool ConstRHS, 7214 Sema::TrivialABIHandling TAH, 7215 CXXMethodDecl **Selected) { 7216 if (Selected) 7217 *Selected = nullptr; 7218 7219 switch (CSM) { 7220 case Sema::CXXInvalid: 7221 llvm_unreachable("not a special member"); 7222 7223 case Sema::CXXDefaultConstructor: 7224 // C++11 [class.ctor]p5: 7225 // A default constructor is trivial if: 7226 // - all the [direct subobjects] have trivial default constructors 7227 // 7228 // Note, no overload resolution is performed in this case. 7229 if (RD->hasTrivialDefaultConstructor()) 7230 return true; 7231 7232 if (Selected) { 7233 // If there's a default constructor which could have been trivial, dig it 7234 // out. Otherwise, if there's any user-provided default constructor, point 7235 // to that as an example of why there's not a trivial one. 7236 CXXConstructorDecl *DefCtor = nullptr; 7237 if (RD->needsImplicitDefaultConstructor()) 7238 S.DeclareImplicitDefaultConstructor(RD); 7239 for (auto *CI : RD->ctors()) { 7240 if (!CI->isDefaultConstructor()) 7241 continue; 7242 DefCtor = CI; 7243 if (!DefCtor->isUserProvided()) 7244 break; 7245 } 7246 7247 *Selected = DefCtor; 7248 } 7249 7250 return false; 7251 7252 case Sema::CXXDestructor: 7253 // C++11 [class.dtor]p5: 7254 // A destructor is trivial if: 7255 // - all the direct [subobjects] have trivial destructors 7256 if (RD->hasTrivialDestructor() || 7257 (TAH == Sema::TAH_ConsiderTrivialABI && 7258 RD->hasTrivialDestructorForCall())) 7259 return true; 7260 7261 if (Selected) { 7262 if (RD->needsImplicitDestructor()) 7263 S.DeclareImplicitDestructor(RD); 7264 *Selected = RD->getDestructor(); 7265 } 7266 7267 return false; 7268 7269 case Sema::CXXCopyConstructor: 7270 // C++11 [class.copy]p12: 7271 // A copy constructor is trivial if: 7272 // - the constructor selected to copy each direct [subobject] is trivial 7273 if (RD->hasTrivialCopyConstructor() || 7274 (TAH == Sema::TAH_ConsiderTrivialABI && 7275 RD->hasTrivialCopyConstructorForCall())) { 7276 if (Quals == Qualifiers::Const) 7277 // We must either select the trivial copy constructor or reach an 7278 // ambiguity; no need to actually perform overload resolution. 7279 return true; 7280 } else if (!Selected) { 7281 return false; 7282 } 7283 // In C++98, we are not supposed to perform overload resolution here, but we 7284 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7285 // cases like B as having a non-trivial copy constructor: 7286 // struct A { template<typename T> A(T&); }; 7287 // struct B { mutable A a; }; 7288 goto NeedOverloadResolution; 7289 7290 case Sema::CXXCopyAssignment: 7291 // C++11 [class.copy]p25: 7292 // A copy assignment operator is trivial if: 7293 // - the assignment operator selected to copy each direct [subobject] is 7294 // trivial 7295 if (RD->hasTrivialCopyAssignment()) { 7296 if (Quals == Qualifiers::Const) 7297 return true; 7298 } else if (!Selected) { 7299 return false; 7300 } 7301 // In C++98, we are not supposed to perform overload resolution here, but we 7302 // treat that as a language defect. 7303 goto NeedOverloadResolution; 7304 7305 case Sema::CXXMoveConstructor: 7306 case Sema::CXXMoveAssignment: 7307 NeedOverloadResolution: 7308 Sema::SpecialMemberOverloadResult SMOR = 7309 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7310 7311 // The standard doesn't describe how to behave if the lookup is ambiguous. 7312 // We treat it as not making the member non-trivial, just like the standard 7313 // mandates for the default constructor. This should rarely matter, because 7314 // the member will also be deleted. 7315 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7316 return true; 7317 7318 if (!SMOR.getMethod()) { 7319 assert(SMOR.getKind() == 7320 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7321 return false; 7322 } 7323 7324 // We deliberately don't check if we found a deleted special member. We're 7325 // not supposed to! 7326 if (Selected) 7327 *Selected = SMOR.getMethod(); 7328 7329 if (TAH == Sema::TAH_ConsiderTrivialABI && 7330 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7331 return SMOR.getMethod()->isTrivialForCall(); 7332 return SMOR.getMethod()->isTrivial(); 7333 } 7334 7335 llvm_unreachable("unknown special method kind"); 7336 } 7337 7338 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7339 for (auto *CI : RD->ctors()) 7340 if (!CI->isImplicit()) 7341 return CI; 7342 7343 // Look for constructor templates. 7344 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7345 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7346 if (CXXConstructorDecl *CD = 7347 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7348 return CD; 7349 } 7350 7351 return nullptr; 7352 } 7353 7354 /// The kind of subobject we are checking for triviality. The values of this 7355 /// enumeration are used in diagnostics. 7356 enum TrivialSubobjectKind { 7357 /// The subobject is a base class. 7358 TSK_BaseClass, 7359 /// The subobject is a non-static data member. 7360 TSK_Field, 7361 /// The object is actually the complete object. 7362 TSK_CompleteObject 7363 }; 7364 7365 /// Check whether the special member selected for a given type would be trivial. 7366 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7367 QualType SubType, bool ConstRHS, 7368 Sema::CXXSpecialMember CSM, 7369 TrivialSubobjectKind Kind, 7370 Sema::TrivialABIHandling TAH, bool Diagnose) { 7371 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7372 if (!SubRD) 7373 return true; 7374 7375 CXXMethodDecl *Selected; 7376 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7377 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7378 return true; 7379 7380 if (Diagnose) { 7381 if (ConstRHS) 7382 SubType.addConst(); 7383 7384 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7385 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7386 << Kind << SubType.getUnqualifiedType(); 7387 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7388 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7389 } else if (!Selected) 7390 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7391 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7392 else if (Selected->isUserProvided()) { 7393 if (Kind == TSK_CompleteObject) 7394 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7395 << Kind << SubType.getUnqualifiedType() << CSM; 7396 else { 7397 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7398 << Kind << SubType.getUnqualifiedType() << CSM; 7399 S.Diag(Selected->getLocation(), diag::note_declared_at); 7400 } 7401 } else { 7402 if (Kind != TSK_CompleteObject) 7403 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7404 << Kind << SubType.getUnqualifiedType() << CSM; 7405 7406 // Explain why the defaulted or deleted special member isn't trivial. 7407 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7408 Diagnose); 7409 } 7410 } 7411 7412 return false; 7413 } 7414 7415 /// Check whether the members of a class type allow a special member to be 7416 /// trivial. 7417 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7418 Sema::CXXSpecialMember CSM, 7419 bool ConstArg, 7420 Sema::TrivialABIHandling TAH, 7421 bool Diagnose) { 7422 for (const auto *FI : RD->fields()) { 7423 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7424 continue; 7425 7426 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7427 7428 // Pretend anonymous struct or union members are members of this class. 7429 if (FI->isAnonymousStructOrUnion()) { 7430 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7431 CSM, ConstArg, TAH, Diagnose)) 7432 return false; 7433 continue; 7434 } 7435 7436 // C++11 [class.ctor]p5: 7437 // A default constructor is trivial if [...] 7438 // -- no non-static data member of its class has a 7439 // brace-or-equal-initializer 7440 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7441 if (Diagnose) 7442 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7443 return false; 7444 } 7445 7446 // Objective C ARC 4.3.5: 7447 // [...] nontrivally ownership-qualified types are [...] not trivially 7448 // default constructible, copy constructible, move constructible, copy 7449 // assignable, move assignable, or destructible [...] 7450 if (FieldType.hasNonTrivialObjCLifetime()) { 7451 if (Diagnose) 7452 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7453 << RD << FieldType.getObjCLifetime(); 7454 return false; 7455 } 7456 7457 bool ConstRHS = ConstArg && !FI->isMutable(); 7458 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7459 CSM, TSK_Field, TAH, Diagnose)) 7460 return false; 7461 } 7462 7463 return true; 7464 } 7465 7466 /// Diagnose why the specified class does not have a trivial special member of 7467 /// the given kind. 7468 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7469 QualType Ty = Context.getRecordType(RD); 7470 7471 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7472 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7473 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7474 /*Diagnose*/true); 7475 } 7476 7477 /// Determine whether a defaulted or deleted special member function is trivial, 7478 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7479 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7480 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7481 TrivialABIHandling TAH, bool Diagnose) { 7482 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7483 7484 CXXRecordDecl *RD = MD->getParent(); 7485 7486 bool ConstArg = false; 7487 7488 // C++11 [class.copy]p12, p25: [DR1593] 7489 // A [special member] is trivial if [...] its parameter-type-list is 7490 // equivalent to the parameter-type-list of an implicit declaration [...] 7491 switch (CSM) { 7492 case CXXDefaultConstructor: 7493 case CXXDestructor: 7494 // Trivial default constructors and destructors cannot have parameters. 7495 break; 7496 7497 case CXXCopyConstructor: 7498 case CXXCopyAssignment: { 7499 // Trivial copy operations always have const, non-volatile parameter types. 7500 ConstArg = true; 7501 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7502 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7503 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7504 if (Diagnose) 7505 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7506 << Param0->getSourceRange() << Param0->getType() 7507 << Context.getLValueReferenceType( 7508 Context.getRecordType(RD).withConst()); 7509 return false; 7510 } 7511 break; 7512 } 7513 7514 case CXXMoveConstructor: 7515 case CXXMoveAssignment: { 7516 // Trivial move operations always have non-cv-qualified parameters. 7517 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7518 const RValueReferenceType *RT = 7519 Param0->getType()->getAs<RValueReferenceType>(); 7520 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7521 if (Diagnose) 7522 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7523 << Param0->getSourceRange() << Param0->getType() 7524 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7525 return false; 7526 } 7527 break; 7528 } 7529 7530 case CXXInvalid: 7531 llvm_unreachable("not a special member"); 7532 } 7533 7534 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7535 if (Diagnose) 7536 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7537 diag::note_nontrivial_default_arg) 7538 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7539 return false; 7540 } 7541 if (MD->isVariadic()) { 7542 if (Diagnose) 7543 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7544 return false; 7545 } 7546 7547 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7548 // A copy/move [constructor or assignment operator] is trivial if 7549 // -- the [member] selected to copy/move each direct base class subobject 7550 // is trivial 7551 // 7552 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7553 // A [default constructor or destructor] is trivial if 7554 // -- all the direct base classes have trivial [default constructors or 7555 // destructors] 7556 for (const auto &BI : RD->bases()) 7557 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7558 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7559 return false; 7560 7561 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7562 // A copy/move [constructor or assignment operator] for a class X is 7563 // trivial if 7564 // -- for each non-static data member of X that is of class type (or array 7565 // thereof), the constructor selected to copy/move that member is 7566 // trivial 7567 // 7568 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7569 // A [default constructor or destructor] is trivial if 7570 // -- for all of the non-static data members of its class that are of class 7571 // type (or array thereof), each such class has a trivial [default 7572 // constructor or destructor] 7573 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7574 return false; 7575 7576 // C++11 [class.dtor]p5: 7577 // A destructor is trivial if [...] 7578 // -- the destructor is not virtual 7579 if (CSM == CXXDestructor && MD->isVirtual()) { 7580 if (Diagnose) 7581 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7582 return false; 7583 } 7584 7585 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7586 // A [special member] for class X is trivial if [...] 7587 // -- class X has no virtual functions and no virtual base classes 7588 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7589 if (!Diagnose) 7590 return false; 7591 7592 if (RD->getNumVBases()) { 7593 // Check for virtual bases. We already know that the corresponding 7594 // member in all bases is trivial, so vbases must all be direct. 7595 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7596 assert(BS.isVirtual()); 7597 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7598 return false; 7599 } 7600 7601 // Must have a virtual method. 7602 for (const auto *MI : RD->methods()) { 7603 if (MI->isVirtual()) { 7604 SourceLocation MLoc = MI->getLocStart(); 7605 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7606 return false; 7607 } 7608 } 7609 7610 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7611 } 7612 7613 // Looks like it's trivial! 7614 return true; 7615 } 7616 7617 namespace { 7618 struct FindHiddenVirtualMethod { 7619 Sema *S; 7620 CXXMethodDecl *Method; 7621 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7622 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7623 7624 private: 7625 /// Check whether any most overriden method from MD in Methods 7626 static bool CheckMostOverridenMethods( 7627 const CXXMethodDecl *MD, 7628 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7629 if (MD->size_overridden_methods() == 0) 7630 return Methods.count(MD->getCanonicalDecl()); 7631 for (const CXXMethodDecl *O : MD->overridden_methods()) 7632 if (CheckMostOverridenMethods(O, Methods)) 7633 return true; 7634 return false; 7635 } 7636 7637 public: 7638 /// Member lookup function that determines whether a given C++ 7639 /// method overloads virtual methods in a base class without overriding any, 7640 /// to be used with CXXRecordDecl::lookupInBases(). 7641 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7642 RecordDecl *BaseRecord = 7643 Specifier->getType()->getAs<RecordType>()->getDecl(); 7644 7645 DeclarationName Name = Method->getDeclName(); 7646 assert(Name.getNameKind() == DeclarationName::Identifier); 7647 7648 bool foundSameNameMethod = false; 7649 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7650 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7651 Path.Decls = Path.Decls.slice(1)) { 7652 NamedDecl *D = Path.Decls.front(); 7653 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7654 MD = MD->getCanonicalDecl(); 7655 foundSameNameMethod = true; 7656 // Interested only in hidden virtual methods. 7657 if (!MD->isVirtual()) 7658 continue; 7659 // If the method we are checking overrides a method from its base 7660 // don't warn about the other overloaded methods. Clang deviates from 7661 // GCC by only diagnosing overloads of inherited virtual functions that 7662 // do not override any other virtual functions in the base. GCC's 7663 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7664 // function from a base class. These cases may be better served by a 7665 // warning (not specific to virtual functions) on call sites when the 7666 // call would select a different function from the base class, were it 7667 // visible. 7668 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7669 if (!S->IsOverload(Method, MD, false)) 7670 return true; 7671 // Collect the overload only if its hidden. 7672 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7673 overloadedMethods.push_back(MD); 7674 } 7675 } 7676 7677 if (foundSameNameMethod) 7678 OverloadedMethods.append(overloadedMethods.begin(), 7679 overloadedMethods.end()); 7680 return foundSameNameMethod; 7681 } 7682 }; 7683 } // end anonymous namespace 7684 7685 /// Add the most overriden methods from MD to Methods 7686 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7687 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7688 if (MD->size_overridden_methods() == 0) 7689 Methods.insert(MD->getCanonicalDecl()); 7690 else 7691 for (const CXXMethodDecl *O : MD->overridden_methods()) 7692 AddMostOverridenMethods(O, Methods); 7693 } 7694 7695 /// Check if a method overloads virtual methods in a base class without 7696 /// overriding any. 7697 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7698 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7699 if (!MD->getDeclName().isIdentifier()) 7700 return; 7701 7702 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7703 /*bool RecordPaths=*/false, 7704 /*bool DetectVirtual=*/false); 7705 FindHiddenVirtualMethod FHVM; 7706 FHVM.Method = MD; 7707 FHVM.S = this; 7708 7709 // Keep the base methods that were overriden or introduced in the subclass 7710 // by 'using' in a set. A base method not in this set is hidden. 7711 CXXRecordDecl *DC = MD->getParent(); 7712 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7713 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7714 NamedDecl *ND = *I; 7715 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7716 ND = shad->getTargetDecl(); 7717 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7718 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7719 } 7720 7721 if (DC->lookupInBases(FHVM, Paths)) 7722 OverloadedMethods = FHVM.OverloadedMethods; 7723 } 7724 7725 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7726 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7727 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7728 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7729 PartialDiagnostic PD = PDiag( 7730 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7731 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7732 Diag(overloadedMD->getLocation(), PD); 7733 } 7734 } 7735 7736 /// Diagnose methods which overload virtual methods in a base class 7737 /// without overriding any. 7738 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7739 if (MD->isInvalidDecl()) 7740 return; 7741 7742 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7743 return; 7744 7745 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7746 FindHiddenVirtualMethods(MD, OverloadedMethods); 7747 if (!OverloadedMethods.empty()) { 7748 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7749 << MD << (OverloadedMethods.size() > 1); 7750 7751 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7752 } 7753 } 7754 7755 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7756 auto PrintDiagAndRemoveAttr = [&]() { 7757 // No diagnostics if this is a template instantiation. 7758 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7759 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7760 diag::ext_cannot_use_trivial_abi) << &RD; 7761 RD.dropAttr<TrivialABIAttr>(); 7762 }; 7763 7764 // Ill-formed if the struct has virtual functions. 7765 if (RD.isPolymorphic()) { 7766 PrintDiagAndRemoveAttr(); 7767 return; 7768 } 7769 7770 for (const auto &B : RD.bases()) { 7771 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7772 // virtual base. 7773 if ((!B.getType()->isDependentType() && 7774 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7775 B.isVirtual()) { 7776 PrintDiagAndRemoveAttr(); 7777 return; 7778 } 7779 } 7780 7781 for (const auto *FD : RD.fields()) { 7782 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7783 // non-trivial for the purpose of calls. 7784 QualType FT = FD->getType(); 7785 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7786 PrintDiagAndRemoveAttr(); 7787 return; 7788 } 7789 7790 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7791 if (!RT->isDependentType() && 7792 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7793 PrintDiagAndRemoveAttr(); 7794 return; 7795 } 7796 } 7797 } 7798 7799 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7800 Decl *TagDecl, 7801 SourceLocation LBrac, 7802 SourceLocation RBrac, 7803 AttributeList *AttrList) { 7804 if (!TagDecl) 7805 return; 7806 7807 AdjustDeclIfTemplate(TagDecl); 7808 7809 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7810 if (l->getKind() != AttributeList::AT_Visibility) 7811 continue; 7812 l->setInvalid(); 7813 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7814 l->getName(); 7815 } 7816 7817 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7818 // strict aliasing violation! 7819 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7820 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7821 7822 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7823 } 7824 7825 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7826 /// special functions, such as the default constructor, copy 7827 /// constructor, or destructor, to the given C++ class (C++ 7828 /// [special]p1). This routine can only be executed just before the 7829 /// definition of the class is complete. 7830 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7831 if (ClassDecl->needsImplicitDefaultConstructor()) { 7832 ++ASTContext::NumImplicitDefaultConstructors; 7833 7834 if (ClassDecl->hasInheritedConstructor()) 7835 DeclareImplicitDefaultConstructor(ClassDecl); 7836 } 7837 7838 if (ClassDecl->needsImplicitCopyConstructor()) { 7839 ++ASTContext::NumImplicitCopyConstructors; 7840 7841 // If the properties or semantics of the copy constructor couldn't be 7842 // determined while the class was being declared, force a declaration 7843 // of it now. 7844 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7845 ClassDecl->hasInheritedConstructor()) 7846 DeclareImplicitCopyConstructor(ClassDecl); 7847 // For the MS ABI we need to know whether the copy ctor is deleted. A 7848 // prerequisite for deleting the implicit copy ctor is that the class has a 7849 // move ctor or move assignment that is either user-declared or whose 7850 // semantics are inherited from a subobject. FIXME: We should provide a more 7851 // direct way for CodeGen to ask whether the constructor was deleted. 7852 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7853 (ClassDecl->hasUserDeclaredMoveConstructor() || 7854 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7855 ClassDecl->hasUserDeclaredMoveAssignment() || 7856 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7857 DeclareImplicitCopyConstructor(ClassDecl); 7858 } 7859 7860 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7861 ++ASTContext::NumImplicitMoveConstructors; 7862 7863 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7864 ClassDecl->hasInheritedConstructor()) 7865 DeclareImplicitMoveConstructor(ClassDecl); 7866 } 7867 7868 if (ClassDecl->needsImplicitCopyAssignment()) { 7869 ++ASTContext::NumImplicitCopyAssignmentOperators; 7870 7871 // If we have a dynamic class, then the copy assignment operator may be 7872 // virtual, so we have to declare it immediately. This ensures that, e.g., 7873 // it shows up in the right place in the vtable and that we diagnose 7874 // problems with the implicit exception specification. 7875 if (ClassDecl->isDynamicClass() || 7876 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7877 ClassDecl->hasInheritedAssignment()) 7878 DeclareImplicitCopyAssignment(ClassDecl); 7879 } 7880 7881 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7882 ++ASTContext::NumImplicitMoveAssignmentOperators; 7883 7884 // Likewise for the move assignment operator. 7885 if (ClassDecl->isDynamicClass() || 7886 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7887 ClassDecl->hasInheritedAssignment()) 7888 DeclareImplicitMoveAssignment(ClassDecl); 7889 } 7890 7891 if (ClassDecl->needsImplicitDestructor()) { 7892 ++ASTContext::NumImplicitDestructors; 7893 7894 // If we have a dynamic class, then the destructor may be virtual, so we 7895 // have to declare the destructor immediately. This ensures that, e.g., it 7896 // shows up in the right place in the vtable and that we diagnose problems 7897 // with the implicit exception specification. 7898 if (ClassDecl->isDynamicClass() || 7899 ClassDecl->needsOverloadResolutionForDestructor()) 7900 DeclareImplicitDestructor(ClassDecl); 7901 } 7902 } 7903 7904 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7905 if (!D) 7906 return 0; 7907 7908 // The order of template parameters is not important here. All names 7909 // get added to the same scope. 7910 SmallVector<TemplateParameterList *, 4> ParameterLists; 7911 7912 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7913 D = TD->getTemplatedDecl(); 7914 7915 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7916 ParameterLists.push_back(PSD->getTemplateParameters()); 7917 7918 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7919 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7920 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7921 7922 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7923 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7924 ParameterLists.push_back(FTD->getTemplateParameters()); 7925 } 7926 } 7927 7928 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7929 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7930 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7931 7932 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7933 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7934 ParameterLists.push_back(CTD->getTemplateParameters()); 7935 } 7936 } 7937 7938 unsigned Count = 0; 7939 for (TemplateParameterList *Params : ParameterLists) { 7940 if (Params->size() > 0) 7941 // Ignore explicit specializations; they don't contribute to the template 7942 // depth. 7943 ++Count; 7944 for (NamedDecl *Param : *Params) { 7945 if (Param->getDeclName()) { 7946 S->AddDecl(Param); 7947 IdResolver.AddDecl(Param); 7948 } 7949 } 7950 } 7951 7952 return Count; 7953 } 7954 7955 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7956 if (!RecordD) return; 7957 AdjustDeclIfTemplate(RecordD); 7958 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7959 PushDeclContext(S, Record); 7960 } 7961 7962 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7963 if (!RecordD) return; 7964 PopDeclContext(); 7965 } 7966 7967 /// This is used to implement the constant expression evaluation part of the 7968 /// attribute enable_if extension. There is nothing in standard C++ which would 7969 /// require reentering parameters. 7970 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7971 if (!Param) 7972 return; 7973 7974 S->AddDecl(Param); 7975 if (Param->getDeclName()) 7976 IdResolver.AddDecl(Param); 7977 } 7978 7979 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7980 /// parsing a top-level (non-nested) C++ class, and we are now 7981 /// parsing those parts of the given Method declaration that could 7982 /// not be parsed earlier (C++ [class.mem]p2), such as default 7983 /// arguments. This action should enter the scope of the given 7984 /// Method declaration as if we had just parsed the qualified method 7985 /// name. However, it should not bring the parameters into scope; 7986 /// that will be performed by ActOnDelayedCXXMethodParameter. 7987 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7988 } 7989 7990 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7991 /// C++ method declaration. We're (re-)introducing the given 7992 /// function parameter into scope for use in parsing later parts of 7993 /// the method declaration. For example, we could see an 7994 /// ActOnParamDefaultArgument event for this parameter. 7995 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7996 if (!ParamD) 7997 return; 7998 7999 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8000 8001 // If this parameter has an unparsed default argument, clear it out 8002 // to make way for the parsed default argument. 8003 if (Param->hasUnparsedDefaultArg()) 8004 Param->setDefaultArg(nullptr); 8005 8006 S->AddDecl(Param); 8007 if (Param->getDeclName()) 8008 IdResolver.AddDecl(Param); 8009 } 8010 8011 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8012 /// processing the delayed method declaration for Method. The method 8013 /// declaration is now considered finished. There may be a separate 8014 /// ActOnStartOfFunctionDef action later (not necessarily 8015 /// immediately!) for this method, if it was also defined inside the 8016 /// class body. 8017 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8018 if (!MethodD) 8019 return; 8020 8021 AdjustDeclIfTemplate(MethodD); 8022 8023 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8024 8025 // Now that we have our default arguments, check the constructor 8026 // again. It could produce additional diagnostics or affect whether 8027 // the class has implicitly-declared destructors, among other 8028 // things. 8029 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8030 CheckConstructor(Constructor); 8031 8032 // Check the default arguments, which we may have added. 8033 if (!Method->isInvalidDecl()) 8034 CheckCXXDefaultArguments(Method); 8035 } 8036 8037 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8038 /// the well-formedness of the constructor declarator @p D with type @p 8039 /// R. If there are any errors in the declarator, this routine will 8040 /// emit diagnostics and set the invalid bit to true. In any case, the type 8041 /// will be updated to reflect a well-formed type for the constructor and 8042 /// returned. 8043 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8044 StorageClass &SC) { 8045 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8046 8047 // C++ [class.ctor]p3: 8048 // A constructor shall not be virtual (10.3) or static (9.4). A 8049 // constructor can be invoked for a const, volatile or const 8050 // volatile object. A constructor shall not be declared const, 8051 // volatile, or const volatile (9.3.2). 8052 if (isVirtual) { 8053 if (!D.isInvalidType()) 8054 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8055 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8056 << SourceRange(D.getIdentifierLoc()); 8057 D.setInvalidType(); 8058 } 8059 if (SC == SC_Static) { 8060 if (!D.isInvalidType()) 8061 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8062 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8063 << SourceRange(D.getIdentifierLoc()); 8064 D.setInvalidType(); 8065 SC = SC_None; 8066 } 8067 8068 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8069 diagnoseIgnoredQualifiers( 8070 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8071 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8072 D.getDeclSpec().getRestrictSpecLoc(), 8073 D.getDeclSpec().getAtomicSpecLoc()); 8074 D.setInvalidType(); 8075 } 8076 8077 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8078 if (FTI.TypeQuals != 0) { 8079 if (FTI.TypeQuals & Qualifiers::Const) 8080 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8081 << "const" << SourceRange(D.getIdentifierLoc()); 8082 if (FTI.TypeQuals & Qualifiers::Volatile) 8083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8084 << "volatile" << SourceRange(D.getIdentifierLoc()); 8085 if (FTI.TypeQuals & Qualifiers::Restrict) 8086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8087 << "restrict" << SourceRange(D.getIdentifierLoc()); 8088 D.setInvalidType(); 8089 } 8090 8091 // C++0x [class.ctor]p4: 8092 // A constructor shall not be declared with a ref-qualifier. 8093 if (FTI.hasRefQualifier()) { 8094 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8095 << FTI.RefQualifierIsLValueRef 8096 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8097 D.setInvalidType(); 8098 } 8099 8100 // Rebuild the function type "R" without any type qualifiers (in 8101 // case any of the errors above fired) and with "void" as the 8102 // return type, since constructors don't have return types. 8103 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8104 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8105 return R; 8106 8107 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8108 EPI.TypeQuals = 0; 8109 EPI.RefQualifier = RQ_None; 8110 8111 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8112 } 8113 8114 /// CheckConstructor - Checks a fully-formed constructor for 8115 /// well-formedness, issuing any diagnostics required. Returns true if 8116 /// the constructor declarator is invalid. 8117 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8118 CXXRecordDecl *ClassDecl 8119 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8120 if (!ClassDecl) 8121 return Constructor->setInvalidDecl(); 8122 8123 // C++ [class.copy]p3: 8124 // A declaration of a constructor for a class X is ill-formed if 8125 // its first parameter is of type (optionally cv-qualified) X and 8126 // either there are no other parameters or else all other 8127 // parameters have default arguments. 8128 if (!Constructor->isInvalidDecl() && 8129 ((Constructor->getNumParams() == 1) || 8130 (Constructor->getNumParams() > 1 && 8131 Constructor->getParamDecl(1)->hasDefaultArg())) && 8132 Constructor->getTemplateSpecializationKind() 8133 != TSK_ImplicitInstantiation) { 8134 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8135 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8136 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8137 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8138 const char *ConstRef 8139 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8140 : " const &"; 8141 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8142 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8143 8144 // FIXME: Rather that making the constructor invalid, we should endeavor 8145 // to fix the type. 8146 Constructor->setInvalidDecl(); 8147 } 8148 } 8149 } 8150 8151 /// CheckDestructor - Checks a fully-formed destructor definition for 8152 /// well-formedness, issuing any diagnostics required. Returns true 8153 /// on error. 8154 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8155 CXXRecordDecl *RD = Destructor->getParent(); 8156 8157 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8158 SourceLocation Loc; 8159 8160 if (!Destructor->isImplicit()) 8161 Loc = Destructor->getLocation(); 8162 else 8163 Loc = RD->getLocation(); 8164 8165 // If we have a virtual destructor, look up the deallocation function 8166 if (FunctionDecl *OperatorDelete = 8167 FindDeallocationFunctionForDestructor(Loc, RD)) { 8168 Expr *ThisArg = nullptr; 8169 8170 // If the notional 'delete this' expression requires a non-trivial 8171 // conversion from 'this' to the type of a destroying operator delete's 8172 // first parameter, perform that conversion now. 8173 if (OperatorDelete->isDestroyingOperatorDelete()) { 8174 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8175 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8176 // C++ [class.dtor]p13: 8177 // ... as if for the expression 'delete this' appearing in a 8178 // non-virtual destructor of the destructor's class. 8179 ContextRAII SwitchContext(*this, Destructor); 8180 ExprResult This = 8181 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8182 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8183 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8184 if (This.isInvalid()) { 8185 // FIXME: Register this as a context note so that it comes out 8186 // in the right order. 8187 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8188 return true; 8189 } 8190 ThisArg = This.get(); 8191 } 8192 } 8193 8194 MarkFunctionReferenced(Loc, OperatorDelete); 8195 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8196 } 8197 } 8198 8199 return false; 8200 } 8201 8202 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8203 /// the well-formednes of the destructor declarator @p D with type @p 8204 /// R. If there are any errors in the declarator, this routine will 8205 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8206 /// will be updated to reflect a well-formed type for the destructor and 8207 /// returned. 8208 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8209 StorageClass& SC) { 8210 // C++ [class.dtor]p1: 8211 // [...] A typedef-name that names a class is a class-name 8212 // (7.1.3); however, a typedef-name that names a class shall not 8213 // be used as the identifier in the declarator for a destructor 8214 // declaration. 8215 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8216 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8217 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8218 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8219 else if (const TemplateSpecializationType *TST = 8220 DeclaratorType->getAs<TemplateSpecializationType>()) 8221 if (TST->isTypeAlias()) 8222 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8223 << DeclaratorType << 1; 8224 8225 // C++ [class.dtor]p2: 8226 // A destructor is used to destroy objects of its class type. A 8227 // destructor takes no parameters, and no return type can be 8228 // specified for it (not even void). The address of a destructor 8229 // shall not be taken. A destructor shall not be static. A 8230 // destructor can be invoked for a const, volatile or const 8231 // volatile object. A destructor shall not be declared const, 8232 // volatile or const volatile (9.3.2). 8233 if (SC == SC_Static) { 8234 if (!D.isInvalidType()) 8235 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8236 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8237 << SourceRange(D.getIdentifierLoc()) 8238 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8239 8240 SC = SC_None; 8241 } 8242 if (!D.isInvalidType()) { 8243 // Destructors don't have return types, but the parser will 8244 // happily parse something like: 8245 // 8246 // class X { 8247 // float ~X(); 8248 // }; 8249 // 8250 // The return type will be eliminated later. 8251 if (D.getDeclSpec().hasTypeSpecifier()) 8252 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8253 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8254 << SourceRange(D.getIdentifierLoc()); 8255 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8256 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8257 SourceLocation(), 8258 D.getDeclSpec().getConstSpecLoc(), 8259 D.getDeclSpec().getVolatileSpecLoc(), 8260 D.getDeclSpec().getRestrictSpecLoc(), 8261 D.getDeclSpec().getAtomicSpecLoc()); 8262 D.setInvalidType(); 8263 } 8264 } 8265 8266 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8267 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8268 if (FTI.TypeQuals & Qualifiers::Const) 8269 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8270 << "const" << SourceRange(D.getIdentifierLoc()); 8271 if (FTI.TypeQuals & Qualifiers::Volatile) 8272 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8273 << "volatile" << SourceRange(D.getIdentifierLoc()); 8274 if (FTI.TypeQuals & Qualifiers::Restrict) 8275 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8276 << "restrict" << SourceRange(D.getIdentifierLoc()); 8277 D.setInvalidType(); 8278 } 8279 8280 // C++0x [class.dtor]p2: 8281 // A destructor shall not be declared with a ref-qualifier. 8282 if (FTI.hasRefQualifier()) { 8283 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8284 << FTI.RefQualifierIsLValueRef 8285 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8286 D.setInvalidType(); 8287 } 8288 8289 // Make sure we don't have any parameters. 8290 if (FTIHasNonVoidParameters(FTI)) { 8291 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8292 8293 // Delete the parameters. 8294 FTI.freeParams(); 8295 D.setInvalidType(); 8296 } 8297 8298 // Make sure the destructor isn't variadic. 8299 if (FTI.isVariadic) { 8300 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8301 D.setInvalidType(); 8302 } 8303 8304 // Rebuild the function type "R" without any type qualifiers or 8305 // parameters (in case any of the errors above fired) and with 8306 // "void" as the return type, since destructors don't have return 8307 // types. 8308 if (!D.isInvalidType()) 8309 return R; 8310 8311 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8312 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8313 EPI.Variadic = false; 8314 EPI.TypeQuals = 0; 8315 EPI.RefQualifier = RQ_None; 8316 return Context.getFunctionType(Context.VoidTy, None, EPI); 8317 } 8318 8319 static void extendLeft(SourceRange &R, SourceRange Before) { 8320 if (Before.isInvalid()) 8321 return; 8322 R.setBegin(Before.getBegin()); 8323 if (R.getEnd().isInvalid()) 8324 R.setEnd(Before.getEnd()); 8325 } 8326 8327 static void extendRight(SourceRange &R, SourceRange After) { 8328 if (After.isInvalid()) 8329 return; 8330 if (R.getBegin().isInvalid()) 8331 R.setBegin(After.getBegin()); 8332 R.setEnd(After.getEnd()); 8333 } 8334 8335 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8336 /// well-formednes of the conversion function declarator @p D with 8337 /// type @p R. If there are any errors in the declarator, this routine 8338 /// will emit diagnostics and return true. Otherwise, it will return 8339 /// false. Either way, the type @p R will be updated to reflect a 8340 /// well-formed type for the conversion operator. 8341 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8342 StorageClass& SC) { 8343 // C++ [class.conv.fct]p1: 8344 // Neither parameter types nor return type can be specified. The 8345 // type of a conversion function (8.3.5) is "function taking no 8346 // parameter returning conversion-type-id." 8347 if (SC == SC_Static) { 8348 if (!D.isInvalidType()) 8349 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8350 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8351 << D.getName().getSourceRange(); 8352 D.setInvalidType(); 8353 SC = SC_None; 8354 } 8355 8356 TypeSourceInfo *ConvTSI = nullptr; 8357 QualType ConvType = 8358 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8359 8360 const DeclSpec &DS = D.getDeclSpec(); 8361 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8362 // Conversion functions don't have return types, but the parser will 8363 // happily parse something like: 8364 // 8365 // class X { 8366 // float operator bool(); 8367 // }; 8368 // 8369 // The return type will be changed later anyway. 8370 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8371 << SourceRange(DS.getTypeSpecTypeLoc()) 8372 << SourceRange(D.getIdentifierLoc()); 8373 D.setInvalidType(); 8374 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8375 // It's also plausible that the user writes type qualifiers in the wrong 8376 // place, such as: 8377 // struct S { const operator int(); }; 8378 // FIXME: we could provide a fixit to move the qualifiers onto the 8379 // conversion type. 8380 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8381 << SourceRange(D.getIdentifierLoc()) << 0; 8382 D.setInvalidType(); 8383 } 8384 8385 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8386 8387 // Make sure we don't have any parameters. 8388 if (Proto->getNumParams() > 0) { 8389 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8390 8391 // Delete the parameters. 8392 D.getFunctionTypeInfo().freeParams(); 8393 D.setInvalidType(); 8394 } else if (Proto->isVariadic()) { 8395 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8396 D.setInvalidType(); 8397 } 8398 8399 // Diagnose "&operator bool()" and other such nonsense. This 8400 // is actually a gcc extension which we don't support. 8401 if (Proto->getReturnType() != ConvType) { 8402 bool NeedsTypedef = false; 8403 SourceRange Before, After; 8404 8405 // Walk the chunks and extract information on them for our diagnostic. 8406 bool PastFunctionChunk = false; 8407 for (auto &Chunk : D.type_objects()) { 8408 switch (Chunk.Kind) { 8409 case DeclaratorChunk::Function: 8410 if (!PastFunctionChunk) { 8411 if (Chunk.Fun.HasTrailingReturnType) { 8412 TypeSourceInfo *TRT = nullptr; 8413 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8414 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8415 } 8416 PastFunctionChunk = true; 8417 break; 8418 } 8419 LLVM_FALLTHROUGH; 8420 case DeclaratorChunk::Array: 8421 NeedsTypedef = true; 8422 extendRight(After, Chunk.getSourceRange()); 8423 break; 8424 8425 case DeclaratorChunk::Pointer: 8426 case DeclaratorChunk::BlockPointer: 8427 case DeclaratorChunk::Reference: 8428 case DeclaratorChunk::MemberPointer: 8429 case DeclaratorChunk::Pipe: 8430 extendLeft(Before, Chunk.getSourceRange()); 8431 break; 8432 8433 case DeclaratorChunk::Paren: 8434 extendLeft(Before, Chunk.Loc); 8435 extendRight(After, Chunk.EndLoc); 8436 break; 8437 } 8438 } 8439 8440 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8441 After.isValid() ? After.getBegin() : 8442 D.getIdentifierLoc(); 8443 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8444 DB << Before << After; 8445 8446 if (!NeedsTypedef) { 8447 DB << /*don't need a typedef*/0; 8448 8449 // If we can provide a correct fix-it hint, do so. 8450 if (After.isInvalid() && ConvTSI) { 8451 SourceLocation InsertLoc = 8452 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8453 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8454 << FixItHint::CreateInsertionFromRange( 8455 InsertLoc, CharSourceRange::getTokenRange(Before)) 8456 << FixItHint::CreateRemoval(Before); 8457 } 8458 } else if (!Proto->getReturnType()->isDependentType()) { 8459 DB << /*typedef*/1 << Proto->getReturnType(); 8460 } else if (getLangOpts().CPlusPlus11) { 8461 DB << /*alias template*/2 << Proto->getReturnType(); 8462 } else { 8463 DB << /*might not be fixable*/3; 8464 } 8465 8466 // Recover by incorporating the other type chunks into the result type. 8467 // Note, this does *not* change the name of the function. This is compatible 8468 // with the GCC extension: 8469 // struct S { &operator int(); } s; 8470 // int &r = s.operator int(); // ok in GCC 8471 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8472 ConvType = Proto->getReturnType(); 8473 } 8474 8475 // C++ [class.conv.fct]p4: 8476 // The conversion-type-id shall not represent a function type nor 8477 // an array type. 8478 if (ConvType->isArrayType()) { 8479 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8480 ConvType = Context.getPointerType(ConvType); 8481 D.setInvalidType(); 8482 } else if (ConvType->isFunctionType()) { 8483 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8484 ConvType = Context.getPointerType(ConvType); 8485 D.setInvalidType(); 8486 } 8487 8488 // Rebuild the function type "R" without any parameters (in case any 8489 // of the errors above fired) and with the conversion type as the 8490 // return type. 8491 if (D.isInvalidType()) 8492 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8493 8494 // C++0x explicit conversion operators. 8495 if (DS.isExplicitSpecified()) 8496 Diag(DS.getExplicitSpecLoc(), 8497 getLangOpts().CPlusPlus11 8498 ? diag::warn_cxx98_compat_explicit_conversion_functions 8499 : diag::ext_explicit_conversion_functions) 8500 << SourceRange(DS.getExplicitSpecLoc()); 8501 } 8502 8503 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8504 /// the declaration of the given C++ conversion function. This routine 8505 /// is responsible for recording the conversion function in the C++ 8506 /// class, if possible. 8507 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8508 assert(Conversion && "Expected to receive a conversion function declaration"); 8509 8510 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8511 8512 // Make sure we aren't redeclaring the conversion function. 8513 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8514 8515 // C++ [class.conv.fct]p1: 8516 // [...] A conversion function is never used to convert a 8517 // (possibly cv-qualified) object to the (possibly cv-qualified) 8518 // same object type (or a reference to it), to a (possibly 8519 // cv-qualified) base class of that type (or a reference to it), 8520 // or to (possibly cv-qualified) void. 8521 // FIXME: Suppress this warning if the conversion function ends up being a 8522 // virtual function that overrides a virtual function in a base class. 8523 QualType ClassType 8524 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8525 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8526 ConvType = ConvTypeRef->getPointeeType(); 8527 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8528 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8529 /* Suppress diagnostics for instantiations. */; 8530 else if (ConvType->isRecordType()) { 8531 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8532 if (ConvType == ClassType) 8533 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8534 << ClassType; 8535 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8536 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8537 << ClassType << ConvType; 8538 } else if (ConvType->isVoidType()) { 8539 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8540 << ClassType << ConvType; 8541 } 8542 8543 if (FunctionTemplateDecl *ConversionTemplate 8544 = Conversion->getDescribedFunctionTemplate()) 8545 return ConversionTemplate; 8546 8547 return Conversion; 8548 } 8549 8550 namespace { 8551 /// Utility class to accumulate and print a diagnostic listing the invalid 8552 /// specifier(s) on a declaration. 8553 struct BadSpecifierDiagnoser { 8554 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8555 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8556 ~BadSpecifierDiagnoser() { 8557 Diagnostic << Specifiers; 8558 } 8559 8560 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8561 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8562 } 8563 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8564 return check(SpecLoc, 8565 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8566 } 8567 void check(SourceLocation SpecLoc, const char *Spec) { 8568 if (SpecLoc.isInvalid()) return; 8569 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8570 if (!Specifiers.empty()) Specifiers += " "; 8571 Specifiers += Spec; 8572 } 8573 8574 Sema &S; 8575 Sema::SemaDiagnosticBuilder Diagnostic; 8576 std::string Specifiers; 8577 }; 8578 } 8579 8580 /// Check the validity of a declarator that we parsed for a deduction-guide. 8581 /// These aren't actually declarators in the grammar, so we need to check that 8582 /// the user didn't specify any pieces that are not part of the deduction-guide 8583 /// grammar. 8584 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8585 StorageClass &SC) { 8586 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8587 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8588 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8589 8590 // C++ [temp.deduct.guide]p3: 8591 // A deduction-gide shall be declared in the same scope as the 8592 // corresponding class template. 8593 if (!CurContext->getRedeclContext()->Equals( 8594 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8595 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8596 << GuidedTemplateDecl; 8597 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8598 } 8599 8600 auto &DS = D.getMutableDeclSpec(); 8601 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8602 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8603 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8604 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8605 BadSpecifierDiagnoser Diagnoser( 8606 *this, D.getIdentifierLoc(), 8607 diag::err_deduction_guide_invalid_specifier); 8608 8609 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8610 DS.ClearStorageClassSpecs(); 8611 SC = SC_None; 8612 8613 // 'explicit' is permitted. 8614 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8615 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8616 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8617 DS.ClearConstexprSpec(); 8618 8619 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8620 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8621 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8622 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8623 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8624 DS.ClearTypeQualifiers(); 8625 8626 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8627 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8628 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8629 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8630 DS.ClearTypeSpecType(); 8631 } 8632 8633 if (D.isInvalidType()) 8634 return; 8635 8636 // Check the declarator is simple enough. 8637 bool FoundFunction = false; 8638 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8639 if (Chunk.Kind == DeclaratorChunk::Paren) 8640 continue; 8641 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8642 Diag(D.getDeclSpec().getLocStart(), 8643 diag::err_deduction_guide_with_complex_decl) 8644 << D.getSourceRange(); 8645 break; 8646 } 8647 if (!Chunk.Fun.hasTrailingReturnType()) { 8648 Diag(D.getName().getLocStart(), 8649 diag::err_deduction_guide_no_trailing_return_type); 8650 break; 8651 } 8652 8653 // Check that the return type is written as a specialization of 8654 // the template specified as the deduction-guide's name. 8655 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8656 TypeSourceInfo *TSI = nullptr; 8657 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8658 assert(TSI && "deduction guide has valid type but invalid return type?"); 8659 bool AcceptableReturnType = false; 8660 bool MightInstantiateToSpecialization = false; 8661 if (auto RetTST = 8662 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8663 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8664 bool TemplateMatches = 8665 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8666 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8667 AcceptableReturnType = true; 8668 else { 8669 // This could still instantiate to the right type, unless we know it 8670 // names the wrong class template. 8671 auto *TD = SpecifiedName.getAsTemplateDecl(); 8672 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8673 !TemplateMatches); 8674 } 8675 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8676 MightInstantiateToSpecialization = true; 8677 } 8678 8679 if (!AcceptableReturnType) { 8680 Diag(TSI->getTypeLoc().getLocStart(), 8681 diag::err_deduction_guide_bad_trailing_return_type) 8682 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8683 << TSI->getTypeLoc().getSourceRange(); 8684 } 8685 8686 // Keep going to check that we don't have any inner declarator pieces (we 8687 // could still have a function returning a pointer to a function). 8688 FoundFunction = true; 8689 } 8690 8691 if (D.isFunctionDefinition()) 8692 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8693 } 8694 8695 //===----------------------------------------------------------------------===// 8696 // Namespace Handling 8697 //===----------------------------------------------------------------------===// 8698 8699 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8700 /// reopened. 8701 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8702 SourceLocation Loc, 8703 IdentifierInfo *II, bool *IsInline, 8704 NamespaceDecl *PrevNS) { 8705 assert(*IsInline != PrevNS->isInline()); 8706 8707 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8708 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8709 // inline namespaces, with the intention of bringing names into namespace std. 8710 // 8711 // We support this just well enough to get that case working; this is not 8712 // sufficient to support reopening namespaces as inline in general. 8713 if (*IsInline && II && II->getName().startswith("__atomic") && 8714 S.getSourceManager().isInSystemHeader(Loc)) { 8715 // Mark all prior declarations of the namespace as inline. 8716 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8717 NS = NS->getPreviousDecl()) 8718 NS->setInline(*IsInline); 8719 // Patch up the lookup table for the containing namespace. This isn't really 8720 // correct, but it's good enough for this particular case. 8721 for (auto *I : PrevNS->decls()) 8722 if (auto *ND = dyn_cast<NamedDecl>(I)) 8723 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8724 return; 8725 } 8726 8727 if (PrevNS->isInline()) 8728 // The user probably just forgot the 'inline', so suggest that it 8729 // be added back. 8730 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8731 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8732 else 8733 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8734 8735 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8736 *IsInline = PrevNS->isInline(); 8737 } 8738 8739 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8740 /// definition. 8741 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8742 SourceLocation InlineLoc, 8743 SourceLocation NamespaceLoc, 8744 SourceLocation IdentLoc, 8745 IdentifierInfo *II, 8746 SourceLocation LBrace, 8747 AttributeList *AttrList, 8748 UsingDirectiveDecl *&UD) { 8749 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8750 // For anonymous namespace, take the location of the left brace. 8751 SourceLocation Loc = II ? IdentLoc : LBrace; 8752 bool IsInline = InlineLoc.isValid(); 8753 bool IsInvalid = false; 8754 bool IsStd = false; 8755 bool AddToKnown = false; 8756 Scope *DeclRegionScope = NamespcScope->getParent(); 8757 8758 NamespaceDecl *PrevNS = nullptr; 8759 if (II) { 8760 // C++ [namespace.def]p2: 8761 // The identifier in an original-namespace-definition shall not 8762 // have been previously defined in the declarative region in 8763 // which the original-namespace-definition appears. The 8764 // identifier in an original-namespace-definition is the name of 8765 // the namespace. Subsequently in that declarative region, it is 8766 // treated as an original-namespace-name. 8767 // 8768 // Since namespace names are unique in their scope, and we don't 8769 // look through using directives, just look for any ordinary names 8770 // as if by qualified name lookup. 8771 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8772 ForExternalRedeclaration); 8773 LookupQualifiedName(R, CurContext->getRedeclContext()); 8774 NamedDecl *PrevDecl = 8775 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8776 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8777 8778 if (PrevNS) { 8779 // This is an extended namespace definition. 8780 if (IsInline != PrevNS->isInline()) 8781 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8782 &IsInline, PrevNS); 8783 } else if (PrevDecl) { 8784 // This is an invalid name redefinition. 8785 Diag(Loc, diag::err_redefinition_different_kind) 8786 << II; 8787 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8788 IsInvalid = true; 8789 // Continue on to push Namespc as current DeclContext and return it. 8790 } else if (II->isStr("std") && 8791 CurContext->getRedeclContext()->isTranslationUnit()) { 8792 // This is the first "real" definition of the namespace "std", so update 8793 // our cache of the "std" namespace to point at this definition. 8794 PrevNS = getStdNamespace(); 8795 IsStd = true; 8796 AddToKnown = !IsInline; 8797 } else { 8798 // We've seen this namespace for the first time. 8799 AddToKnown = !IsInline; 8800 } 8801 } else { 8802 // Anonymous namespaces. 8803 8804 // Determine whether the parent already has an anonymous namespace. 8805 DeclContext *Parent = CurContext->getRedeclContext(); 8806 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8807 PrevNS = TU->getAnonymousNamespace(); 8808 } else { 8809 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8810 PrevNS = ND->getAnonymousNamespace(); 8811 } 8812 8813 if (PrevNS && IsInline != PrevNS->isInline()) 8814 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8815 &IsInline, PrevNS); 8816 } 8817 8818 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8819 StartLoc, Loc, II, PrevNS); 8820 if (IsInvalid) 8821 Namespc->setInvalidDecl(); 8822 8823 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8824 AddPragmaAttributes(DeclRegionScope, Namespc); 8825 8826 // FIXME: Should we be merging attributes? 8827 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8828 PushNamespaceVisibilityAttr(Attr, Loc); 8829 8830 if (IsStd) 8831 StdNamespace = Namespc; 8832 if (AddToKnown) 8833 KnownNamespaces[Namespc] = false; 8834 8835 if (II) { 8836 PushOnScopeChains(Namespc, DeclRegionScope); 8837 } else { 8838 // Link the anonymous namespace into its parent. 8839 DeclContext *Parent = CurContext->getRedeclContext(); 8840 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8841 TU->setAnonymousNamespace(Namespc); 8842 } else { 8843 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8844 } 8845 8846 CurContext->addDecl(Namespc); 8847 8848 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8849 // behaves as if it were replaced by 8850 // namespace unique { /* empty body */ } 8851 // using namespace unique; 8852 // namespace unique { namespace-body } 8853 // where all occurrences of 'unique' in a translation unit are 8854 // replaced by the same identifier and this identifier differs 8855 // from all other identifiers in the entire program. 8856 8857 // We just create the namespace with an empty name and then add an 8858 // implicit using declaration, just like the standard suggests. 8859 // 8860 // CodeGen enforces the "universally unique" aspect by giving all 8861 // declarations semantically contained within an anonymous 8862 // namespace internal linkage. 8863 8864 if (!PrevNS) { 8865 UD = UsingDirectiveDecl::Create(Context, Parent, 8866 /* 'using' */ LBrace, 8867 /* 'namespace' */ SourceLocation(), 8868 /* qualifier */ NestedNameSpecifierLoc(), 8869 /* identifier */ SourceLocation(), 8870 Namespc, 8871 /* Ancestor */ Parent); 8872 UD->setImplicit(); 8873 Parent->addDecl(UD); 8874 } 8875 } 8876 8877 ActOnDocumentableDecl(Namespc); 8878 8879 // Although we could have an invalid decl (i.e. the namespace name is a 8880 // redefinition), push it as current DeclContext and try to continue parsing. 8881 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8882 // for the namespace has the declarations that showed up in that particular 8883 // namespace definition. 8884 PushDeclContext(NamespcScope, Namespc); 8885 return Namespc; 8886 } 8887 8888 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8889 /// is a namespace alias, returns the namespace it points to. 8890 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8891 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8892 return AD->getNamespace(); 8893 return dyn_cast_or_null<NamespaceDecl>(D); 8894 } 8895 8896 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8897 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8898 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8899 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8900 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8901 Namespc->setRBraceLoc(RBrace); 8902 PopDeclContext(); 8903 if (Namespc->hasAttr<VisibilityAttr>()) 8904 PopPragmaVisibility(true, RBrace); 8905 } 8906 8907 CXXRecordDecl *Sema::getStdBadAlloc() const { 8908 return cast_or_null<CXXRecordDecl>( 8909 StdBadAlloc.get(Context.getExternalSource())); 8910 } 8911 8912 EnumDecl *Sema::getStdAlignValT() const { 8913 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8914 } 8915 8916 NamespaceDecl *Sema::getStdNamespace() const { 8917 return cast_or_null<NamespaceDecl>( 8918 StdNamespace.get(Context.getExternalSource())); 8919 } 8920 8921 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8922 if (!StdExperimentalNamespaceCache) { 8923 if (auto Std = getStdNamespace()) { 8924 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8925 SourceLocation(), LookupNamespaceName); 8926 if (!LookupQualifiedName(Result, Std) || 8927 !(StdExperimentalNamespaceCache = 8928 Result.getAsSingle<NamespaceDecl>())) 8929 Result.suppressDiagnostics(); 8930 } 8931 } 8932 return StdExperimentalNamespaceCache; 8933 } 8934 8935 namespace { 8936 8937 enum UnsupportedSTLSelect { 8938 USS_InvalidMember, 8939 USS_MissingMember, 8940 USS_NonTrivial, 8941 USS_Other 8942 }; 8943 8944 struct InvalidSTLDiagnoser { 8945 Sema &S; 8946 SourceLocation Loc; 8947 QualType TyForDiags; 8948 8949 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 8950 const VarDecl *VD = nullptr) { 8951 { 8952 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 8953 << TyForDiags << ((int)Sel); 8954 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 8955 assert(!Name.empty()); 8956 D << Name; 8957 } 8958 } 8959 if (Sel == USS_InvalidMember) { 8960 S.Diag(VD->getLocation(), diag::note_var_declared_here) 8961 << VD << VD->getSourceRange(); 8962 } 8963 return QualType(); 8964 } 8965 }; 8966 } // namespace 8967 8968 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 8969 SourceLocation Loc) { 8970 assert(getLangOpts().CPlusPlus && 8971 "Looking for comparison category type outside of C++."); 8972 8973 // Check if we've already successfully checked the comparison category type 8974 // before. If so, skip checking it again. 8975 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 8976 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 8977 return Info->getType(); 8978 8979 // If lookup failed 8980 if (!Info) { 8981 std::string NameForDiags = "std::"; 8982 NameForDiags += ComparisonCategories::getCategoryString(Kind); 8983 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 8984 << NameForDiags; 8985 return QualType(); 8986 } 8987 8988 assert(Info->Kind == Kind); 8989 assert(Info->Record); 8990 8991 // Update the Record decl in case we encountered a forward declaration on our 8992 // first pass. FIXME: This is a bit of a hack. 8993 if (Info->Record->hasDefinition()) 8994 Info->Record = Info->Record->getDefinition(); 8995 8996 // Use an elaborated type for diagnostics which has a name containing the 8997 // prepended 'std' namespace but not any inline namespace names. 8998 QualType TyForDiags = [&]() { 8999 auto *NNS = 9000 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9001 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9002 }(); 9003 9004 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9005 return QualType(); 9006 9007 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9008 9009 if (!Info->Record->isTriviallyCopyable()) 9010 return UnsupportedSTLError(USS_NonTrivial); 9011 9012 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9013 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9014 // Tolerate empty base classes. 9015 if (Base->isEmpty()) 9016 continue; 9017 // Reject STL implementations which have at least one non-empty base. 9018 return UnsupportedSTLError(); 9019 } 9020 9021 // Check that the STL has implemented the types using a single integer field. 9022 // This expectation allows better codegen for builtin operators. We require: 9023 // (1) The class has exactly one field. 9024 // (2) The field is an integral or enumeration type. 9025 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9026 if (std::distance(FIt, FEnd) != 1 || 9027 !FIt->getType()->isIntegralOrEnumerationType()) { 9028 return UnsupportedSTLError(); 9029 } 9030 9031 // Build each of the require values and store them in Info. 9032 for (ComparisonCategoryResult CCR : 9033 ComparisonCategories::getPossibleResultsForType(Kind)) { 9034 StringRef MemName = ComparisonCategories::getResultString(CCR); 9035 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9036 9037 if (!ValInfo) 9038 return UnsupportedSTLError(USS_MissingMember, MemName); 9039 9040 VarDecl *VD = ValInfo->VD; 9041 assert(VD && "should not be null!"); 9042 9043 // Attempt to diagnose reasons why the STL definition of this type 9044 // might be foobar, including it failing to be a constant expression. 9045 // TODO Handle more ways the lookup or result can be invalid. 9046 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9047 !VD->checkInitIsICE()) 9048 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9049 9050 // Attempt to evaluate the var decl as a constant expression and extract 9051 // the value of its first field as a ICE. If this fails, the STL 9052 // implementation is not supported. 9053 if (!ValInfo->hasValidIntValue()) 9054 return UnsupportedSTLError(); 9055 9056 MarkVariableReferenced(Loc, VD); 9057 } 9058 9059 // We've successfully built the required types and expressions. Update 9060 // the cache and return the newly cached value. 9061 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9062 return Info->getType(); 9063 } 9064 9065 /// Retrieve the special "std" namespace, which may require us to 9066 /// implicitly define the namespace. 9067 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9068 if (!StdNamespace) { 9069 // The "std" namespace has not yet been defined, so build one implicitly. 9070 StdNamespace = NamespaceDecl::Create(Context, 9071 Context.getTranslationUnitDecl(), 9072 /*Inline=*/false, 9073 SourceLocation(), SourceLocation(), 9074 &PP.getIdentifierTable().get("std"), 9075 /*PrevDecl=*/nullptr); 9076 getStdNamespace()->setImplicit(true); 9077 } 9078 9079 return getStdNamespace(); 9080 } 9081 9082 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9083 assert(getLangOpts().CPlusPlus && 9084 "Looking for std::initializer_list outside of C++."); 9085 9086 // We're looking for implicit instantiations of 9087 // template <typename E> class std::initializer_list. 9088 9089 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9090 return false; 9091 9092 ClassTemplateDecl *Template = nullptr; 9093 const TemplateArgument *Arguments = nullptr; 9094 9095 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9096 9097 ClassTemplateSpecializationDecl *Specialization = 9098 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9099 if (!Specialization) 9100 return false; 9101 9102 Template = Specialization->getSpecializedTemplate(); 9103 Arguments = Specialization->getTemplateArgs().data(); 9104 } else if (const TemplateSpecializationType *TST = 9105 Ty->getAs<TemplateSpecializationType>()) { 9106 Template = dyn_cast_or_null<ClassTemplateDecl>( 9107 TST->getTemplateName().getAsTemplateDecl()); 9108 Arguments = TST->getArgs(); 9109 } 9110 if (!Template) 9111 return false; 9112 9113 if (!StdInitializerList) { 9114 // Haven't recognized std::initializer_list yet, maybe this is it. 9115 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9116 if (TemplateClass->getIdentifier() != 9117 &PP.getIdentifierTable().get("initializer_list") || 9118 !getStdNamespace()->InEnclosingNamespaceSetOf( 9119 TemplateClass->getDeclContext())) 9120 return false; 9121 // This is a template called std::initializer_list, but is it the right 9122 // template? 9123 TemplateParameterList *Params = Template->getTemplateParameters(); 9124 if (Params->getMinRequiredArguments() != 1) 9125 return false; 9126 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9127 return false; 9128 9129 // It's the right template. 9130 StdInitializerList = Template; 9131 } 9132 9133 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9134 return false; 9135 9136 // This is an instance of std::initializer_list. Find the argument type. 9137 if (Element) 9138 *Element = Arguments[0].getAsType(); 9139 return true; 9140 } 9141 9142 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9143 NamespaceDecl *Std = S.getStdNamespace(); 9144 if (!Std) { 9145 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9146 return nullptr; 9147 } 9148 9149 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9150 Loc, Sema::LookupOrdinaryName); 9151 if (!S.LookupQualifiedName(Result, Std)) { 9152 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9153 return nullptr; 9154 } 9155 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9156 if (!Template) { 9157 Result.suppressDiagnostics(); 9158 // We found something weird. Complain about the first thing we found. 9159 NamedDecl *Found = *Result.begin(); 9160 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9161 return nullptr; 9162 } 9163 9164 // We found some template called std::initializer_list. Now verify that it's 9165 // correct. 9166 TemplateParameterList *Params = Template->getTemplateParameters(); 9167 if (Params->getMinRequiredArguments() != 1 || 9168 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9169 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9170 return nullptr; 9171 } 9172 9173 return Template; 9174 } 9175 9176 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9177 if (!StdInitializerList) { 9178 StdInitializerList = LookupStdInitializerList(*this, Loc); 9179 if (!StdInitializerList) 9180 return QualType(); 9181 } 9182 9183 TemplateArgumentListInfo Args(Loc, Loc); 9184 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9185 Context.getTrivialTypeSourceInfo(Element, 9186 Loc))); 9187 return Context.getCanonicalType( 9188 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9189 } 9190 9191 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9192 // C++ [dcl.init.list]p2: 9193 // A constructor is an initializer-list constructor if its first parameter 9194 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9195 // std::initializer_list<E> for some type E, and either there are no other 9196 // parameters or else all other parameters have default arguments. 9197 if (Ctor->getNumParams() < 1 || 9198 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9199 return false; 9200 9201 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9202 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9203 ArgType = RT->getPointeeType().getUnqualifiedType(); 9204 9205 return isStdInitializerList(ArgType, nullptr); 9206 } 9207 9208 /// Determine whether a using statement is in a context where it will be 9209 /// apply in all contexts. 9210 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9211 switch (CurContext->getDeclKind()) { 9212 case Decl::TranslationUnit: 9213 return true; 9214 case Decl::LinkageSpec: 9215 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9216 default: 9217 return false; 9218 } 9219 } 9220 9221 namespace { 9222 9223 // Callback to only accept typo corrections that are namespaces. 9224 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9225 public: 9226 bool ValidateCandidate(const TypoCorrection &candidate) override { 9227 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9228 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9229 return false; 9230 } 9231 }; 9232 9233 } 9234 9235 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9236 CXXScopeSpec &SS, 9237 SourceLocation IdentLoc, 9238 IdentifierInfo *Ident) { 9239 R.clear(); 9240 if (TypoCorrection Corrected = 9241 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9242 llvm::make_unique<NamespaceValidatorCCC>(), 9243 Sema::CTK_ErrorRecovery)) { 9244 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9245 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9246 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9247 Ident->getName().equals(CorrectedStr); 9248 S.diagnoseTypo(Corrected, 9249 S.PDiag(diag::err_using_directive_member_suggest) 9250 << Ident << DC << DroppedSpecifier << SS.getRange(), 9251 S.PDiag(diag::note_namespace_defined_here)); 9252 } else { 9253 S.diagnoseTypo(Corrected, 9254 S.PDiag(diag::err_using_directive_suggest) << Ident, 9255 S.PDiag(diag::note_namespace_defined_here)); 9256 } 9257 R.addDecl(Corrected.getFoundDecl()); 9258 return true; 9259 } 9260 return false; 9261 } 9262 9263 Decl *Sema::ActOnUsingDirective(Scope *S, 9264 SourceLocation UsingLoc, 9265 SourceLocation NamespcLoc, 9266 CXXScopeSpec &SS, 9267 SourceLocation IdentLoc, 9268 IdentifierInfo *NamespcName, 9269 AttributeList *AttrList) { 9270 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9271 assert(NamespcName && "Invalid NamespcName."); 9272 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9273 9274 // This can only happen along a recovery path. 9275 while (S->isTemplateParamScope()) 9276 S = S->getParent(); 9277 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9278 9279 UsingDirectiveDecl *UDir = nullptr; 9280 NestedNameSpecifier *Qualifier = nullptr; 9281 if (SS.isSet()) 9282 Qualifier = SS.getScopeRep(); 9283 9284 // Lookup namespace name. 9285 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9286 LookupParsedName(R, S, &SS); 9287 if (R.isAmbiguous()) 9288 return nullptr; 9289 9290 if (R.empty()) { 9291 R.clear(); 9292 // Allow "using namespace std;" or "using namespace ::std;" even if 9293 // "std" hasn't been defined yet, for GCC compatibility. 9294 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9295 NamespcName->isStr("std")) { 9296 Diag(IdentLoc, diag::ext_using_undefined_std); 9297 R.addDecl(getOrCreateStdNamespace()); 9298 R.resolveKind(); 9299 } 9300 // Otherwise, attempt typo correction. 9301 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9302 } 9303 9304 if (!R.empty()) { 9305 NamedDecl *Named = R.getRepresentativeDecl(); 9306 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9307 assert(NS && "expected namespace decl"); 9308 9309 // The use of a nested name specifier may trigger deprecation warnings. 9310 DiagnoseUseOfDecl(Named, IdentLoc); 9311 9312 // C++ [namespace.udir]p1: 9313 // A using-directive specifies that the names in the nominated 9314 // namespace can be used in the scope in which the 9315 // using-directive appears after the using-directive. During 9316 // unqualified name lookup (3.4.1), the names appear as if they 9317 // were declared in the nearest enclosing namespace which 9318 // contains both the using-directive and the nominated 9319 // namespace. [Note: in this context, "contains" means "contains 9320 // directly or indirectly". ] 9321 9322 // Find enclosing context containing both using-directive and 9323 // nominated namespace. 9324 DeclContext *CommonAncestor = NS; 9325 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9326 CommonAncestor = CommonAncestor->getParent(); 9327 9328 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9329 SS.getWithLocInContext(Context), 9330 IdentLoc, Named, CommonAncestor); 9331 9332 if (IsUsingDirectiveInToplevelContext(CurContext) && 9333 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9334 Diag(IdentLoc, diag::warn_using_directive_in_header); 9335 } 9336 9337 PushUsingDirective(S, UDir); 9338 } else { 9339 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9340 } 9341 9342 if (UDir) 9343 ProcessDeclAttributeList(S, UDir, AttrList); 9344 9345 return UDir; 9346 } 9347 9348 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9349 // If the scope has an associated entity and the using directive is at 9350 // namespace or translation unit scope, add the UsingDirectiveDecl into 9351 // its lookup structure so qualified name lookup can find it. 9352 DeclContext *Ctx = S->getEntity(); 9353 if (Ctx && !Ctx->isFunctionOrMethod()) 9354 Ctx->addDecl(UDir); 9355 else 9356 // Otherwise, it is at block scope. The using-directives will affect lookup 9357 // only to the end of the scope. 9358 S->PushUsingDirective(UDir); 9359 } 9360 9361 9362 Decl *Sema::ActOnUsingDeclaration(Scope *S, 9363 AccessSpecifier AS, 9364 SourceLocation UsingLoc, 9365 SourceLocation TypenameLoc, 9366 CXXScopeSpec &SS, 9367 UnqualifiedId &Name, 9368 SourceLocation EllipsisLoc, 9369 AttributeList *AttrList) { 9370 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9371 9372 if (SS.isEmpty()) { 9373 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 9374 return nullptr; 9375 } 9376 9377 switch (Name.getKind()) { 9378 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9379 case UnqualifiedIdKind::IK_Identifier: 9380 case UnqualifiedIdKind::IK_OperatorFunctionId: 9381 case UnqualifiedIdKind::IK_LiteralOperatorId: 9382 case UnqualifiedIdKind::IK_ConversionFunctionId: 9383 break; 9384 9385 case UnqualifiedIdKind::IK_ConstructorName: 9386 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9387 // C++11 inheriting constructors. 9388 Diag(Name.getLocStart(), 9389 getLangOpts().CPlusPlus11 ? 9390 diag::warn_cxx98_compat_using_decl_constructor : 9391 diag::err_using_decl_constructor) 9392 << SS.getRange(); 9393 9394 if (getLangOpts().CPlusPlus11) break; 9395 9396 return nullptr; 9397 9398 case UnqualifiedIdKind::IK_DestructorName: 9399 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9400 << SS.getRange(); 9401 return nullptr; 9402 9403 case UnqualifiedIdKind::IK_TemplateId: 9404 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9405 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9406 return nullptr; 9407 9408 case UnqualifiedIdKind::IK_DeductionGuideName: 9409 llvm_unreachable("cannot parse qualified deduction guide name"); 9410 } 9411 9412 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9413 DeclarationName TargetName = TargetNameInfo.getName(); 9414 if (!TargetName) 9415 return nullptr; 9416 9417 // Warn about access declarations. 9418 if (UsingLoc.isInvalid()) { 9419 Diag(Name.getLocStart(), 9420 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9421 : diag::warn_access_decl_deprecated) 9422 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9423 } 9424 9425 if (EllipsisLoc.isInvalid()) { 9426 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9427 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9428 return nullptr; 9429 } else { 9430 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9431 !TargetNameInfo.containsUnexpandedParameterPack()) { 9432 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9433 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9434 EllipsisLoc = SourceLocation(); 9435 } 9436 } 9437 9438 NamedDecl *UD = 9439 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9440 SS, TargetNameInfo, EllipsisLoc, AttrList, 9441 /*IsInstantiation*/false); 9442 if (UD) 9443 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9444 9445 return UD; 9446 } 9447 9448 /// Determine whether a using declaration considers the given 9449 /// declarations as "equivalent", e.g., if they are redeclarations of 9450 /// the same entity or are both typedefs of the same type. 9451 static bool 9452 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9453 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9454 return true; 9455 9456 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9457 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9458 return Context.hasSameType(TD1->getUnderlyingType(), 9459 TD2->getUnderlyingType()); 9460 9461 return false; 9462 } 9463 9464 9465 /// Determines whether to create a using shadow decl for a particular 9466 /// decl, given the set of decls existing prior to this using lookup. 9467 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9468 const LookupResult &Previous, 9469 UsingShadowDecl *&PrevShadow) { 9470 // Diagnose finding a decl which is not from a base class of the 9471 // current class. We do this now because there are cases where this 9472 // function will silently decide not to build a shadow decl, which 9473 // will pre-empt further diagnostics. 9474 // 9475 // We don't need to do this in C++11 because we do the check once on 9476 // the qualifier. 9477 // 9478 // FIXME: diagnose the following if we care enough: 9479 // struct A { int foo; }; 9480 // struct B : A { using A::foo; }; 9481 // template <class T> struct C : A {}; 9482 // template <class T> struct D : C<T> { using B::foo; } // <--- 9483 // This is invalid (during instantiation) in C++03 because B::foo 9484 // resolves to the using decl in B, which is not a base class of D<T>. 9485 // We can't diagnose it immediately because C<T> is an unknown 9486 // specialization. The UsingShadowDecl in D<T> then points directly 9487 // to A::foo, which will look well-formed when we instantiate. 9488 // The right solution is to not collapse the shadow-decl chain. 9489 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9490 DeclContext *OrigDC = Orig->getDeclContext(); 9491 9492 // Handle enums and anonymous structs. 9493 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9494 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9495 while (OrigRec->isAnonymousStructOrUnion()) 9496 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9497 9498 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9499 if (OrigDC == CurContext) { 9500 Diag(Using->getLocation(), 9501 diag::err_using_decl_nested_name_specifier_is_current_class) 9502 << Using->getQualifierLoc().getSourceRange(); 9503 Diag(Orig->getLocation(), diag::note_using_decl_target); 9504 Using->setInvalidDecl(); 9505 return true; 9506 } 9507 9508 Diag(Using->getQualifierLoc().getBeginLoc(), 9509 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9510 << Using->getQualifier() 9511 << cast<CXXRecordDecl>(CurContext) 9512 << Using->getQualifierLoc().getSourceRange(); 9513 Diag(Orig->getLocation(), diag::note_using_decl_target); 9514 Using->setInvalidDecl(); 9515 return true; 9516 } 9517 } 9518 9519 if (Previous.empty()) return false; 9520 9521 NamedDecl *Target = Orig; 9522 if (isa<UsingShadowDecl>(Target)) 9523 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9524 9525 // If the target happens to be one of the previous declarations, we 9526 // don't have a conflict. 9527 // 9528 // FIXME: but we might be increasing its access, in which case we 9529 // should redeclare it. 9530 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9531 bool FoundEquivalentDecl = false; 9532 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9533 I != E; ++I) { 9534 NamedDecl *D = (*I)->getUnderlyingDecl(); 9535 // We can have UsingDecls in our Previous results because we use the same 9536 // LookupResult for checking whether the UsingDecl itself is a valid 9537 // redeclaration. 9538 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9539 continue; 9540 9541 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9542 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9543 PrevShadow = Shadow; 9544 FoundEquivalentDecl = true; 9545 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9546 // We don't conflict with an existing using shadow decl of an equivalent 9547 // declaration, but we're not a redeclaration of it. 9548 FoundEquivalentDecl = true; 9549 } 9550 9551 if (isVisible(D)) 9552 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9553 } 9554 9555 if (FoundEquivalentDecl) 9556 return false; 9557 9558 if (FunctionDecl *FD = Target->getAsFunction()) { 9559 NamedDecl *OldDecl = nullptr; 9560 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9561 /*IsForUsingDecl*/ true)) { 9562 case Ovl_Overload: 9563 return false; 9564 9565 case Ovl_NonFunction: 9566 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9567 break; 9568 9569 // We found a decl with the exact signature. 9570 case Ovl_Match: 9571 // If we're in a record, we want to hide the target, so we 9572 // return true (without a diagnostic) to tell the caller not to 9573 // build a shadow decl. 9574 if (CurContext->isRecord()) 9575 return true; 9576 9577 // If we're not in a record, this is an error. 9578 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9579 break; 9580 } 9581 9582 Diag(Target->getLocation(), diag::note_using_decl_target); 9583 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9584 Using->setInvalidDecl(); 9585 return true; 9586 } 9587 9588 // Target is not a function. 9589 9590 if (isa<TagDecl>(Target)) { 9591 // No conflict between a tag and a non-tag. 9592 if (!Tag) return false; 9593 9594 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9595 Diag(Target->getLocation(), diag::note_using_decl_target); 9596 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9597 Using->setInvalidDecl(); 9598 return true; 9599 } 9600 9601 // No conflict between a tag and a non-tag. 9602 if (!NonTag) return false; 9603 9604 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9605 Diag(Target->getLocation(), diag::note_using_decl_target); 9606 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9607 Using->setInvalidDecl(); 9608 return true; 9609 } 9610 9611 /// Determine whether a direct base class is a virtual base class. 9612 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9613 if (!Derived->getNumVBases()) 9614 return false; 9615 for (auto &B : Derived->bases()) 9616 if (B.getType()->getAsCXXRecordDecl() == Base) 9617 return B.isVirtual(); 9618 llvm_unreachable("not a direct base class"); 9619 } 9620 9621 /// Builds a shadow declaration corresponding to a 'using' declaration. 9622 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9623 UsingDecl *UD, 9624 NamedDecl *Orig, 9625 UsingShadowDecl *PrevDecl) { 9626 // If we resolved to another shadow declaration, just coalesce them. 9627 NamedDecl *Target = Orig; 9628 if (isa<UsingShadowDecl>(Target)) { 9629 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9630 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9631 } 9632 9633 NamedDecl *NonTemplateTarget = Target; 9634 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9635 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9636 9637 UsingShadowDecl *Shadow; 9638 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9639 bool IsVirtualBase = 9640 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9641 UD->getQualifier()->getAsRecordDecl()); 9642 Shadow = ConstructorUsingShadowDecl::Create( 9643 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9644 } else { 9645 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9646 Target); 9647 } 9648 UD->addShadowDecl(Shadow); 9649 9650 Shadow->setAccess(UD->getAccess()); 9651 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9652 Shadow->setInvalidDecl(); 9653 9654 Shadow->setPreviousDecl(PrevDecl); 9655 9656 if (S) 9657 PushOnScopeChains(Shadow, S); 9658 else 9659 CurContext->addDecl(Shadow); 9660 9661 9662 return Shadow; 9663 } 9664 9665 /// Hides a using shadow declaration. This is required by the current 9666 /// using-decl implementation when a resolvable using declaration in a 9667 /// class is followed by a declaration which would hide or override 9668 /// one or more of the using decl's targets; for example: 9669 /// 9670 /// struct Base { void foo(int); }; 9671 /// struct Derived : Base { 9672 /// using Base::foo; 9673 /// void foo(int); 9674 /// }; 9675 /// 9676 /// The governing language is C++03 [namespace.udecl]p12: 9677 /// 9678 /// When a using-declaration brings names from a base class into a 9679 /// derived class scope, member functions in the derived class 9680 /// override and/or hide member functions with the same name and 9681 /// parameter types in a base class (rather than conflicting). 9682 /// 9683 /// There are two ways to implement this: 9684 /// (1) optimistically create shadow decls when they're not hidden 9685 /// by existing declarations, or 9686 /// (2) don't create any shadow decls (or at least don't make them 9687 /// visible) until we've fully parsed/instantiated the class. 9688 /// The problem with (1) is that we might have to retroactively remove 9689 /// a shadow decl, which requires several O(n) operations because the 9690 /// decl structures are (very reasonably) not designed for removal. 9691 /// (2) avoids this but is very fiddly and phase-dependent. 9692 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9693 if (Shadow->getDeclName().getNameKind() == 9694 DeclarationName::CXXConversionFunctionName) 9695 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9696 9697 // Remove it from the DeclContext... 9698 Shadow->getDeclContext()->removeDecl(Shadow); 9699 9700 // ...and the scope, if applicable... 9701 if (S) { 9702 S->RemoveDecl(Shadow); 9703 IdResolver.RemoveDecl(Shadow); 9704 } 9705 9706 // ...and the using decl. 9707 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9708 9709 // TODO: complain somehow if Shadow was used. It shouldn't 9710 // be possible for this to happen, because...? 9711 } 9712 9713 /// Find the base specifier for a base class with the given type. 9714 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9715 QualType DesiredBase, 9716 bool &AnyDependentBases) { 9717 // Check whether the named type is a direct base class. 9718 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9719 for (auto &Base : Derived->bases()) { 9720 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9721 if (CanonicalDesiredBase == BaseType) 9722 return &Base; 9723 if (BaseType->isDependentType()) 9724 AnyDependentBases = true; 9725 } 9726 return nullptr; 9727 } 9728 9729 namespace { 9730 class UsingValidatorCCC : public CorrectionCandidateCallback { 9731 public: 9732 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9733 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9734 : HasTypenameKeyword(HasTypenameKeyword), 9735 IsInstantiation(IsInstantiation), OldNNS(NNS), 9736 RequireMemberOf(RequireMemberOf) {} 9737 9738 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9739 NamedDecl *ND = Candidate.getCorrectionDecl(); 9740 9741 // Keywords are not valid here. 9742 if (!ND || isa<NamespaceDecl>(ND)) 9743 return false; 9744 9745 // Completely unqualified names are invalid for a 'using' declaration. 9746 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9747 return false; 9748 9749 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9750 // reject. 9751 9752 if (RequireMemberOf) { 9753 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9754 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9755 // No-one ever wants a using-declaration to name an injected-class-name 9756 // of a base class, unless they're declaring an inheriting constructor. 9757 ASTContext &Ctx = ND->getASTContext(); 9758 if (!Ctx.getLangOpts().CPlusPlus11) 9759 return false; 9760 QualType FoundType = Ctx.getRecordType(FoundRecord); 9761 9762 // Check that the injected-class-name is named as a member of its own 9763 // type; we don't want to suggest 'using Derived::Base;', since that 9764 // means something else. 9765 NestedNameSpecifier *Specifier = 9766 Candidate.WillReplaceSpecifier() 9767 ? Candidate.getCorrectionSpecifier() 9768 : OldNNS; 9769 if (!Specifier->getAsType() || 9770 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9771 return false; 9772 9773 // Check that this inheriting constructor declaration actually names a 9774 // direct base class of the current class. 9775 bool AnyDependentBases = false; 9776 if (!findDirectBaseWithType(RequireMemberOf, 9777 Ctx.getRecordType(FoundRecord), 9778 AnyDependentBases) && 9779 !AnyDependentBases) 9780 return false; 9781 } else { 9782 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9783 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9784 return false; 9785 9786 // FIXME: Check that the base class member is accessible? 9787 } 9788 } else { 9789 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9790 if (FoundRecord && FoundRecord->isInjectedClassName()) 9791 return false; 9792 } 9793 9794 if (isa<TypeDecl>(ND)) 9795 return HasTypenameKeyword || !IsInstantiation; 9796 9797 return !HasTypenameKeyword; 9798 } 9799 9800 private: 9801 bool HasTypenameKeyword; 9802 bool IsInstantiation; 9803 NestedNameSpecifier *OldNNS; 9804 CXXRecordDecl *RequireMemberOf; 9805 }; 9806 } // end anonymous namespace 9807 9808 /// Builds a using declaration. 9809 /// 9810 /// \param IsInstantiation - Whether this call arises from an 9811 /// instantiation of an unresolved using declaration. We treat 9812 /// the lookup differently for these declarations. 9813 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9814 SourceLocation UsingLoc, 9815 bool HasTypenameKeyword, 9816 SourceLocation TypenameLoc, 9817 CXXScopeSpec &SS, 9818 DeclarationNameInfo NameInfo, 9819 SourceLocation EllipsisLoc, 9820 AttributeList *AttrList, 9821 bool IsInstantiation) { 9822 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9823 SourceLocation IdentLoc = NameInfo.getLoc(); 9824 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9825 9826 // FIXME: We ignore attributes for now. 9827 9828 // For an inheriting constructor declaration, the name of the using 9829 // declaration is the name of a constructor in this class, not in the 9830 // base class. 9831 DeclarationNameInfo UsingName = NameInfo; 9832 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9833 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9834 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9835 Context.getCanonicalType(Context.getRecordType(RD)))); 9836 9837 // Do the redeclaration lookup in the current scope. 9838 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9839 ForVisibleRedeclaration); 9840 Previous.setHideTags(false); 9841 if (S) { 9842 LookupName(Previous, S); 9843 9844 // It is really dumb that we have to do this. 9845 LookupResult::Filter F = Previous.makeFilter(); 9846 while (F.hasNext()) { 9847 NamedDecl *D = F.next(); 9848 if (!isDeclInScope(D, CurContext, S)) 9849 F.erase(); 9850 // If we found a local extern declaration that's not ordinarily visible, 9851 // and this declaration is being added to a non-block scope, ignore it. 9852 // We're only checking for scope conflicts here, not also for violations 9853 // of the linkage rules. 9854 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9855 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9856 F.erase(); 9857 } 9858 F.done(); 9859 } else { 9860 assert(IsInstantiation && "no scope in non-instantiation"); 9861 if (CurContext->isRecord()) 9862 LookupQualifiedName(Previous, CurContext); 9863 else { 9864 // No redeclaration check is needed here; in non-member contexts we 9865 // diagnosed all possible conflicts with other using-declarations when 9866 // building the template: 9867 // 9868 // For a dependent non-type using declaration, the only valid case is 9869 // if we instantiate to a single enumerator. We check for conflicts 9870 // between shadow declarations we introduce, and we check in the template 9871 // definition for conflicts between a non-type using declaration and any 9872 // other declaration, which together covers all cases. 9873 // 9874 // A dependent typename using declaration will never successfully 9875 // instantiate, since it will always name a class member, so we reject 9876 // that in the template definition. 9877 } 9878 } 9879 9880 // Check for invalid redeclarations. 9881 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9882 SS, IdentLoc, Previous)) 9883 return nullptr; 9884 9885 // Check for bad qualifiers. 9886 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9887 IdentLoc)) 9888 return nullptr; 9889 9890 DeclContext *LookupContext = computeDeclContext(SS); 9891 NamedDecl *D; 9892 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9893 if (!LookupContext || EllipsisLoc.isValid()) { 9894 if (HasTypenameKeyword) { 9895 // FIXME: not all declaration name kinds are legal here 9896 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9897 UsingLoc, TypenameLoc, 9898 QualifierLoc, 9899 IdentLoc, NameInfo.getName(), 9900 EllipsisLoc); 9901 } else { 9902 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9903 QualifierLoc, NameInfo, EllipsisLoc); 9904 } 9905 D->setAccess(AS); 9906 CurContext->addDecl(D); 9907 return D; 9908 } 9909 9910 auto Build = [&](bool Invalid) { 9911 UsingDecl *UD = 9912 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9913 UsingName, HasTypenameKeyword); 9914 UD->setAccess(AS); 9915 CurContext->addDecl(UD); 9916 UD->setInvalidDecl(Invalid); 9917 return UD; 9918 }; 9919 auto BuildInvalid = [&]{ return Build(true); }; 9920 auto BuildValid = [&]{ return Build(false); }; 9921 9922 if (RequireCompleteDeclContext(SS, LookupContext)) 9923 return BuildInvalid(); 9924 9925 // Look up the target name. 9926 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9927 9928 // Unlike most lookups, we don't always want to hide tag 9929 // declarations: tag names are visible through the using declaration 9930 // even if hidden by ordinary names, *except* in a dependent context 9931 // where it's important for the sanity of two-phase lookup. 9932 if (!IsInstantiation) 9933 R.setHideTags(false); 9934 9935 // For the purposes of this lookup, we have a base object type 9936 // equal to that of the current context. 9937 if (CurContext->isRecord()) { 9938 R.setBaseObjectType( 9939 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9940 } 9941 9942 LookupQualifiedName(R, LookupContext); 9943 9944 // Try to correct typos if possible. If constructor name lookup finds no 9945 // results, that means the named class has no explicit constructors, and we 9946 // suppressed declaring implicit ones (probably because it's dependent or 9947 // invalid). 9948 if (R.empty() && 9949 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9950 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9951 // it will believe that glibc provides a ::gets in cases where it does not, 9952 // and will try to pull it into namespace std with a using-declaration. 9953 // Just ignore the using-declaration in that case. 9954 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9955 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9956 CurContext->isStdNamespace() && 9957 isa<TranslationUnitDecl>(LookupContext) && 9958 getSourceManager().isInSystemHeader(UsingLoc)) 9959 return nullptr; 9960 if (TypoCorrection Corrected = CorrectTypo( 9961 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9962 llvm::make_unique<UsingValidatorCCC>( 9963 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9964 dyn_cast<CXXRecordDecl>(CurContext)), 9965 CTK_ErrorRecovery)) { 9966 // We reject candidates where DroppedSpecifier == true, hence the 9967 // literal '0' below. 9968 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9969 << NameInfo.getName() << LookupContext << 0 9970 << SS.getRange()); 9971 9972 // If we picked a correction with no attached Decl we can't do anything 9973 // useful with it, bail out. 9974 NamedDecl *ND = Corrected.getCorrectionDecl(); 9975 if (!ND) 9976 return BuildInvalid(); 9977 9978 // If we corrected to an inheriting constructor, handle it as one. 9979 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9980 if (RD && RD->isInjectedClassName()) { 9981 // The parent of the injected class name is the class itself. 9982 RD = cast<CXXRecordDecl>(RD->getParent()); 9983 9984 // Fix up the information we'll use to build the using declaration. 9985 if (Corrected.WillReplaceSpecifier()) { 9986 NestedNameSpecifierLocBuilder Builder; 9987 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9988 QualifierLoc.getSourceRange()); 9989 QualifierLoc = Builder.getWithLocInContext(Context); 9990 } 9991 9992 // In this case, the name we introduce is the name of a derived class 9993 // constructor. 9994 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9995 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9996 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9997 UsingName.setNamedTypeInfo(nullptr); 9998 for (auto *Ctor : LookupConstructors(RD)) 9999 R.addDecl(Ctor); 10000 R.resolveKind(); 10001 } else { 10002 // FIXME: Pick up all the declarations if we found an overloaded 10003 // function. 10004 UsingName.setName(ND->getDeclName()); 10005 R.addDecl(ND); 10006 } 10007 } else { 10008 Diag(IdentLoc, diag::err_no_member) 10009 << NameInfo.getName() << LookupContext << SS.getRange(); 10010 return BuildInvalid(); 10011 } 10012 } 10013 10014 if (R.isAmbiguous()) 10015 return BuildInvalid(); 10016 10017 if (HasTypenameKeyword) { 10018 // If we asked for a typename and got a non-type decl, error out. 10019 if (!R.getAsSingle<TypeDecl>()) { 10020 Diag(IdentLoc, diag::err_using_typename_non_type); 10021 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10022 Diag((*I)->getUnderlyingDecl()->getLocation(), 10023 diag::note_using_decl_target); 10024 return BuildInvalid(); 10025 } 10026 } else { 10027 // If we asked for a non-typename and we got a type, error out, 10028 // but only if this is an instantiation of an unresolved using 10029 // decl. Otherwise just silently find the type name. 10030 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10031 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10032 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10033 return BuildInvalid(); 10034 } 10035 } 10036 10037 // C++14 [namespace.udecl]p6: 10038 // A using-declaration shall not name a namespace. 10039 if (R.getAsSingle<NamespaceDecl>()) { 10040 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10041 << SS.getRange(); 10042 return BuildInvalid(); 10043 } 10044 10045 // C++14 [namespace.udecl]p7: 10046 // A using-declaration shall not name a scoped enumerator. 10047 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10048 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10049 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10050 << SS.getRange(); 10051 return BuildInvalid(); 10052 } 10053 } 10054 10055 UsingDecl *UD = BuildValid(); 10056 10057 // Some additional rules apply to inheriting constructors. 10058 if (UsingName.getName().getNameKind() == 10059 DeclarationName::CXXConstructorName) { 10060 // Suppress access diagnostics; the access check is instead performed at the 10061 // point of use for an inheriting constructor. 10062 R.suppressDiagnostics(); 10063 if (CheckInheritingConstructorUsingDecl(UD)) 10064 return UD; 10065 } 10066 10067 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10068 UsingShadowDecl *PrevDecl = nullptr; 10069 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10070 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10071 } 10072 10073 return UD; 10074 } 10075 10076 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10077 ArrayRef<NamedDecl *> Expansions) { 10078 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10079 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10080 isa<UsingPackDecl>(InstantiatedFrom)); 10081 10082 auto *UPD = 10083 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10084 UPD->setAccess(InstantiatedFrom->getAccess()); 10085 CurContext->addDecl(UPD); 10086 return UPD; 10087 } 10088 10089 /// Additional checks for a using declaration referring to a constructor name. 10090 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10091 assert(!UD->hasTypename() && "expecting a constructor name"); 10092 10093 const Type *SourceType = UD->getQualifier()->getAsType(); 10094 assert(SourceType && 10095 "Using decl naming constructor doesn't have type in scope spec."); 10096 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10097 10098 // Check whether the named type is a direct base class. 10099 bool AnyDependentBases = false; 10100 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10101 AnyDependentBases); 10102 if (!Base && !AnyDependentBases) { 10103 Diag(UD->getUsingLoc(), 10104 diag::err_using_decl_constructor_not_in_direct_base) 10105 << UD->getNameInfo().getSourceRange() 10106 << QualType(SourceType, 0) << TargetClass; 10107 UD->setInvalidDecl(); 10108 return true; 10109 } 10110 10111 if (Base) 10112 Base->setInheritConstructors(); 10113 10114 return false; 10115 } 10116 10117 /// Checks that the given using declaration is not an invalid 10118 /// redeclaration. Note that this is checking only for the using decl 10119 /// itself, not for any ill-formedness among the UsingShadowDecls. 10120 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10121 bool HasTypenameKeyword, 10122 const CXXScopeSpec &SS, 10123 SourceLocation NameLoc, 10124 const LookupResult &Prev) { 10125 NestedNameSpecifier *Qual = SS.getScopeRep(); 10126 10127 // C++03 [namespace.udecl]p8: 10128 // C++0x [namespace.udecl]p10: 10129 // A using-declaration is a declaration and can therefore be used 10130 // repeatedly where (and only where) multiple declarations are 10131 // allowed. 10132 // 10133 // That's in non-member contexts. 10134 if (!CurContext->getRedeclContext()->isRecord()) { 10135 // A dependent qualifier outside a class can only ever resolve to an 10136 // enumeration type. Therefore it conflicts with any other non-type 10137 // declaration in the same scope. 10138 // FIXME: How should we check for dependent type-type conflicts at block 10139 // scope? 10140 if (Qual->isDependent() && !HasTypenameKeyword) { 10141 for (auto *D : Prev) { 10142 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10143 bool OldCouldBeEnumerator = 10144 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10145 Diag(NameLoc, 10146 OldCouldBeEnumerator ? diag::err_redefinition 10147 : diag::err_redefinition_different_kind) 10148 << Prev.getLookupName(); 10149 Diag(D->getLocation(), diag::note_previous_definition); 10150 return true; 10151 } 10152 } 10153 } 10154 return false; 10155 } 10156 10157 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10158 NamedDecl *D = *I; 10159 10160 bool DTypename; 10161 NestedNameSpecifier *DQual; 10162 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10163 DTypename = UD->hasTypename(); 10164 DQual = UD->getQualifier(); 10165 } else if (UnresolvedUsingValueDecl *UD 10166 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10167 DTypename = false; 10168 DQual = UD->getQualifier(); 10169 } else if (UnresolvedUsingTypenameDecl *UD 10170 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10171 DTypename = true; 10172 DQual = UD->getQualifier(); 10173 } else continue; 10174 10175 // using decls differ if one says 'typename' and the other doesn't. 10176 // FIXME: non-dependent using decls? 10177 if (HasTypenameKeyword != DTypename) continue; 10178 10179 // using decls differ if they name different scopes (but note that 10180 // template instantiation can cause this check to trigger when it 10181 // didn't before instantiation). 10182 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10183 Context.getCanonicalNestedNameSpecifier(DQual)) 10184 continue; 10185 10186 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10187 Diag(D->getLocation(), diag::note_using_decl) << 1; 10188 return true; 10189 } 10190 10191 return false; 10192 } 10193 10194 10195 /// Checks that the given nested-name qualifier used in a using decl 10196 /// in the current context is appropriately related to the current 10197 /// scope. If an error is found, diagnoses it and returns true. 10198 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10199 bool HasTypename, 10200 const CXXScopeSpec &SS, 10201 const DeclarationNameInfo &NameInfo, 10202 SourceLocation NameLoc) { 10203 DeclContext *NamedContext = computeDeclContext(SS); 10204 10205 if (!CurContext->isRecord()) { 10206 // C++03 [namespace.udecl]p3: 10207 // C++0x [namespace.udecl]p8: 10208 // A using-declaration for a class member shall be a member-declaration. 10209 10210 // If we weren't able to compute a valid scope, it might validly be a 10211 // dependent class scope or a dependent enumeration unscoped scope. If 10212 // we have a 'typename' keyword, the scope must resolve to a class type. 10213 if ((HasTypename && !NamedContext) || 10214 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10215 auto *RD = NamedContext 10216 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10217 : nullptr; 10218 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10219 RD = nullptr; 10220 10221 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10222 << SS.getRange(); 10223 10224 // If we have a complete, non-dependent source type, try to suggest a 10225 // way to get the same effect. 10226 if (!RD) 10227 return true; 10228 10229 // Find what this using-declaration was referring to. 10230 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10231 R.setHideTags(false); 10232 R.suppressDiagnostics(); 10233 LookupQualifiedName(R, RD); 10234 10235 if (R.getAsSingle<TypeDecl>()) { 10236 if (getLangOpts().CPlusPlus11) { 10237 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10238 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10239 << 0 // alias declaration 10240 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10241 NameInfo.getName().getAsString() + 10242 " = "); 10243 } else { 10244 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10245 SourceLocation InsertLoc = 10246 getLocForEndOfToken(NameInfo.getLocEnd()); 10247 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10248 << 1 // typedef declaration 10249 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10250 << FixItHint::CreateInsertion( 10251 InsertLoc, " " + NameInfo.getName().getAsString()); 10252 } 10253 } else if (R.getAsSingle<VarDecl>()) { 10254 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10255 // repeating the type of the static data member here. 10256 FixItHint FixIt; 10257 if (getLangOpts().CPlusPlus11) { 10258 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10259 FixIt = FixItHint::CreateReplacement( 10260 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10261 } 10262 10263 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10264 << 2 // reference declaration 10265 << FixIt; 10266 } else if (R.getAsSingle<EnumConstantDecl>()) { 10267 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10268 // repeating the type of the enumeration here, and we can't do so if 10269 // the type is anonymous. 10270 FixItHint FixIt; 10271 if (getLangOpts().CPlusPlus11) { 10272 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10273 FixIt = FixItHint::CreateReplacement( 10274 UsingLoc, 10275 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10276 } 10277 10278 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10279 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10280 << FixIt; 10281 } 10282 return true; 10283 } 10284 10285 // Otherwise, this might be valid. 10286 return false; 10287 } 10288 10289 // The current scope is a record. 10290 10291 // If the named context is dependent, we can't decide much. 10292 if (!NamedContext) { 10293 // FIXME: in C++0x, we can diagnose if we can prove that the 10294 // nested-name-specifier does not refer to a base class, which is 10295 // still possible in some cases. 10296 10297 // Otherwise we have to conservatively report that things might be 10298 // okay. 10299 return false; 10300 } 10301 10302 if (!NamedContext->isRecord()) { 10303 // Ideally this would point at the last name in the specifier, 10304 // but we don't have that level of source info. 10305 Diag(SS.getRange().getBegin(), 10306 diag::err_using_decl_nested_name_specifier_is_not_class) 10307 << SS.getScopeRep() << SS.getRange(); 10308 return true; 10309 } 10310 10311 if (!NamedContext->isDependentContext() && 10312 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10313 return true; 10314 10315 if (getLangOpts().CPlusPlus11) { 10316 // C++11 [namespace.udecl]p3: 10317 // In a using-declaration used as a member-declaration, the 10318 // nested-name-specifier shall name a base class of the class 10319 // being defined. 10320 10321 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10322 cast<CXXRecordDecl>(NamedContext))) { 10323 if (CurContext == NamedContext) { 10324 Diag(NameLoc, 10325 diag::err_using_decl_nested_name_specifier_is_current_class) 10326 << SS.getRange(); 10327 return true; 10328 } 10329 10330 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10331 Diag(SS.getRange().getBegin(), 10332 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10333 << SS.getScopeRep() 10334 << cast<CXXRecordDecl>(CurContext) 10335 << SS.getRange(); 10336 } 10337 return true; 10338 } 10339 10340 return false; 10341 } 10342 10343 // C++03 [namespace.udecl]p4: 10344 // A using-declaration used as a member-declaration shall refer 10345 // to a member of a base class of the class being defined [etc.]. 10346 10347 // Salient point: SS doesn't have to name a base class as long as 10348 // lookup only finds members from base classes. Therefore we can 10349 // diagnose here only if we can prove that that can't happen, 10350 // i.e. if the class hierarchies provably don't intersect. 10351 10352 // TODO: it would be nice if "definitely valid" results were cached 10353 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10354 // need to be repeated. 10355 10356 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10357 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10358 Bases.insert(Base); 10359 return true; 10360 }; 10361 10362 // Collect all bases. Return false if we find a dependent base. 10363 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10364 return false; 10365 10366 // Returns true if the base is dependent or is one of the accumulated base 10367 // classes. 10368 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10369 return !Bases.count(Base); 10370 }; 10371 10372 // Return false if the class has a dependent base or if it or one 10373 // of its bases is present in the base set of the current context. 10374 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10375 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10376 return false; 10377 10378 Diag(SS.getRange().getBegin(), 10379 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10380 << SS.getScopeRep() 10381 << cast<CXXRecordDecl>(CurContext) 10382 << SS.getRange(); 10383 10384 return true; 10385 } 10386 10387 Decl *Sema::ActOnAliasDeclaration(Scope *S, 10388 AccessSpecifier AS, 10389 MultiTemplateParamsArg TemplateParamLists, 10390 SourceLocation UsingLoc, 10391 UnqualifiedId &Name, 10392 AttributeList *AttrList, 10393 TypeResult Type, 10394 Decl *DeclFromDeclSpec) { 10395 // Skip up to the relevant declaration scope. 10396 while (S->isTemplateParamScope()) 10397 S = S->getParent(); 10398 assert((S->getFlags() & Scope::DeclScope) && 10399 "got alias-declaration outside of declaration scope"); 10400 10401 if (Type.isInvalid()) 10402 return nullptr; 10403 10404 bool Invalid = false; 10405 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10406 TypeSourceInfo *TInfo = nullptr; 10407 GetTypeFromParser(Type.get(), &TInfo); 10408 10409 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10410 return nullptr; 10411 10412 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10413 UPPC_DeclarationType)) { 10414 Invalid = true; 10415 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10416 TInfo->getTypeLoc().getBeginLoc()); 10417 } 10418 10419 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10420 TemplateParamLists.size() 10421 ? forRedeclarationInCurContext() 10422 : ForVisibleRedeclaration); 10423 LookupName(Previous, S); 10424 10425 // Warn about shadowing the name of a template parameter. 10426 if (Previous.isSingleResult() && 10427 Previous.getFoundDecl()->isTemplateParameter()) { 10428 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10429 Previous.clear(); 10430 } 10431 10432 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10433 "name in alias declaration must be an identifier"); 10434 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10435 Name.StartLocation, 10436 Name.Identifier, TInfo); 10437 10438 NewTD->setAccess(AS); 10439 10440 if (Invalid) 10441 NewTD->setInvalidDecl(); 10442 10443 ProcessDeclAttributeList(S, NewTD, AttrList); 10444 AddPragmaAttributes(S, NewTD); 10445 10446 CheckTypedefForVariablyModifiedType(S, NewTD); 10447 Invalid |= NewTD->isInvalidDecl(); 10448 10449 bool Redeclaration = false; 10450 10451 NamedDecl *NewND; 10452 if (TemplateParamLists.size()) { 10453 TypeAliasTemplateDecl *OldDecl = nullptr; 10454 TemplateParameterList *OldTemplateParams = nullptr; 10455 10456 if (TemplateParamLists.size() != 1) { 10457 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10458 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10459 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10460 } 10461 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10462 10463 // Check that we can declare a template here. 10464 if (CheckTemplateDeclScope(S, TemplateParams)) 10465 return nullptr; 10466 10467 // Only consider previous declarations in the same scope. 10468 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10469 /*ExplicitInstantiationOrSpecialization*/false); 10470 if (!Previous.empty()) { 10471 Redeclaration = true; 10472 10473 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10474 if (!OldDecl && !Invalid) { 10475 Diag(UsingLoc, diag::err_redefinition_different_kind) 10476 << Name.Identifier; 10477 10478 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10479 if (OldD->getLocation().isValid()) 10480 Diag(OldD->getLocation(), diag::note_previous_definition); 10481 10482 Invalid = true; 10483 } 10484 10485 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10486 if (TemplateParameterListsAreEqual(TemplateParams, 10487 OldDecl->getTemplateParameters(), 10488 /*Complain=*/true, 10489 TPL_TemplateMatch)) 10490 OldTemplateParams = OldDecl->getTemplateParameters(); 10491 else 10492 Invalid = true; 10493 10494 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10495 if (!Invalid && 10496 !Context.hasSameType(OldTD->getUnderlyingType(), 10497 NewTD->getUnderlyingType())) { 10498 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10499 // but we can't reasonably accept it. 10500 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10501 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10502 if (OldTD->getLocation().isValid()) 10503 Diag(OldTD->getLocation(), diag::note_previous_definition); 10504 Invalid = true; 10505 } 10506 } 10507 } 10508 10509 // Merge any previous default template arguments into our parameters, 10510 // and check the parameter list. 10511 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10512 TPC_TypeAliasTemplate)) 10513 return nullptr; 10514 10515 TypeAliasTemplateDecl *NewDecl = 10516 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10517 Name.Identifier, TemplateParams, 10518 NewTD); 10519 NewTD->setDescribedAliasTemplate(NewDecl); 10520 10521 NewDecl->setAccess(AS); 10522 10523 if (Invalid) 10524 NewDecl->setInvalidDecl(); 10525 else if (OldDecl) { 10526 NewDecl->setPreviousDecl(OldDecl); 10527 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10528 } 10529 10530 NewND = NewDecl; 10531 } else { 10532 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10533 setTagNameForLinkagePurposes(TD, NewTD); 10534 handleTagNumbering(TD, S); 10535 } 10536 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10537 NewND = NewTD; 10538 } 10539 10540 PushOnScopeChains(NewND, S); 10541 ActOnDocumentableDecl(NewND); 10542 return NewND; 10543 } 10544 10545 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10546 SourceLocation AliasLoc, 10547 IdentifierInfo *Alias, CXXScopeSpec &SS, 10548 SourceLocation IdentLoc, 10549 IdentifierInfo *Ident) { 10550 10551 // Lookup the namespace name. 10552 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10553 LookupParsedName(R, S, &SS); 10554 10555 if (R.isAmbiguous()) 10556 return nullptr; 10557 10558 if (R.empty()) { 10559 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10560 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10561 return nullptr; 10562 } 10563 } 10564 assert(!R.isAmbiguous() && !R.empty()); 10565 NamedDecl *ND = R.getRepresentativeDecl(); 10566 10567 // Check if we have a previous declaration with the same name. 10568 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10569 ForVisibleRedeclaration); 10570 LookupName(PrevR, S); 10571 10572 // Check we're not shadowing a template parameter. 10573 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10574 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10575 PrevR.clear(); 10576 } 10577 10578 // Filter out any other lookup result from an enclosing scope. 10579 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10580 /*AllowInlineNamespace*/false); 10581 10582 // Find the previous declaration and check that we can redeclare it. 10583 NamespaceAliasDecl *Prev = nullptr; 10584 if (PrevR.isSingleResult()) { 10585 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10586 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10587 // We already have an alias with the same name that points to the same 10588 // namespace; check that it matches. 10589 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10590 Prev = AD; 10591 } else if (isVisible(PrevDecl)) { 10592 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10593 << Alias; 10594 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10595 << AD->getNamespace(); 10596 return nullptr; 10597 } 10598 } else if (isVisible(PrevDecl)) { 10599 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10600 ? diag::err_redefinition 10601 : diag::err_redefinition_different_kind; 10602 Diag(AliasLoc, DiagID) << Alias; 10603 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10604 return nullptr; 10605 } 10606 } 10607 10608 // The use of a nested name specifier may trigger deprecation warnings. 10609 DiagnoseUseOfDecl(ND, IdentLoc); 10610 10611 NamespaceAliasDecl *AliasDecl = 10612 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10613 Alias, SS.getWithLocInContext(Context), 10614 IdentLoc, ND); 10615 if (Prev) 10616 AliasDecl->setPreviousDecl(Prev); 10617 10618 PushOnScopeChains(AliasDecl, S); 10619 return AliasDecl; 10620 } 10621 10622 namespace { 10623 struct SpecialMemberExceptionSpecInfo 10624 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10625 SourceLocation Loc; 10626 Sema::ImplicitExceptionSpecification ExceptSpec; 10627 10628 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10629 Sema::CXXSpecialMember CSM, 10630 Sema::InheritedConstructorInfo *ICI, 10631 SourceLocation Loc) 10632 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10633 10634 bool visitBase(CXXBaseSpecifier *Base); 10635 bool visitField(FieldDecl *FD); 10636 10637 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10638 unsigned Quals); 10639 10640 void visitSubobjectCall(Subobject Subobj, 10641 Sema::SpecialMemberOverloadResult SMOR); 10642 }; 10643 } 10644 10645 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10646 auto *RT = Base->getType()->getAs<RecordType>(); 10647 if (!RT) 10648 return false; 10649 10650 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10651 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10652 if (auto *BaseCtor = SMOR.getMethod()) { 10653 visitSubobjectCall(Base, BaseCtor); 10654 return false; 10655 } 10656 10657 visitClassSubobject(BaseClass, Base, 0); 10658 return false; 10659 } 10660 10661 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10662 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10663 Expr *E = FD->getInClassInitializer(); 10664 if (!E) 10665 // FIXME: It's a little wasteful to build and throw away a 10666 // CXXDefaultInitExpr here. 10667 // FIXME: We should have a single context note pointing at Loc, and 10668 // this location should be MD->getLocation() instead, since that's 10669 // the location where we actually use the default init expression. 10670 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10671 if (E) 10672 ExceptSpec.CalledExpr(E); 10673 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10674 ->getAs<RecordType>()) { 10675 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10676 FD->getType().getCVRQualifiers()); 10677 } 10678 return false; 10679 } 10680 10681 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10682 Subobject Subobj, 10683 unsigned Quals) { 10684 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10685 bool IsMutable = Field && Field->isMutable(); 10686 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10687 } 10688 10689 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10690 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10691 // Note, if lookup fails, it doesn't matter what exception specification we 10692 // choose because the special member will be deleted. 10693 if (CXXMethodDecl *MD = SMOR.getMethod()) 10694 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10695 } 10696 10697 static Sema::ImplicitExceptionSpecification 10698 ComputeDefaultedSpecialMemberExceptionSpec( 10699 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10700 Sema::InheritedConstructorInfo *ICI) { 10701 CXXRecordDecl *ClassDecl = MD->getParent(); 10702 10703 // C++ [except.spec]p14: 10704 // An implicitly declared special member function (Clause 12) shall have an 10705 // exception-specification. [...] 10706 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10707 if (ClassDecl->isInvalidDecl()) 10708 return Info.ExceptSpec; 10709 10710 // C++1z [except.spec]p7: 10711 // [Look for exceptions thrown by] a constructor selected [...] to 10712 // initialize a potentially constructed subobject, 10713 // C++1z [except.spec]p8: 10714 // The exception specification for an implicitly-declared destructor, or a 10715 // destructor without a noexcept-specifier, is potentially-throwing if and 10716 // only if any of the destructors for any of its potentially constructed 10717 // subojects is potentially throwing. 10718 // FIXME: We respect the first rule but ignore the "potentially constructed" 10719 // in the second rule to resolve a core issue (no number yet) that would have 10720 // us reject: 10721 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10722 // struct B : A {}; 10723 // struct C : B { void f(); }; 10724 // ... due to giving B::~B() a non-throwing exception specification. 10725 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10726 : Info.VisitAllBases); 10727 10728 return Info.ExceptSpec; 10729 } 10730 10731 namespace { 10732 /// RAII object to register a special member as being currently declared. 10733 struct DeclaringSpecialMember { 10734 Sema &S; 10735 Sema::SpecialMemberDecl D; 10736 Sema::ContextRAII SavedContext; 10737 bool WasAlreadyBeingDeclared; 10738 10739 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10740 : S(S), D(RD, CSM), SavedContext(S, RD) { 10741 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10742 if (WasAlreadyBeingDeclared) 10743 // This almost never happens, but if it does, ensure that our cache 10744 // doesn't contain a stale result. 10745 S.SpecialMemberCache.clear(); 10746 else { 10747 // Register a note to be produced if we encounter an error while 10748 // declaring the special member. 10749 Sema::CodeSynthesisContext Ctx; 10750 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10751 // FIXME: We don't have a location to use here. Using the class's 10752 // location maintains the fiction that we declare all special members 10753 // with the class, but (1) it's not clear that lying about that helps our 10754 // users understand what's going on, and (2) there may be outer contexts 10755 // on the stack (some of which are relevant) and printing them exposes 10756 // our lies. 10757 Ctx.PointOfInstantiation = RD->getLocation(); 10758 Ctx.Entity = RD; 10759 Ctx.SpecialMember = CSM; 10760 S.pushCodeSynthesisContext(Ctx); 10761 } 10762 } 10763 ~DeclaringSpecialMember() { 10764 if (!WasAlreadyBeingDeclared) { 10765 S.SpecialMembersBeingDeclared.erase(D); 10766 S.popCodeSynthesisContext(); 10767 } 10768 } 10769 10770 /// Are we already trying to declare this special member? 10771 bool isAlreadyBeingDeclared() const { 10772 return WasAlreadyBeingDeclared; 10773 } 10774 }; 10775 } 10776 10777 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10778 // Look up any existing declarations, but don't trigger declaration of all 10779 // implicit special members with this name. 10780 DeclarationName Name = FD->getDeclName(); 10781 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10782 ForExternalRedeclaration); 10783 for (auto *D : FD->getParent()->lookup(Name)) 10784 if (auto *Acceptable = R.getAcceptableDecl(D)) 10785 R.addDecl(Acceptable); 10786 R.resolveKind(); 10787 R.suppressDiagnostics(); 10788 10789 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10790 } 10791 10792 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10793 CXXRecordDecl *ClassDecl) { 10794 // C++ [class.ctor]p5: 10795 // A default constructor for a class X is a constructor of class X 10796 // that can be called without an argument. If there is no 10797 // user-declared constructor for class X, a default constructor is 10798 // implicitly declared. An implicitly-declared default constructor 10799 // is an inline public member of its class. 10800 assert(ClassDecl->needsImplicitDefaultConstructor() && 10801 "Should not build implicit default constructor!"); 10802 10803 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10804 if (DSM.isAlreadyBeingDeclared()) 10805 return nullptr; 10806 10807 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10808 CXXDefaultConstructor, 10809 false); 10810 10811 // Create the actual constructor declaration. 10812 CanQualType ClassType 10813 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10814 SourceLocation ClassLoc = ClassDecl->getLocation(); 10815 DeclarationName Name 10816 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10817 DeclarationNameInfo NameInfo(Name, ClassLoc); 10818 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10819 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10820 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10821 /*isImplicitlyDeclared=*/true, Constexpr); 10822 DefaultCon->setAccess(AS_public); 10823 DefaultCon->setDefaulted(); 10824 10825 if (getLangOpts().CUDA) { 10826 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10827 DefaultCon, 10828 /* ConstRHS */ false, 10829 /* Diagnose */ false); 10830 } 10831 10832 // Build an exception specification pointing back at this constructor. 10833 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10834 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10835 10836 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10837 // constructors is easy to compute. 10838 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10839 10840 // Note that we have declared this constructor. 10841 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10842 10843 Scope *S = getScopeForContext(ClassDecl); 10844 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10845 10846 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10847 SetDeclDeleted(DefaultCon, ClassLoc); 10848 10849 if (S) 10850 PushOnScopeChains(DefaultCon, S, false); 10851 ClassDecl->addDecl(DefaultCon); 10852 10853 return DefaultCon; 10854 } 10855 10856 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10857 CXXConstructorDecl *Constructor) { 10858 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10859 !Constructor->doesThisDeclarationHaveABody() && 10860 !Constructor->isDeleted()) && 10861 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10862 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10863 return; 10864 10865 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10866 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10867 10868 SynthesizedFunctionScope Scope(*this, Constructor); 10869 10870 // The exception specification is needed because we are defining the 10871 // function. 10872 ResolveExceptionSpec(CurrentLocation, 10873 Constructor->getType()->castAs<FunctionProtoType>()); 10874 MarkVTableUsed(CurrentLocation, ClassDecl); 10875 10876 // Add a context note for diagnostics produced after this point. 10877 Scope.addContextNote(CurrentLocation); 10878 10879 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10880 Constructor->setInvalidDecl(); 10881 return; 10882 } 10883 10884 SourceLocation Loc = Constructor->getLocEnd().isValid() 10885 ? Constructor->getLocEnd() 10886 : Constructor->getLocation(); 10887 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10888 Constructor->markUsed(Context); 10889 10890 if (ASTMutationListener *L = getASTMutationListener()) { 10891 L->CompletedImplicitDefinition(Constructor); 10892 } 10893 10894 DiagnoseUninitializedFields(*this, Constructor); 10895 } 10896 10897 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10898 // Perform any delayed checks on exception specifications. 10899 CheckDelayedMemberExceptionSpecs(); 10900 } 10901 10902 /// Find or create the fake constructor we synthesize to model constructing an 10903 /// object of a derived class via a constructor of a base class. 10904 CXXConstructorDecl * 10905 Sema::findInheritingConstructor(SourceLocation Loc, 10906 CXXConstructorDecl *BaseCtor, 10907 ConstructorUsingShadowDecl *Shadow) { 10908 CXXRecordDecl *Derived = Shadow->getParent(); 10909 SourceLocation UsingLoc = Shadow->getLocation(); 10910 10911 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10912 // For now we use the name of the base class constructor as a member of the 10913 // derived class to indicate a (fake) inherited constructor name. 10914 DeclarationName Name = BaseCtor->getDeclName(); 10915 10916 // Check to see if we already have a fake constructor for this inherited 10917 // constructor call. 10918 for (NamedDecl *Ctor : Derived->lookup(Name)) 10919 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10920 ->getInheritedConstructor() 10921 .getConstructor(), 10922 BaseCtor)) 10923 return cast<CXXConstructorDecl>(Ctor); 10924 10925 DeclarationNameInfo NameInfo(Name, UsingLoc); 10926 TypeSourceInfo *TInfo = 10927 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10928 FunctionProtoTypeLoc ProtoLoc = 10929 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10930 10931 // Check the inherited constructor is valid and find the list of base classes 10932 // from which it was inherited. 10933 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10934 10935 bool Constexpr = 10936 BaseCtor->isConstexpr() && 10937 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10938 false, BaseCtor, &ICI); 10939 10940 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10941 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10942 BaseCtor->isExplicit(), /*Inline=*/true, 10943 /*ImplicitlyDeclared=*/true, Constexpr, 10944 InheritedConstructor(Shadow, BaseCtor)); 10945 if (Shadow->isInvalidDecl()) 10946 DerivedCtor->setInvalidDecl(); 10947 10948 // Build an unevaluated exception specification for this fake constructor. 10949 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10950 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10951 EPI.ExceptionSpec.Type = EST_Unevaluated; 10952 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10953 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10954 FPT->getParamTypes(), EPI)); 10955 10956 // Build the parameter declarations. 10957 SmallVector<ParmVarDecl *, 16> ParamDecls; 10958 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10959 TypeSourceInfo *TInfo = 10960 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10961 ParmVarDecl *PD = ParmVarDecl::Create( 10962 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10963 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10964 PD->setScopeInfo(0, I); 10965 PD->setImplicit(); 10966 // Ensure attributes are propagated onto parameters (this matters for 10967 // format, pass_object_size, ...). 10968 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10969 ParamDecls.push_back(PD); 10970 ProtoLoc.setParam(I, PD); 10971 } 10972 10973 // Set up the new constructor. 10974 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10975 DerivedCtor->setAccess(BaseCtor->getAccess()); 10976 DerivedCtor->setParams(ParamDecls); 10977 Derived->addDecl(DerivedCtor); 10978 10979 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10980 SetDeclDeleted(DerivedCtor, UsingLoc); 10981 10982 return DerivedCtor; 10983 } 10984 10985 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10986 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10987 Ctor->getInheritedConstructor().getShadowDecl()); 10988 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10989 /*Diagnose*/true); 10990 } 10991 10992 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10993 CXXConstructorDecl *Constructor) { 10994 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10995 assert(Constructor->getInheritedConstructor() && 10996 !Constructor->doesThisDeclarationHaveABody() && 10997 !Constructor->isDeleted()); 10998 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10999 return; 11000 11001 // Initializations are performed "as if by a defaulted default constructor", 11002 // so enter the appropriate scope. 11003 SynthesizedFunctionScope Scope(*this, Constructor); 11004 11005 // The exception specification is needed because we are defining the 11006 // function. 11007 ResolveExceptionSpec(CurrentLocation, 11008 Constructor->getType()->castAs<FunctionProtoType>()); 11009 MarkVTableUsed(CurrentLocation, ClassDecl); 11010 11011 // Add a context note for diagnostics produced after this point. 11012 Scope.addContextNote(CurrentLocation); 11013 11014 ConstructorUsingShadowDecl *Shadow = 11015 Constructor->getInheritedConstructor().getShadowDecl(); 11016 CXXConstructorDecl *InheritedCtor = 11017 Constructor->getInheritedConstructor().getConstructor(); 11018 11019 // [class.inhctor.init]p1: 11020 // initialization proceeds as if a defaulted default constructor is used to 11021 // initialize the D object and each base class subobject from which the 11022 // constructor was inherited 11023 11024 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11025 CXXRecordDecl *RD = Shadow->getParent(); 11026 SourceLocation InitLoc = Shadow->getLocation(); 11027 11028 // Build explicit initializers for all base classes from which the 11029 // constructor was inherited. 11030 SmallVector<CXXCtorInitializer*, 8> Inits; 11031 for (bool VBase : {false, true}) { 11032 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11033 if (B.isVirtual() != VBase) 11034 continue; 11035 11036 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11037 if (!BaseRD) 11038 continue; 11039 11040 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11041 if (!BaseCtor.first) 11042 continue; 11043 11044 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11045 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11046 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11047 11048 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11049 Inits.push_back(new (Context) CXXCtorInitializer( 11050 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11051 SourceLocation())); 11052 } 11053 } 11054 11055 // We now proceed as if for a defaulted default constructor, with the relevant 11056 // initializers replaced. 11057 11058 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11059 Constructor->setInvalidDecl(); 11060 return; 11061 } 11062 11063 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11064 Constructor->markUsed(Context); 11065 11066 if (ASTMutationListener *L = getASTMutationListener()) { 11067 L->CompletedImplicitDefinition(Constructor); 11068 } 11069 11070 DiagnoseUninitializedFields(*this, Constructor); 11071 } 11072 11073 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11074 // C++ [class.dtor]p2: 11075 // If a class has no user-declared destructor, a destructor is 11076 // declared implicitly. An implicitly-declared destructor is an 11077 // inline public member of its class. 11078 assert(ClassDecl->needsImplicitDestructor()); 11079 11080 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11081 if (DSM.isAlreadyBeingDeclared()) 11082 return nullptr; 11083 11084 // Create the actual destructor declaration. 11085 CanQualType ClassType 11086 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11087 SourceLocation ClassLoc = ClassDecl->getLocation(); 11088 DeclarationName Name 11089 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11090 DeclarationNameInfo NameInfo(Name, ClassLoc); 11091 CXXDestructorDecl *Destructor 11092 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11093 QualType(), nullptr, /*isInline=*/true, 11094 /*isImplicitlyDeclared=*/true); 11095 Destructor->setAccess(AS_public); 11096 Destructor->setDefaulted(); 11097 11098 if (getLangOpts().CUDA) { 11099 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11100 Destructor, 11101 /* ConstRHS */ false, 11102 /* Diagnose */ false); 11103 } 11104 11105 // Build an exception specification pointing back at this destructor. 11106 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 11107 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11108 11109 // We don't need to use SpecialMemberIsTrivial here; triviality for 11110 // destructors is easy to compute. 11111 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11112 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11113 ClassDecl->hasTrivialDestructorForCall()); 11114 11115 // Note that we have declared this destructor. 11116 ++ASTContext::NumImplicitDestructorsDeclared; 11117 11118 Scope *S = getScopeForContext(ClassDecl); 11119 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11120 11121 // We can't check whether an implicit destructor is deleted before we complete 11122 // the definition of the class, because its validity depends on the alignment 11123 // of the class. We'll check this from ActOnFields once the class is complete. 11124 if (ClassDecl->isCompleteDefinition() && 11125 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11126 SetDeclDeleted(Destructor, ClassLoc); 11127 11128 // Introduce this destructor into its scope. 11129 if (S) 11130 PushOnScopeChains(Destructor, S, false); 11131 ClassDecl->addDecl(Destructor); 11132 11133 return Destructor; 11134 } 11135 11136 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11137 CXXDestructorDecl *Destructor) { 11138 assert((Destructor->isDefaulted() && 11139 !Destructor->doesThisDeclarationHaveABody() && 11140 !Destructor->isDeleted()) && 11141 "DefineImplicitDestructor - call it for implicit default dtor"); 11142 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11143 return; 11144 11145 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11146 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11147 11148 SynthesizedFunctionScope Scope(*this, Destructor); 11149 11150 // The exception specification is needed because we are defining the 11151 // function. 11152 ResolveExceptionSpec(CurrentLocation, 11153 Destructor->getType()->castAs<FunctionProtoType>()); 11154 MarkVTableUsed(CurrentLocation, ClassDecl); 11155 11156 // Add a context note for diagnostics produced after this point. 11157 Scope.addContextNote(CurrentLocation); 11158 11159 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11160 Destructor->getParent()); 11161 11162 if (CheckDestructor(Destructor)) { 11163 Destructor->setInvalidDecl(); 11164 return; 11165 } 11166 11167 SourceLocation Loc = Destructor->getLocEnd().isValid() 11168 ? Destructor->getLocEnd() 11169 : Destructor->getLocation(); 11170 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11171 Destructor->markUsed(Context); 11172 11173 if (ASTMutationListener *L = getASTMutationListener()) { 11174 L->CompletedImplicitDefinition(Destructor); 11175 } 11176 } 11177 11178 /// Perform any semantic analysis which needs to be delayed until all 11179 /// pending class member declarations have been parsed. 11180 void Sema::ActOnFinishCXXMemberDecls() { 11181 // If the context is an invalid C++ class, just suppress these checks. 11182 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11183 if (Record->isInvalidDecl()) { 11184 DelayedDefaultedMemberExceptionSpecs.clear(); 11185 DelayedExceptionSpecChecks.clear(); 11186 return; 11187 } 11188 checkForMultipleExportedDefaultConstructors(*this, Record); 11189 } 11190 } 11191 11192 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11193 referenceDLLExportedClassMethods(); 11194 } 11195 11196 void Sema::referenceDLLExportedClassMethods() { 11197 if (!DelayedDllExportClasses.empty()) { 11198 // Calling ReferenceDllExportedMembers might cause the current function to 11199 // be called again, so use a local copy of DelayedDllExportClasses. 11200 SmallVector<CXXRecordDecl *, 4> WorkList; 11201 std::swap(DelayedDllExportClasses, WorkList); 11202 for (CXXRecordDecl *Class : WorkList) 11203 ReferenceDllExportedMembers(*this, Class); 11204 } 11205 } 11206 11207 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 11208 CXXDestructorDecl *Destructor) { 11209 assert(getLangOpts().CPlusPlus11 && 11210 "adjusting dtor exception specs was introduced in c++11"); 11211 11212 // C++11 [class.dtor]p3: 11213 // A declaration of a destructor that does not have an exception- 11214 // specification is implicitly considered to have the same exception- 11215 // specification as an implicit declaration. 11216 const FunctionProtoType *DtorType = Destructor->getType()-> 11217 getAs<FunctionProtoType>(); 11218 if (DtorType->hasExceptionSpec()) 11219 return; 11220 11221 // Replace the destructor's type, building off the existing one. Fortunately, 11222 // the only thing of interest in the destructor type is its extended info. 11223 // The return and arguments are fixed. 11224 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11225 EPI.ExceptionSpec.Type = EST_Unevaluated; 11226 EPI.ExceptionSpec.SourceDecl = Destructor; 11227 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11228 11229 // FIXME: If the destructor has a body that could throw, and the newly created 11230 // spec doesn't allow exceptions, we should emit a warning, because this 11231 // change in behavior can break conforming C++03 programs at runtime. 11232 // However, we don't have a body or an exception specification yet, so it 11233 // needs to be done somewhere else. 11234 } 11235 11236 namespace { 11237 /// An abstract base class for all helper classes used in building the 11238 // copy/move operators. These classes serve as factory functions and help us 11239 // avoid using the same Expr* in the AST twice. 11240 class ExprBuilder { 11241 ExprBuilder(const ExprBuilder&) = delete; 11242 ExprBuilder &operator=(const ExprBuilder&) = delete; 11243 11244 protected: 11245 static Expr *assertNotNull(Expr *E) { 11246 assert(E && "Expression construction must not fail."); 11247 return E; 11248 } 11249 11250 public: 11251 ExprBuilder() {} 11252 virtual ~ExprBuilder() {} 11253 11254 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11255 }; 11256 11257 class RefBuilder: public ExprBuilder { 11258 VarDecl *Var; 11259 QualType VarType; 11260 11261 public: 11262 Expr *build(Sema &S, SourceLocation Loc) const override { 11263 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11264 } 11265 11266 RefBuilder(VarDecl *Var, QualType VarType) 11267 : Var(Var), VarType(VarType) {} 11268 }; 11269 11270 class ThisBuilder: public ExprBuilder { 11271 public: 11272 Expr *build(Sema &S, SourceLocation Loc) const override { 11273 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11274 } 11275 }; 11276 11277 class CastBuilder: public ExprBuilder { 11278 const ExprBuilder &Builder; 11279 QualType Type; 11280 ExprValueKind Kind; 11281 const CXXCastPath &Path; 11282 11283 public: 11284 Expr *build(Sema &S, SourceLocation Loc) const override { 11285 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11286 CK_UncheckedDerivedToBase, Kind, 11287 &Path).get()); 11288 } 11289 11290 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11291 const CXXCastPath &Path) 11292 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11293 }; 11294 11295 class DerefBuilder: public ExprBuilder { 11296 const ExprBuilder &Builder; 11297 11298 public: 11299 Expr *build(Sema &S, SourceLocation Loc) const override { 11300 return assertNotNull( 11301 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11302 } 11303 11304 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11305 }; 11306 11307 class MemberBuilder: public ExprBuilder { 11308 const ExprBuilder &Builder; 11309 QualType Type; 11310 CXXScopeSpec SS; 11311 bool IsArrow; 11312 LookupResult &MemberLookup; 11313 11314 public: 11315 Expr *build(Sema &S, SourceLocation Loc) const override { 11316 return assertNotNull(S.BuildMemberReferenceExpr( 11317 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11318 nullptr, MemberLookup, nullptr, nullptr).get()); 11319 } 11320 11321 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11322 LookupResult &MemberLookup) 11323 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11324 MemberLookup(MemberLookup) {} 11325 }; 11326 11327 class MoveCastBuilder: public ExprBuilder { 11328 const ExprBuilder &Builder; 11329 11330 public: 11331 Expr *build(Sema &S, SourceLocation Loc) const override { 11332 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11333 } 11334 11335 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11336 }; 11337 11338 class LvalueConvBuilder: public ExprBuilder { 11339 const ExprBuilder &Builder; 11340 11341 public: 11342 Expr *build(Sema &S, SourceLocation Loc) const override { 11343 return assertNotNull( 11344 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11345 } 11346 11347 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11348 }; 11349 11350 class SubscriptBuilder: public ExprBuilder { 11351 const ExprBuilder &Base; 11352 const ExprBuilder &Index; 11353 11354 public: 11355 Expr *build(Sema &S, SourceLocation Loc) const override { 11356 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11357 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11358 } 11359 11360 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11361 : Base(Base), Index(Index) {} 11362 }; 11363 11364 } // end anonymous namespace 11365 11366 /// When generating a defaulted copy or move assignment operator, if a field 11367 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11368 /// do so. This optimization only applies for arrays of scalars, and for arrays 11369 /// of class type where the selected copy/move-assignment operator is trivial. 11370 static StmtResult 11371 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11372 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11373 // Compute the size of the memory buffer to be copied. 11374 QualType SizeType = S.Context.getSizeType(); 11375 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11376 S.Context.getTypeSizeInChars(T).getQuantity()); 11377 11378 // Take the address of the field references for "from" and "to". We 11379 // directly construct UnaryOperators here because semantic analysis 11380 // does not permit us to take the address of an xvalue. 11381 Expr *From = FromB.build(S, Loc); 11382 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11383 S.Context.getPointerType(From->getType()), 11384 VK_RValue, OK_Ordinary, Loc, false); 11385 Expr *To = ToB.build(S, Loc); 11386 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11387 S.Context.getPointerType(To->getType()), 11388 VK_RValue, OK_Ordinary, Loc, false); 11389 11390 const Type *E = T->getBaseElementTypeUnsafe(); 11391 bool NeedsCollectableMemCpy = 11392 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11393 11394 // Create a reference to the __builtin_objc_memmove_collectable function 11395 StringRef MemCpyName = NeedsCollectableMemCpy ? 11396 "__builtin_objc_memmove_collectable" : 11397 "__builtin_memcpy"; 11398 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11399 Sema::LookupOrdinaryName); 11400 S.LookupName(R, S.TUScope, true); 11401 11402 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11403 if (!MemCpy) 11404 // Something went horribly wrong earlier, and we will have complained 11405 // about it. 11406 return StmtError(); 11407 11408 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11409 VK_RValue, Loc, nullptr); 11410 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11411 11412 Expr *CallArgs[] = { 11413 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11414 }; 11415 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11416 Loc, CallArgs, Loc); 11417 11418 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11419 return Call.getAs<Stmt>(); 11420 } 11421 11422 /// Builds a statement that copies/moves the given entity from \p From to 11423 /// \c To. 11424 /// 11425 /// This routine is used to copy/move the members of a class with an 11426 /// implicitly-declared copy/move assignment operator. When the entities being 11427 /// copied are arrays, this routine builds for loops to copy them. 11428 /// 11429 /// \param S The Sema object used for type-checking. 11430 /// 11431 /// \param Loc The location where the implicit copy/move is being generated. 11432 /// 11433 /// \param T The type of the expressions being copied/moved. Both expressions 11434 /// must have this type. 11435 /// 11436 /// \param To The expression we are copying/moving to. 11437 /// 11438 /// \param From The expression we are copying/moving from. 11439 /// 11440 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11441 /// Otherwise, it's a non-static member subobject. 11442 /// 11443 /// \param Copying Whether we're copying or moving. 11444 /// 11445 /// \param Depth Internal parameter recording the depth of the recursion. 11446 /// 11447 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11448 /// if a memcpy should be used instead. 11449 static StmtResult 11450 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11451 const ExprBuilder &To, const ExprBuilder &From, 11452 bool CopyingBaseSubobject, bool Copying, 11453 unsigned Depth = 0) { 11454 // C++11 [class.copy]p28: 11455 // Each subobject is assigned in the manner appropriate to its type: 11456 // 11457 // - if the subobject is of class type, as if by a call to operator= with 11458 // the subobject as the object expression and the corresponding 11459 // subobject of x as a single function argument (as if by explicit 11460 // qualification; that is, ignoring any possible virtual overriding 11461 // functions in more derived classes); 11462 // 11463 // C++03 [class.copy]p13: 11464 // - if the subobject is of class type, the copy assignment operator for 11465 // the class is used (as if by explicit qualification; that is, 11466 // ignoring any possible virtual overriding functions in more derived 11467 // classes); 11468 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11469 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11470 11471 // Look for operator=. 11472 DeclarationName Name 11473 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11474 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11475 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11476 11477 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11478 // operator. 11479 if (!S.getLangOpts().CPlusPlus11) { 11480 LookupResult::Filter F = OpLookup.makeFilter(); 11481 while (F.hasNext()) { 11482 NamedDecl *D = F.next(); 11483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11484 if (Method->isCopyAssignmentOperator() || 11485 (!Copying && Method->isMoveAssignmentOperator())) 11486 continue; 11487 11488 F.erase(); 11489 } 11490 F.done(); 11491 } 11492 11493 // Suppress the protected check (C++ [class.protected]) for each of the 11494 // assignment operators we found. This strange dance is required when 11495 // we're assigning via a base classes's copy-assignment operator. To 11496 // ensure that we're getting the right base class subobject (without 11497 // ambiguities), we need to cast "this" to that subobject type; to 11498 // ensure that we don't go through the virtual call mechanism, we need 11499 // to qualify the operator= name with the base class (see below). However, 11500 // this means that if the base class has a protected copy assignment 11501 // operator, the protected member access check will fail. So, we 11502 // rewrite "protected" access to "public" access in this case, since we 11503 // know by construction that we're calling from a derived class. 11504 if (CopyingBaseSubobject) { 11505 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11506 L != LEnd; ++L) { 11507 if (L.getAccess() == AS_protected) 11508 L.setAccess(AS_public); 11509 } 11510 } 11511 11512 // Create the nested-name-specifier that will be used to qualify the 11513 // reference to operator=; this is required to suppress the virtual 11514 // call mechanism. 11515 CXXScopeSpec SS; 11516 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11517 SS.MakeTrivial(S.Context, 11518 NestedNameSpecifier::Create(S.Context, nullptr, false, 11519 CanonicalT), 11520 Loc); 11521 11522 // Create the reference to operator=. 11523 ExprResult OpEqualRef 11524 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11525 SS, /*TemplateKWLoc=*/SourceLocation(), 11526 /*FirstQualifierInScope=*/nullptr, 11527 OpLookup, 11528 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11529 /*SuppressQualifierCheck=*/true); 11530 if (OpEqualRef.isInvalid()) 11531 return StmtError(); 11532 11533 // Build the call to the assignment operator. 11534 11535 Expr *FromInst = From.build(S, Loc); 11536 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11537 OpEqualRef.getAs<Expr>(), 11538 Loc, FromInst, Loc); 11539 if (Call.isInvalid()) 11540 return StmtError(); 11541 11542 // If we built a call to a trivial 'operator=' while copying an array, 11543 // bail out. We'll replace the whole shebang with a memcpy. 11544 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11545 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11546 return StmtResult((Stmt*)nullptr); 11547 11548 // Convert to an expression-statement, and clean up any produced 11549 // temporaries. 11550 return S.ActOnExprStmt(Call); 11551 } 11552 11553 // - if the subobject is of scalar type, the built-in assignment 11554 // operator is used. 11555 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11556 if (!ArrayTy) { 11557 ExprResult Assignment = S.CreateBuiltinBinOp( 11558 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11559 if (Assignment.isInvalid()) 11560 return StmtError(); 11561 return S.ActOnExprStmt(Assignment); 11562 } 11563 11564 // - if the subobject is an array, each element is assigned, in the 11565 // manner appropriate to the element type; 11566 11567 // Construct a loop over the array bounds, e.g., 11568 // 11569 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11570 // 11571 // that will copy each of the array elements. 11572 QualType SizeType = S.Context.getSizeType(); 11573 11574 // Create the iteration variable. 11575 IdentifierInfo *IterationVarName = nullptr; 11576 { 11577 SmallString<8> Str; 11578 llvm::raw_svector_ostream OS(Str); 11579 OS << "__i" << Depth; 11580 IterationVarName = &S.Context.Idents.get(OS.str()); 11581 } 11582 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11583 IterationVarName, SizeType, 11584 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11585 SC_None); 11586 11587 // Initialize the iteration variable to zero. 11588 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11589 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11590 11591 // Creates a reference to the iteration variable. 11592 RefBuilder IterationVarRef(IterationVar, SizeType); 11593 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11594 11595 // Create the DeclStmt that holds the iteration variable. 11596 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11597 11598 // Subscript the "from" and "to" expressions with the iteration variable. 11599 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11600 MoveCastBuilder FromIndexMove(FromIndexCopy); 11601 const ExprBuilder *FromIndex; 11602 if (Copying) 11603 FromIndex = &FromIndexCopy; 11604 else 11605 FromIndex = &FromIndexMove; 11606 11607 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11608 11609 // Build the copy/move for an individual element of the array. 11610 StmtResult Copy = 11611 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11612 ToIndex, *FromIndex, CopyingBaseSubobject, 11613 Copying, Depth + 1); 11614 // Bail out if copying fails or if we determined that we should use memcpy. 11615 if (Copy.isInvalid() || !Copy.get()) 11616 return Copy; 11617 11618 // Create the comparison against the array bound. 11619 llvm::APInt Upper 11620 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11621 Expr *Comparison 11622 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11623 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11624 BO_NE, S.Context.BoolTy, 11625 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11626 11627 // Create the pre-increment of the iteration variable. We can determine 11628 // whether the increment will overflow based on the value of the array 11629 // bound. 11630 Expr *Increment = new (S.Context) 11631 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11632 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11633 11634 // Construct the loop that copies all elements of this array. 11635 return S.ActOnForStmt( 11636 Loc, Loc, InitStmt, 11637 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11638 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11639 } 11640 11641 static StmtResult 11642 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11643 const ExprBuilder &To, const ExprBuilder &From, 11644 bool CopyingBaseSubobject, bool Copying) { 11645 // Maybe we should use a memcpy? 11646 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11647 T.isTriviallyCopyableType(S.Context)) 11648 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11649 11650 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11651 CopyingBaseSubobject, 11652 Copying, 0)); 11653 11654 // If we ended up picking a trivial assignment operator for an array of a 11655 // non-trivially-copyable class type, just emit a memcpy. 11656 if (!Result.isInvalid() && !Result.get()) 11657 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11658 11659 return Result; 11660 } 11661 11662 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11663 // Note: The following rules are largely analoguous to the copy 11664 // constructor rules. Note that virtual bases are not taken into account 11665 // for determining the argument type of the operator. Note also that 11666 // operators taking an object instead of a reference are allowed. 11667 assert(ClassDecl->needsImplicitCopyAssignment()); 11668 11669 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11670 if (DSM.isAlreadyBeingDeclared()) 11671 return nullptr; 11672 11673 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11674 QualType RetType = Context.getLValueReferenceType(ArgType); 11675 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11676 if (Const) 11677 ArgType = ArgType.withConst(); 11678 ArgType = Context.getLValueReferenceType(ArgType); 11679 11680 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11681 CXXCopyAssignment, 11682 Const); 11683 11684 // An implicitly-declared copy assignment operator is an inline public 11685 // member of its class. 11686 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11687 SourceLocation ClassLoc = ClassDecl->getLocation(); 11688 DeclarationNameInfo NameInfo(Name, ClassLoc); 11689 CXXMethodDecl *CopyAssignment = 11690 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11691 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11692 /*isInline=*/true, Constexpr, SourceLocation()); 11693 CopyAssignment->setAccess(AS_public); 11694 CopyAssignment->setDefaulted(); 11695 CopyAssignment->setImplicit(); 11696 11697 if (getLangOpts().CUDA) { 11698 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11699 CopyAssignment, 11700 /* ConstRHS */ Const, 11701 /* Diagnose */ false); 11702 } 11703 11704 // Build an exception specification pointing back at this member. 11705 FunctionProtoType::ExtProtoInfo EPI = 11706 getImplicitMethodEPI(*this, CopyAssignment); 11707 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11708 11709 // Add the parameter to the operator. 11710 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11711 ClassLoc, ClassLoc, 11712 /*Id=*/nullptr, ArgType, 11713 /*TInfo=*/nullptr, SC_None, 11714 nullptr); 11715 CopyAssignment->setParams(FromParam); 11716 11717 CopyAssignment->setTrivial( 11718 ClassDecl->needsOverloadResolutionForCopyAssignment() 11719 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11720 : ClassDecl->hasTrivialCopyAssignment()); 11721 11722 // Note that we have added this copy-assignment operator. 11723 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11724 11725 Scope *S = getScopeForContext(ClassDecl); 11726 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11727 11728 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11729 SetDeclDeleted(CopyAssignment, ClassLoc); 11730 11731 if (S) 11732 PushOnScopeChains(CopyAssignment, S, false); 11733 ClassDecl->addDecl(CopyAssignment); 11734 11735 return CopyAssignment; 11736 } 11737 11738 /// Diagnose an implicit copy operation for a class which is odr-used, but 11739 /// which is deprecated because the class has a user-declared copy constructor, 11740 /// copy assignment operator, or destructor. 11741 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11742 assert(CopyOp->isImplicit()); 11743 11744 CXXRecordDecl *RD = CopyOp->getParent(); 11745 CXXMethodDecl *UserDeclaredOperation = nullptr; 11746 11747 // In Microsoft mode, assignment operations don't affect constructors and 11748 // vice versa. 11749 if (RD->hasUserDeclaredDestructor()) { 11750 UserDeclaredOperation = RD->getDestructor(); 11751 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11752 RD->hasUserDeclaredCopyConstructor() && 11753 !S.getLangOpts().MSVCCompat) { 11754 // Find any user-declared copy constructor. 11755 for (auto *I : RD->ctors()) { 11756 if (I->isCopyConstructor()) { 11757 UserDeclaredOperation = I; 11758 break; 11759 } 11760 } 11761 assert(UserDeclaredOperation); 11762 } else if (isa<CXXConstructorDecl>(CopyOp) && 11763 RD->hasUserDeclaredCopyAssignment() && 11764 !S.getLangOpts().MSVCCompat) { 11765 // Find any user-declared move assignment operator. 11766 for (auto *I : RD->methods()) { 11767 if (I->isCopyAssignmentOperator()) { 11768 UserDeclaredOperation = I; 11769 break; 11770 } 11771 } 11772 assert(UserDeclaredOperation); 11773 } 11774 11775 if (UserDeclaredOperation) { 11776 S.Diag(UserDeclaredOperation->getLocation(), 11777 diag::warn_deprecated_copy_operation) 11778 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11779 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11780 } 11781 } 11782 11783 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11784 CXXMethodDecl *CopyAssignOperator) { 11785 assert((CopyAssignOperator->isDefaulted() && 11786 CopyAssignOperator->isOverloadedOperator() && 11787 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11788 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11789 !CopyAssignOperator->isDeleted()) && 11790 "DefineImplicitCopyAssignment called for wrong function"); 11791 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11792 return; 11793 11794 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11795 if (ClassDecl->isInvalidDecl()) { 11796 CopyAssignOperator->setInvalidDecl(); 11797 return; 11798 } 11799 11800 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11801 11802 // The exception specification is needed because we are defining the 11803 // function. 11804 ResolveExceptionSpec(CurrentLocation, 11805 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11806 11807 // Add a context note for diagnostics produced after this point. 11808 Scope.addContextNote(CurrentLocation); 11809 11810 // C++11 [class.copy]p18: 11811 // The [definition of an implicitly declared copy assignment operator] is 11812 // deprecated if the class has a user-declared copy constructor or a 11813 // user-declared destructor. 11814 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11815 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11816 11817 // C++0x [class.copy]p30: 11818 // The implicitly-defined or explicitly-defaulted copy assignment operator 11819 // for a non-union class X performs memberwise copy assignment of its 11820 // subobjects. The direct base classes of X are assigned first, in the 11821 // order of their declaration in the base-specifier-list, and then the 11822 // immediate non-static data members of X are assigned, in the order in 11823 // which they were declared in the class definition. 11824 11825 // The statements that form the synthesized function body. 11826 SmallVector<Stmt*, 8> Statements; 11827 11828 // The parameter for the "other" object, which we are copying from. 11829 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11830 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11831 QualType OtherRefType = Other->getType(); 11832 if (const LValueReferenceType *OtherRef 11833 = OtherRefType->getAs<LValueReferenceType>()) { 11834 OtherRefType = OtherRef->getPointeeType(); 11835 OtherQuals = OtherRefType.getQualifiers(); 11836 } 11837 11838 // Our location for everything implicitly-generated. 11839 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11840 ? CopyAssignOperator->getLocEnd() 11841 : CopyAssignOperator->getLocation(); 11842 11843 // Builds a DeclRefExpr for the "other" object. 11844 RefBuilder OtherRef(Other, OtherRefType); 11845 11846 // Builds the "this" pointer. 11847 ThisBuilder This; 11848 11849 // Assign base classes. 11850 bool Invalid = false; 11851 for (auto &Base : ClassDecl->bases()) { 11852 // Form the assignment: 11853 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11854 QualType BaseType = Base.getType().getUnqualifiedType(); 11855 if (!BaseType->isRecordType()) { 11856 Invalid = true; 11857 continue; 11858 } 11859 11860 CXXCastPath BasePath; 11861 BasePath.push_back(&Base); 11862 11863 // Construct the "from" expression, which is an implicit cast to the 11864 // appropriately-qualified base type. 11865 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11866 VK_LValue, BasePath); 11867 11868 // Dereference "this". 11869 DerefBuilder DerefThis(This); 11870 CastBuilder To(DerefThis, 11871 Context.getCVRQualifiedType( 11872 BaseType, CopyAssignOperator->getTypeQualifiers()), 11873 VK_LValue, BasePath); 11874 11875 // Build the copy. 11876 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11877 To, From, 11878 /*CopyingBaseSubobject=*/true, 11879 /*Copying=*/true); 11880 if (Copy.isInvalid()) { 11881 CopyAssignOperator->setInvalidDecl(); 11882 return; 11883 } 11884 11885 // Success! Record the copy. 11886 Statements.push_back(Copy.getAs<Expr>()); 11887 } 11888 11889 // Assign non-static members. 11890 for (auto *Field : ClassDecl->fields()) { 11891 // FIXME: We should form some kind of AST representation for the implied 11892 // memcpy in a union copy operation. 11893 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11894 continue; 11895 11896 if (Field->isInvalidDecl()) { 11897 Invalid = true; 11898 continue; 11899 } 11900 11901 // Check for members of reference type; we can't copy those. 11902 if (Field->getType()->isReferenceType()) { 11903 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11904 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11905 Diag(Field->getLocation(), diag::note_declared_at); 11906 Invalid = true; 11907 continue; 11908 } 11909 11910 // Check for members of const-qualified, non-class type. 11911 QualType BaseType = Context.getBaseElementType(Field->getType()); 11912 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11913 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11914 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11915 Diag(Field->getLocation(), diag::note_declared_at); 11916 Invalid = true; 11917 continue; 11918 } 11919 11920 // Suppress assigning zero-width bitfields. 11921 if (Field->isZeroLengthBitField(Context)) 11922 continue; 11923 11924 QualType FieldType = Field->getType().getNonReferenceType(); 11925 if (FieldType->isIncompleteArrayType()) { 11926 assert(ClassDecl->hasFlexibleArrayMember() && 11927 "Incomplete array type is not valid"); 11928 continue; 11929 } 11930 11931 // Build references to the field in the object we're copying from and to. 11932 CXXScopeSpec SS; // Intentionally empty 11933 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11934 LookupMemberName); 11935 MemberLookup.addDecl(Field); 11936 MemberLookup.resolveKind(); 11937 11938 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11939 11940 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11941 11942 // Build the copy of this field. 11943 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11944 To, From, 11945 /*CopyingBaseSubobject=*/false, 11946 /*Copying=*/true); 11947 if (Copy.isInvalid()) { 11948 CopyAssignOperator->setInvalidDecl(); 11949 return; 11950 } 11951 11952 // Success! Record the copy. 11953 Statements.push_back(Copy.getAs<Stmt>()); 11954 } 11955 11956 if (!Invalid) { 11957 // Add a "return *this;" 11958 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11959 11960 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11961 if (Return.isInvalid()) 11962 Invalid = true; 11963 else 11964 Statements.push_back(Return.getAs<Stmt>()); 11965 } 11966 11967 if (Invalid) { 11968 CopyAssignOperator->setInvalidDecl(); 11969 return; 11970 } 11971 11972 StmtResult Body; 11973 { 11974 CompoundScopeRAII CompoundScope(*this); 11975 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11976 /*isStmtExpr=*/false); 11977 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11978 } 11979 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11980 CopyAssignOperator->markUsed(Context); 11981 11982 if (ASTMutationListener *L = getASTMutationListener()) { 11983 L->CompletedImplicitDefinition(CopyAssignOperator); 11984 } 11985 } 11986 11987 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11988 assert(ClassDecl->needsImplicitMoveAssignment()); 11989 11990 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11991 if (DSM.isAlreadyBeingDeclared()) 11992 return nullptr; 11993 11994 // Note: The following rules are largely analoguous to the move 11995 // constructor rules. 11996 11997 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11998 QualType RetType = Context.getLValueReferenceType(ArgType); 11999 ArgType = Context.getRValueReferenceType(ArgType); 12000 12001 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12002 CXXMoveAssignment, 12003 false); 12004 12005 // An implicitly-declared move assignment operator is an inline public 12006 // member of its class. 12007 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12008 SourceLocation ClassLoc = ClassDecl->getLocation(); 12009 DeclarationNameInfo NameInfo(Name, ClassLoc); 12010 CXXMethodDecl *MoveAssignment = 12011 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12012 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12013 /*isInline=*/true, Constexpr, SourceLocation()); 12014 MoveAssignment->setAccess(AS_public); 12015 MoveAssignment->setDefaulted(); 12016 MoveAssignment->setImplicit(); 12017 12018 if (getLangOpts().CUDA) { 12019 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12020 MoveAssignment, 12021 /* ConstRHS */ false, 12022 /* Diagnose */ false); 12023 } 12024 12025 // Build an exception specification pointing back at this member. 12026 FunctionProtoType::ExtProtoInfo EPI = 12027 getImplicitMethodEPI(*this, MoveAssignment); 12028 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12029 12030 // Add the parameter to the operator. 12031 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12032 ClassLoc, ClassLoc, 12033 /*Id=*/nullptr, ArgType, 12034 /*TInfo=*/nullptr, SC_None, 12035 nullptr); 12036 MoveAssignment->setParams(FromParam); 12037 12038 MoveAssignment->setTrivial( 12039 ClassDecl->needsOverloadResolutionForMoveAssignment() 12040 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12041 : ClassDecl->hasTrivialMoveAssignment()); 12042 12043 // Note that we have added this copy-assignment operator. 12044 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 12045 12046 Scope *S = getScopeForContext(ClassDecl); 12047 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12048 12049 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12050 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12051 SetDeclDeleted(MoveAssignment, ClassLoc); 12052 } 12053 12054 if (S) 12055 PushOnScopeChains(MoveAssignment, S, false); 12056 ClassDecl->addDecl(MoveAssignment); 12057 12058 return MoveAssignment; 12059 } 12060 12061 /// Check if we're implicitly defining a move assignment operator for a class 12062 /// with virtual bases. Such a move assignment might move-assign the virtual 12063 /// base multiple times. 12064 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12065 SourceLocation CurrentLocation) { 12066 assert(!Class->isDependentContext() && "should not define dependent move"); 12067 12068 // Only a virtual base could get implicitly move-assigned multiple times. 12069 // Only a non-trivial move assignment can observe this. We only want to 12070 // diagnose if we implicitly define an assignment operator that assigns 12071 // two base classes, both of which move-assign the same virtual base. 12072 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12073 Class->getNumBases() < 2) 12074 return; 12075 12076 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12077 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12078 VBaseMap VBases; 12079 12080 for (auto &BI : Class->bases()) { 12081 Worklist.push_back(&BI); 12082 while (!Worklist.empty()) { 12083 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12084 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12085 12086 // If the base has no non-trivial move assignment operators, 12087 // we don't care about moves from it. 12088 if (!Base->hasNonTrivialMoveAssignment()) 12089 continue; 12090 12091 // If there's nothing virtual here, skip it. 12092 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12093 continue; 12094 12095 // If we're not actually going to call a move assignment for this base, 12096 // or the selected move assignment is trivial, skip it. 12097 Sema::SpecialMemberOverloadResult SMOR = 12098 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12099 /*ConstArg*/false, /*VolatileArg*/false, 12100 /*RValueThis*/true, /*ConstThis*/false, 12101 /*VolatileThis*/false); 12102 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12103 !SMOR.getMethod()->isMoveAssignmentOperator()) 12104 continue; 12105 12106 if (BaseSpec->isVirtual()) { 12107 // We're going to move-assign this virtual base, and its move 12108 // assignment operator is not trivial. If this can happen for 12109 // multiple distinct direct bases of Class, diagnose it. (If it 12110 // only happens in one base, we'll diagnose it when synthesizing 12111 // that base class's move assignment operator.) 12112 CXXBaseSpecifier *&Existing = 12113 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12114 .first->second; 12115 if (Existing && Existing != &BI) { 12116 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12117 << Class << Base; 12118 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 12119 << (Base->getCanonicalDecl() == 12120 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12121 << Base << Existing->getType() << Existing->getSourceRange(); 12122 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 12123 << (Base->getCanonicalDecl() == 12124 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12125 << Base << BI.getType() << BaseSpec->getSourceRange(); 12126 12127 // Only diagnose each vbase once. 12128 Existing = nullptr; 12129 } 12130 } else { 12131 // Only walk over bases that have defaulted move assignment operators. 12132 // We assume that any user-provided move assignment operator handles 12133 // the multiple-moves-of-vbase case itself somehow. 12134 if (!SMOR.getMethod()->isDefaulted()) 12135 continue; 12136 12137 // We're going to move the base classes of Base. Add them to the list. 12138 for (auto &BI : Base->bases()) 12139 Worklist.push_back(&BI); 12140 } 12141 } 12142 } 12143 } 12144 12145 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12146 CXXMethodDecl *MoveAssignOperator) { 12147 assert((MoveAssignOperator->isDefaulted() && 12148 MoveAssignOperator->isOverloadedOperator() && 12149 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12150 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12151 !MoveAssignOperator->isDeleted()) && 12152 "DefineImplicitMoveAssignment called for wrong function"); 12153 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12154 return; 12155 12156 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12157 if (ClassDecl->isInvalidDecl()) { 12158 MoveAssignOperator->setInvalidDecl(); 12159 return; 12160 } 12161 12162 // C++0x [class.copy]p28: 12163 // The implicitly-defined or move assignment operator for a non-union class 12164 // X performs memberwise move assignment of its subobjects. The direct base 12165 // classes of X are assigned first, in the order of their declaration in the 12166 // base-specifier-list, and then the immediate non-static data members of X 12167 // are assigned, in the order in which they were declared in the class 12168 // definition. 12169 12170 // Issue a warning if our implicit move assignment operator will move 12171 // from a virtual base more than once. 12172 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12173 12174 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12175 12176 // The exception specification is needed because we are defining the 12177 // function. 12178 ResolveExceptionSpec(CurrentLocation, 12179 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12180 12181 // Add a context note for diagnostics produced after this point. 12182 Scope.addContextNote(CurrentLocation); 12183 12184 // The statements that form the synthesized function body. 12185 SmallVector<Stmt*, 8> Statements; 12186 12187 // The parameter for the "other" object, which we are move from. 12188 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12189 QualType OtherRefType = Other->getType()-> 12190 getAs<RValueReferenceType>()->getPointeeType(); 12191 assert(!OtherRefType.getQualifiers() && 12192 "Bad argument type of defaulted move assignment"); 12193 12194 // Our location for everything implicitly-generated. 12195 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 12196 ? MoveAssignOperator->getLocEnd() 12197 : MoveAssignOperator->getLocation(); 12198 12199 // Builds a reference to the "other" object. 12200 RefBuilder OtherRef(Other, OtherRefType); 12201 // Cast to rvalue. 12202 MoveCastBuilder MoveOther(OtherRef); 12203 12204 // Builds the "this" pointer. 12205 ThisBuilder This; 12206 12207 // Assign base classes. 12208 bool Invalid = false; 12209 for (auto &Base : ClassDecl->bases()) { 12210 // C++11 [class.copy]p28: 12211 // It is unspecified whether subobjects representing virtual base classes 12212 // are assigned more than once by the implicitly-defined copy assignment 12213 // operator. 12214 // FIXME: Do not assign to a vbase that will be assigned by some other base 12215 // class. For a move-assignment, this can result in the vbase being moved 12216 // multiple times. 12217 12218 // Form the assignment: 12219 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12220 QualType BaseType = Base.getType().getUnqualifiedType(); 12221 if (!BaseType->isRecordType()) { 12222 Invalid = true; 12223 continue; 12224 } 12225 12226 CXXCastPath BasePath; 12227 BasePath.push_back(&Base); 12228 12229 // Construct the "from" expression, which is an implicit cast to the 12230 // appropriately-qualified base type. 12231 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12232 12233 // Dereference "this". 12234 DerefBuilder DerefThis(This); 12235 12236 // Implicitly cast "this" to the appropriately-qualified base type. 12237 CastBuilder To(DerefThis, 12238 Context.getCVRQualifiedType( 12239 BaseType, MoveAssignOperator->getTypeQualifiers()), 12240 VK_LValue, BasePath); 12241 12242 // Build the move. 12243 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12244 To, From, 12245 /*CopyingBaseSubobject=*/true, 12246 /*Copying=*/false); 12247 if (Move.isInvalid()) { 12248 MoveAssignOperator->setInvalidDecl(); 12249 return; 12250 } 12251 12252 // Success! Record the move. 12253 Statements.push_back(Move.getAs<Expr>()); 12254 } 12255 12256 // Assign non-static members. 12257 for (auto *Field : ClassDecl->fields()) { 12258 // FIXME: We should form some kind of AST representation for the implied 12259 // memcpy in a union copy operation. 12260 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12261 continue; 12262 12263 if (Field->isInvalidDecl()) { 12264 Invalid = true; 12265 continue; 12266 } 12267 12268 // Check for members of reference type; we can't move those. 12269 if (Field->getType()->isReferenceType()) { 12270 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12271 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12272 Diag(Field->getLocation(), diag::note_declared_at); 12273 Invalid = true; 12274 continue; 12275 } 12276 12277 // Check for members of const-qualified, non-class type. 12278 QualType BaseType = Context.getBaseElementType(Field->getType()); 12279 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12280 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12281 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12282 Diag(Field->getLocation(), diag::note_declared_at); 12283 Invalid = true; 12284 continue; 12285 } 12286 12287 // Suppress assigning zero-width bitfields. 12288 if (Field->isZeroLengthBitField(Context)) 12289 continue; 12290 12291 QualType FieldType = Field->getType().getNonReferenceType(); 12292 if (FieldType->isIncompleteArrayType()) { 12293 assert(ClassDecl->hasFlexibleArrayMember() && 12294 "Incomplete array type is not valid"); 12295 continue; 12296 } 12297 12298 // Build references to the field in the object we're copying from and to. 12299 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12300 LookupMemberName); 12301 MemberLookup.addDecl(Field); 12302 MemberLookup.resolveKind(); 12303 MemberBuilder From(MoveOther, OtherRefType, 12304 /*IsArrow=*/false, MemberLookup); 12305 MemberBuilder To(This, getCurrentThisType(), 12306 /*IsArrow=*/true, MemberLookup); 12307 12308 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12309 "Member reference with rvalue base must be rvalue except for reference " 12310 "members, which aren't allowed for move assignment."); 12311 12312 // Build the move of this field. 12313 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12314 To, From, 12315 /*CopyingBaseSubobject=*/false, 12316 /*Copying=*/false); 12317 if (Move.isInvalid()) { 12318 MoveAssignOperator->setInvalidDecl(); 12319 return; 12320 } 12321 12322 // Success! Record the copy. 12323 Statements.push_back(Move.getAs<Stmt>()); 12324 } 12325 12326 if (!Invalid) { 12327 // Add a "return *this;" 12328 ExprResult ThisObj = 12329 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12330 12331 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12332 if (Return.isInvalid()) 12333 Invalid = true; 12334 else 12335 Statements.push_back(Return.getAs<Stmt>()); 12336 } 12337 12338 if (Invalid) { 12339 MoveAssignOperator->setInvalidDecl(); 12340 return; 12341 } 12342 12343 StmtResult Body; 12344 { 12345 CompoundScopeRAII CompoundScope(*this); 12346 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12347 /*isStmtExpr=*/false); 12348 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12349 } 12350 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12351 MoveAssignOperator->markUsed(Context); 12352 12353 if (ASTMutationListener *L = getASTMutationListener()) { 12354 L->CompletedImplicitDefinition(MoveAssignOperator); 12355 } 12356 } 12357 12358 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12359 CXXRecordDecl *ClassDecl) { 12360 // C++ [class.copy]p4: 12361 // If the class definition does not explicitly declare a copy 12362 // constructor, one is declared implicitly. 12363 assert(ClassDecl->needsImplicitCopyConstructor()); 12364 12365 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12366 if (DSM.isAlreadyBeingDeclared()) 12367 return nullptr; 12368 12369 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12370 QualType ArgType = ClassType; 12371 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12372 if (Const) 12373 ArgType = ArgType.withConst(); 12374 ArgType = Context.getLValueReferenceType(ArgType); 12375 12376 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12377 CXXCopyConstructor, 12378 Const); 12379 12380 DeclarationName Name 12381 = Context.DeclarationNames.getCXXConstructorName( 12382 Context.getCanonicalType(ClassType)); 12383 SourceLocation ClassLoc = ClassDecl->getLocation(); 12384 DeclarationNameInfo NameInfo(Name, ClassLoc); 12385 12386 // An implicitly-declared copy constructor is an inline public 12387 // member of its class. 12388 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12389 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12390 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12391 Constexpr); 12392 CopyConstructor->setAccess(AS_public); 12393 CopyConstructor->setDefaulted(); 12394 12395 if (getLangOpts().CUDA) { 12396 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12397 CopyConstructor, 12398 /* ConstRHS */ Const, 12399 /* Diagnose */ false); 12400 } 12401 12402 // Build an exception specification pointing back at this member. 12403 FunctionProtoType::ExtProtoInfo EPI = 12404 getImplicitMethodEPI(*this, CopyConstructor); 12405 CopyConstructor->setType( 12406 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12407 12408 // Add the parameter to the constructor. 12409 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12410 ClassLoc, ClassLoc, 12411 /*IdentifierInfo=*/nullptr, 12412 ArgType, /*TInfo=*/nullptr, 12413 SC_None, nullptr); 12414 CopyConstructor->setParams(FromParam); 12415 12416 CopyConstructor->setTrivial( 12417 ClassDecl->needsOverloadResolutionForCopyConstructor() 12418 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12419 : ClassDecl->hasTrivialCopyConstructor()); 12420 12421 CopyConstructor->setTrivialForCall( 12422 ClassDecl->hasAttr<TrivialABIAttr>() || 12423 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12424 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12425 TAH_ConsiderTrivialABI) 12426 : ClassDecl->hasTrivialCopyConstructorForCall())); 12427 12428 // Note that we have declared this constructor. 12429 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12430 12431 Scope *S = getScopeForContext(ClassDecl); 12432 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12433 12434 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12435 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12436 SetDeclDeleted(CopyConstructor, ClassLoc); 12437 } 12438 12439 if (S) 12440 PushOnScopeChains(CopyConstructor, S, false); 12441 ClassDecl->addDecl(CopyConstructor); 12442 12443 return CopyConstructor; 12444 } 12445 12446 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12447 CXXConstructorDecl *CopyConstructor) { 12448 assert((CopyConstructor->isDefaulted() && 12449 CopyConstructor->isCopyConstructor() && 12450 !CopyConstructor->doesThisDeclarationHaveABody() && 12451 !CopyConstructor->isDeleted()) && 12452 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12453 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12454 return; 12455 12456 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12457 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12458 12459 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12460 12461 // The exception specification is needed because we are defining the 12462 // function. 12463 ResolveExceptionSpec(CurrentLocation, 12464 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12465 MarkVTableUsed(CurrentLocation, ClassDecl); 12466 12467 // Add a context note for diagnostics produced after this point. 12468 Scope.addContextNote(CurrentLocation); 12469 12470 // C++11 [class.copy]p7: 12471 // The [definition of an implicitly declared copy constructor] is 12472 // deprecated if the class has a user-declared copy assignment operator 12473 // or a user-declared destructor. 12474 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12475 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12476 12477 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12478 CopyConstructor->setInvalidDecl(); 12479 } else { 12480 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12481 ? CopyConstructor->getLocEnd() 12482 : CopyConstructor->getLocation(); 12483 Sema::CompoundScopeRAII CompoundScope(*this); 12484 CopyConstructor->setBody( 12485 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12486 CopyConstructor->markUsed(Context); 12487 } 12488 12489 if (ASTMutationListener *L = getASTMutationListener()) { 12490 L->CompletedImplicitDefinition(CopyConstructor); 12491 } 12492 } 12493 12494 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12495 CXXRecordDecl *ClassDecl) { 12496 assert(ClassDecl->needsImplicitMoveConstructor()); 12497 12498 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12499 if (DSM.isAlreadyBeingDeclared()) 12500 return nullptr; 12501 12502 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12503 QualType ArgType = Context.getRValueReferenceType(ClassType); 12504 12505 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12506 CXXMoveConstructor, 12507 false); 12508 12509 DeclarationName Name 12510 = Context.DeclarationNames.getCXXConstructorName( 12511 Context.getCanonicalType(ClassType)); 12512 SourceLocation ClassLoc = ClassDecl->getLocation(); 12513 DeclarationNameInfo NameInfo(Name, ClassLoc); 12514 12515 // C++11 [class.copy]p11: 12516 // An implicitly-declared copy/move constructor is an inline public 12517 // member of its class. 12518 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12519 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12520 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12521 Constexpr); 12522 MoveConstructor->setAccess(AS_public); 12523 MoveConstructor->setDefaulted(); 12524 12525 if (getLangOpts().CUDA) { 12526 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12527 MoveConstructor, 12528 /* ConstRHS */ false, 12529 /* Diagnose */ false); 12530 } 12531 12532 // Build an exception specification pointing back at this member. 12533 FunctionProtoType::ExtProtoInfo EPI = 12534 getImplicitMethodEPI(*this, MoveConstructor); 12535 MoveConstructor->setType( 12536 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12537 12538 // Add the parameter to the constructor. 12539 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12540 ClassLoc, ClassLoc, 12541 /*IdentifierInfo=*/nullptr, 12542 ArgType, /*TInfo=*/nullptr, 12543 SC_None, nullptr); 12544 MoveConstructor->setParams(FromParam); 12545 12546 MoveConstructor->setTrivial( 12547 ClassDecl->needsOverloadResolutionForMoveConstructor() 12548 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12549 : ClassDecl->hasTrivialMoveConstructor()); 12550 12551 MoveConstructor->setTrivialForCall( 12552 ClassDecl->hasAttr<TrivialABIAttr>() || 12553 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12554 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12555 TAH_ConsiderTrivialABI) 12556 : ClassDecl->hasTrivialMoveConstructorForCall())); 12557 12558 // Note that we have declared this constructor. 12559 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12560 12561 Scope *S = getScopeForContext(ClassDecl); 12562 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12563 12564 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12565 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12566 SetDeclDeleted(MoveConstructor, ClassLoc); 12567 } 12568 12569 if (S) 12570 PushOnScopeChains(MoveConstructor, S, false); 12571 ClassDecl->addDecl(MoveConstructor); 12572 12573 return MoveConstructor; 12574 } 12575 12576 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12577 CXXConstructorDecl *MoveConstructor) { 12578 assert((MoveConstructor->isDefaulted() && 12579 MoveConstructor->isMoveConstructor() && 12580 !MoveConstructor->doesThisDeclarationHaveABody() && 12581 !MoveConstructor->isDeleted()) && 12582 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12583 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12584 return; 12585 12586 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12587 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12588 12589 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12590 12591 // The exception specification is needed because we are defining the 12592 // function. 12593 ResolveExceptionSpec(CurrentLocation, 12594 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12595 MarkVTableUsed(CurrentLocation, ClassDecl); 12596 12597 // Add a context note for diagnostics produced after this point. 12598 Scope.addContextNote(CurrentLocation); 12599 12600 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12601 MoveConstructor->setInvalidDecl(); 12602 } else { 12603 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12604 ? MoveConstructor->getLocEnd() 12605 : MoveConstructor->getLocation(); 12606 Sema::CompoundScopeRAII CompoundScope(*this); 12607 MoveConstructor->setBody(ActOnCompoundStmt( 12608 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12609 MoveConstructor->markUsed(Context); 12610 } 12611 12612 if (ASTMutationListener *L = getASTMutationListener()) { 12613 L->CompletedImplicitDefinition(MoveConstructor); 12614 } 12615 } 12616 12617 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12618 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12619 } 12620 12621 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12622 SourceLocation CurrentLocation, 12623 CXXConversionDecl *Conv) { 12624 SynthesizedFunctionScope Scope(*this, Conv); 12625 assert(!Conv->getReturnType()->isUndeducedType()); 12626 12627 CXXRecordDecl *Lambda = Conv->getParent(); 12628 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12629 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12630 12631 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12632 CallOp = InstantiateFunctionDeclaration( 12633 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12634 if (!CallOp) 12635 return; 12636 12637 Invoker = InstantiateFunctionDeclaration( 12638 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12639 if (!Invoker) 12640 return; 12641 } 12642 12643 if (CallOp->isInvalidDecl()) 12644 return; 12645 12646 // Mark the call operator referenced (and add to pending instantiations 12647 // if necessary). 12648 // For both the conversion and static-invoker template specializations 12649 // we construct their body's in this function, so no need to add them 12650 // to the PendingInstantiations. 12651 MarkFunctionReferenced(CurrentLocation, CallOp); 12652 12653 // Fill in the __invoke function with a dummy implementation. IR generation 12654 // will fill in the actual details. Update its type in case it contained 12655 // an 'auto'. 12656 Invoker->markUsed(Context); 12657 Invoker->setReferenced(); 12658 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12659 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12660 12661 // Construct the body of the conversion function { return __invoke; }. 12662 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12663 VK_LValue, Conv->getLocation()).get(); 12664 assert(FunctionRef && "Can't refer to __invoke function?"); 12665 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12666 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12667 Conv->getLocation())); 12668 Conv->markUsed(Context); 12669 Conv->setReferenced(); 12670 12671 if (ASTMutationListener *L = getASTMutationListener()) { 12672 L->CompletedImplicitDefinition(Conv); 12673 L->CompletedImplicitDefinition(Invoker); 12674 } 12675 } 12676 12677 12678 12679 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12680 SourceLocation CurrentLocation, 12681 CXXConversionDecl *Conv) 12682 { 12683 assert(!Conv->getParent()->isGenericLambda()); 12684 12685 SynthesizedFunctionScope Scope(*this, Conv); 12686 12687 // Copy-initialize the lambda object as needed to capture it. 12688 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12689 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12690 12691 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12692 Conv->getLocation(), 12693 Conv, DerefThis); 12694 12695 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12696 // behavior. Note that only the general conversion function does this 12697 // (since it's unusable otherwise); in the case where we inline the 12698 // block literal, it has block literal lifetime semantics. 12699 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12700 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12701 CK_CopyAndAutoreleaseBlockObject, 12702 BuildBlock.get(), nullptr, VK_RValue); 12703 12704 if (BuildBlock.isInvalid()) { 12705 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12706 Conv->setInvalidDecl(); 12707 return; 12708 } 12709 12710 // Create the return statement that returns the block from the conversion 12711 // function. 12712 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12713 if (Return.isInvalid()) { 12714 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12715 Conv->setInvalidDecl(); 12716 return; 12717 } 12718 12719 // Set the body of the conversion function. 12720 Stmt *ReturnS = Return.get(); 12721 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12722 Conv->getLocation())); 12723 Conv->markUsed(Context); 12724 12725 // We're done; notify the mutation listener, if any. 12726 if (ASTMutationListener *L = getASTMutationListener()) { 12727 L->CompletedImplicitDefinition(Conv); 12728 } 12729 } 12730 12731 /// Determine whether the given list arguments contains exactly one 12732 /// "real" (non-default) argument. 12733 static bool hasOneRealArgument(MultiExprArg Args) { 12734 switch (Args.size()) { 12735 case 0: 12736 return false; 12737 12738 default: 12739 if (!Args[1]->isDefaultArgument()) 12740 return false; 12741 12742 LLVM_FALLTHROUGH; 12743 case 1: 12744 return !Args[0]->isDefaultArgument(); 12745 } 12746 12747 return false; 12748 } 12749 12750 ExprResult 12751 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12752 NamedDecl *FoundDecl, 12753 CXXConstructorDecl *Constructor, 12754 MultiExprArg ExprArgs, 12755 bool HadMultipleCandidates, 12756 bool IsListInitialization, 12757 bool IsStdInitListInitialization, 12758 bool RequiresZeroInit, 12759 unsigned ConstructKind, 12760 SourceRange ParenRange) { 12761 bool Elidable = false; 12762 12763 // C++0x [class.copy]p34: 12764 // When certain criteria are met, an implementation is allowed to 12765 // omit the copy/move construction of a class object, even if the 12766 // copy/move constructor and/or destructor for the object have 12767 // side effects. [...] 12768 // - when a temporary class object that has not been bound to a 12769 // reference (12.2) would be copied/moved to a class object 12770 // with the same cv-unqualified type, the copy/move operation 12771 // can be omitted by constructing the temporary object 12772 // directly into the target of the omitted copy/move 12773 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12774 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12775 Expr *SubExpr = ExprArgs[0]; 12776 Elidable = SubExpr->isTemporaryObject( 12777 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12778 } 12779 12780 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12781 FoundDecl, Constructor, 12782 Elidable, ExprArgs, HadMultipleCandidates, 12783 IsListInitialization, 12784 IsStdInitListInitialization, RequiresZeroInit, 12785 ConstructKind, ParenRange); 12786 } 12787 12788 ExprResult 12789 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12790 NamedDecl *FoundDecl, 12791 CXXConstructorDecl *Constructor, 12792 bool Elidable, 12793 MultiExprArg ExprArgs, 12794 bool HadMultipleCandidates, 12795 bool IsListInitialization, 12796 bool IsStdInitListInitialization, 12797 bool RequiresZeroInit, 12798 unsigned ConstructKind, 12799 SourceRange ParenRange) { 12800 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12801 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12802 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12803 return ExprError(); 12804 } 12805 12806 return BuildCXXConstructExpr( 12807 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12808 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12809 RequiresZeroInit, ConstructKind, ParenRange); 12810 } 12811 12812 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12813 /// including handling of its default argument expressions. 12814 ExprResult 12815 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12816 CXXConstructorDecl *Constructor, 12817 bool Elidable, 12818 MultiExprArg ExprArgs, 12819 bool HadMultipleCandidates, 12820 bool IsListInitialization, 12821 bool IsStdInitListInitialization, 12822 bool RequiresZeroInit, 12823 unsigned ConstructKind, 12824 SourceRange ParenRange) { 12825 assert(declaresSameEntity( 12826 Constructor->getParent(), 12827 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12828 "given constructor for wrong type"); 12829 MarkFunctionReferenced(ConstructLoc, Constructor); 12830 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12831 return ExprError(); 12832 12833 return CXXConstructExpr::Create( 12834 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12835 ExprArgs, HadMultipleCandidates, IsListInitialization, 12836 IsStdInitListInitialization, RequiresZeroInit, 12837 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12838 ParenRange); 12839 } 12840 12841 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12842 assert(Field->hasInClassInitializer()); 12843 12844 // If we already have the in-class initializer nothing needs to be done. 12845 if (Field->getInClassInitializer()) 12846 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12847 12848 // If we might have already tried and failed to instantiate, don't try again. 12849 if (Field->isInvalidDecl()) 12850 return ExprError(); 12851 12852 // Maybe we haven't instantiated the in-class initializer. Go check the 12853 // pattern FieldDecl to see if it has one. 12854 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12855 12856 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12857 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12858 DeclContext::lookup_result Lookup = 12859 ClassPattern->lookup(Field->getDeclName()); 12860 12861 // Lookup can return at most two results: the pattern for the field, or the 12862 // injected class name of the parent record. No other member can have the 12863 // same name as the field. 12864 // In modules mode, lookup can return multiple results (coming from 12865 // different modules). 12866 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12867 "more than two lookup results for field name"); 12868 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12869 if (!Pattern) { 12870 assert(isa<CXXRecordDecl>(Lookup[0]) && 12871 "cannot have other non-field member with same name"); 12872 for (auto L : Lookup) 12873 if (isa<FieldDecl>(L)) { 12874 Pattern = cast<FieldDecl>(L); 12875 break; 12876 } 12877 assert(Pattern && "We must have set the Pattern!"); 12878 } 12879 12880 if (!Pattern->hasInClassInitializer() || 12881 InstantiateInClassInitializer(Loc, Field, Pattern, 12882 getTemplateInstantiationArgs(Field))) { 12883 // Don't diagnose this again. 12884 Field->setInvalidDecl(); 12885 return ExprError(); 12886 } 12887 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12888 } 12889 12890 // DR1351: 12891 // If the brace-or-equal-initializer of a non-static data member 12892 // invokes a defaulted default constructor of its class or of an 12893 // enclosing class in a potentially evaluated subexpression, the 12894 // program is ill-formed. 12895 // 12896 // This resolution is unworkable: the exception specification of the 12897 // default constructor can be needed in an unevaluated context, in 12898 // particular, in the operand of a noexcept-expression, and we can be 12899 // unable to compute an exception specification for an enclosed class. 12900 // 12901 // Any attempt to resolve the exception specification of a defaulted default 12902 // constructor before the initializer is lexically complete will ultimately 12903 // come here at which point we can diagnose it. 12904 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12905 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12906 << OutermostClass << Field; 12907 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12908 // Recover by marking the field invalid, unless we're in a SFINAE context. 12909 if (!isSFINAEContext()) 12910 Field->setInvalidDecl(); 12911 return ExprError(); 12912 } 12913 12914 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12915 if (VD->isInvalidDecl()) return; 12916 12917 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12918 if (ClassDecl->isInvalidDecl()) return; 12919 if (ClassDecl->hasIrrelevantDestructor()) return; 12920 if (ClassDecl->isDependentContext()) return; 12921 12922 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12923 MarkFunctionReferenced(VD->getLocation(), Destructor); 12924 CheckDestructorAccess(VD->getLocation(), Destructor, 12925 PDiag(diag::err_access_dtor_var) 12926 << VD->getDeclName() 12927 << VD->getType()); 12928 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12929 12930 if (Destructor->isTrivial()) return; 12931 if (!VD->hasGlobalStorage()) return; 12932 12933 // Emit warning for non-trivial dtor in global scope (a real global, 12934 // class-static, function-static). 12935 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12936 12937 // TODO: this should be re-enabled for static locals by !CXAAtExit 12938 if (!VD->isStaticLocal()) 12939 Diag(VD->getLocation(), diag::warn_global_destructor); 12940 } 12941 12942 /// Given a constructor and the set of arguments provided for the 12943 /// constructor, convert the arguments and add any required default arguments 12944 /// to form a proper call to this constructor. 12945 /// 12946 /// \returns true if an error occurred, false otherwise. 12947 bool 12948 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12949 MultiExprArg ArgsPtr, 12950 SourceLocation Loc, 12951 SmallVectorImpl<Expr*> &ConvertedArgs, 12952 bool AllowExplicit, 12953 bool IsListInitialization) { 12954 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12955 unsigned NumArgs = ArgsPtr.size(); 12956 Expr **Args = ArgsPtr.data(); 12957 12958 const FunctionProtoType *Proto 12959 = Constructor->getType()->getAs<FunctionProtoType>(); 12960 assert(Proto && "Constructor without a prototype?"); 12961 unsigned NumParams = Proto->getNumParams(); 12962 12963 // If too few arguments are available, we'll fill in the rest with defaults. 12964 if (NumArgs < NumParams) 12965 ConvertedArgs.reserve(NumParams); 12966 else 12967 ConvertedArgs.reserve(NumArgs); 12968 12969 VariadicCallType CallType = 12970 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12971 SmallVector<Expr *, 8> AllArgs; 12972 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12973 Proto, 0, 12974 llvm::makeArrayRef(Args, NumArgs), 12975 AllArgs, 12976 CallType, AllowExplicit, 12977 IsListInitialization); 12978 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12979 12980 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12981 12982 CheckConstructorCall(Constructor, 12983 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12984 Proto, Loc); 12985 12986 return Invalid; 12987 } 12988 12989 static inline bool 12990 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12991 const FunctionDecl *FnDecl) { 12992 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12993 if (isa<NamespaceDecl>(DC)) { 12994 return SemaRef.Diag(FnDecl->getLocation(), 12995 diag::err_operator_new_delete_declared_in_namespace) 12996 << FnDecl->getDeclName(); 12997 } 12998 12999 if (isa<TranslationUnitDecl>(DC) && 13000 FnDecl->getStorageClass() == SC_Static) { 13001 return SemaRef.Diag(FnDecl->getLocation(), 13002 diag::err_operator_new_delete_declared_static) 13003 << FnDecl->getDeclName(); 13004 } 13005 13006 return false; 13007 } 13008 13009 static QualType 13010 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13011 QualType QTy = PtrTy->getPointeeType(); 13012 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13013 return SemaRef.Context.getPointerType(QTy); 13014 } 13015 13016 static inline bool 13017 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13018 CanQualType ExpectedResultType, 13019 CanQualType ExpectedFirstParamType, 13020 unsigned DependentParamTypeDiag, 13021 unsigned InvalidParamTypeDiag) { 13022 QualType ResultType = 13023 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13024 13025 // Check that the result type is not dependent. 13026 if (ResultType->isDependentType()) 13027 return SemaRef.Diag(FnDecl->getLocation(), 13028 diag::err_operator_new_delete_dependent_result_type) 13029 << FnDecl->getDeclName() << ExpectedResultType; 13030 13031 // OpenCL C++: the operator is valid on any address space. 13032 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13033 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13034 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13035 } 13036 } 13037 13038 // Check that the result type is what we expect. 13039 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13040 return SemaRef.Diag(FnDecl->getLocation(), 13041 diag::err_operator_new_delete_invalid_result_type) 13042 << FnDecl->getDeclName() << ExpectedResultType; 13043 13044 // A function template must have at least 2 parameters. 13045 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13046 return SemaRef.Diag(FnDecl->getLocation(), 13047 diag::err_operator_new_delete_template_too_few_parameters) 13048 << FnDecl->getDeclName(); 13049 13050 // The function decl must have at least 1 parameter. 13051 if (FnDecl->getNumParams() == 0) 13052 return SemaRef.Diag(FnDecl->getLocation(), 13053 diag::err_operator_new_delete_too_few_parameters) 13054 << FnDecl->getDeclName(); 13055 13056 // Check the first parameter type is not dependent. 13057 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13058 if (FirstParamType->isDependentType()) 13059 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13060 << FnDecl->getDeclName() << ExpectedFirstParamType; 13061 13062 // Check that the first parameter type is what we expect. 13063 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13064 // OpenCL C++: the operator is valid on any address space. 13065 if (auto *PtrTy = 13066 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13067 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13068 } 13069 } 13070 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13071 ExpectedFirstParamType) 13072 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13073 << FnDecl->getDeclName() << ExpectedFirstParamType; 13074 13075 return false; 13076 } 13077 13078 static bool 13079 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13080 // C++ [basic.stc.dynamic.allocation]p1: 13081 // A program is ill-formed if an allocation function is declared in a 13082 // namespace scope other than global scope or declared static in global 13083 // scope. 13084 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13085 return true; 13086 13087 CanQualType SizeTy = 13088 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13089 13090 // C++ [basic.stc.dynamic.allocation]p1: 13091 // The return type shall be void*. The first parameter shall have type 13092 // std::size_t. 13093 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13094 SizeTy, 13095 diag::err_operator_new_dependent_param_type, 13096 diag::err_operator_new_param_type)) 13097 return true; 13098 13099 // C++ [basic.stc.dynamic.allocation]p1: 13100 // The first parameter shall not have an associated default argument. 13101 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13102 return SemaRef.Diag(FnDecl->getLocation(), 13103 diag::err_operator_new_default_arg) 13104 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13105 13106 return false; 13107 } 13108 13109 static bool 13110 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13111 // C++ [basic.stc.dynamic.deallocation]p1: 13112 // A program is ill-formed if deallocation functions are declared in a 13113 // namespace scope other than global scope or declared static in global 13114 // scope. 13115 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13116 return true; 13117 13118 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13119 13120 // C++ P0722: 13121 // Within a class C, the first parameter of a destroying operator delete 13122 // shall be of type C *. The first parameter of any other deallocation 13123 // function shall be of type void *. 13124 CanQualType ExpectedFirstParamType = 13125 MD && MD->isDestroyingOperatorDelete() 13126 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13127 SemaRef.Context.getRecordType(MD->getParent()))) 13128 : SemaRef.Context.VoidPtrTy; 13129 13130 // C++ [basic.stc.dynamic.deallocation]p2: 13131 // Each deallocation function shall return void 13132 if (CheckOperatorNewDeleteTypes( 13133 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13134 diag::err_operator_delete_dependent_param_type, 13135 diag::err_operator_delete_param_type)) 13136 return true; 13137 13138 // C++ P0722: 13139 // A destroying operator delete shall be a usual deallocation function. 13140 if (MD && !MD->getParent()->isDependentContext() && 13141 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 13142 SemaRef.Diag(MD->getLocation(), 13143 diag::err_destroying_operator_delete_not_usual); 13144 return true; 13145 } 13146 13147 return false; 13148 } 13149 13150 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13151 /// of this overloaded operator is well-formed. If so, returns false; 13152 /// otherwise, emits appropriate diagnostics and returns true. 13153 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13154 assert(FnDecl && FnDecl->isOverloadedOperator() && 13155 "Expected an overloaded operator declaration"); 13156 13157 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13158 13159 // C++ [over.oper]p5: 13160 // The allocation and deallocation functions, operator new, 13161 // operator new[], operator delete and operator delete[], are 13162 // described completely in 3.7.3. The attributes and restrictions 13163 // found in the rest of this subclause do not apply to them unless 13164 // explicitly stated in 3.7.3. 13165 if (Op == OO_Delete || Op == OO_Array_Delete) 13166 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13167 13168 if (Op == OO_New || Op == OO_Array_New) 13169 return CheckOperatorNewDeclaration(*this, FnDecl); 13170 13171 // C++ [over.oper]p6: 13172 // An operator function shall either be a non-static member 13173 // function or be a non-member function and have at least one 13174 // parameter whose type is a class, a reference to a class, an 13175 // enumeration, or a reference to an enumeration. 13176 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13177 if (MethodDecl->isStatic()) 13178 return Diag(FnDecl->getLocation(), 13179 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13180 } else { 13181 bool ClassOrEnumParam = false; 13182 for (auto Param : FnDecl->parameters()) { 13183 QualType ParamType = Param->getType().getNonReferenceType(); 13184 if (ParamType->isDependentType() || ParamType->isRecordType() || 13185 ParamType->isEnumeralType()) { 13186 ClassOrEnumParam = true; 13187 break; 13188 } 13189 } 13190 13191 if (!ClassOrEnumParam) 13192 return Diag(FnDecl->getLocation(), 13193 diag::err_operator_overload_needs_class_or_enum) 13194 << FnDecl->getDeclName(); 13195 } 13196 13197 // C++ [over.oper]p8: 13198 // An operator function cannot have default arguments (8.3.6), 13199 // except where explicitly stated below. 13200 // 13201 // Only the function-call operator allows default arguments 13202 // (C++ [over.call]p1). 13203 if (Op != OO_Call) { 13204 for (auto Param : FnDecl->parameters()) { 13205 if (Param->hasDefaultArg()) 13206 return Diag(Param->getLocation(), 13207 diag::err_operator_overload_default_arg) 13208 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13209 } 13210 } 13211 13212 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13213 { false, false, false } 13214 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13215 , { Unary, Binary, MemberOnly } 13216 #include "clang/Basic/OperatorKinds.def" 13217 }; 13218 13219 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13220 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13221 bool MustBeMemberOperator = OperatorUses[Op][2]; 13222 13223 // C++ [over.oper]p8: 13224 // [...] Operator functions cannot have more or fewer parameters 13225 // than the number required for the corresponding operator, as 13226 // described in the rest of this subclause. 13227 unsigned NumParams = FnDecl->getNumParams() 13228 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13229 if (Op != OO_Call && 13230 ((NumParams == 1 && !CanBeUnaryOperator) || 13231 (NumParams == 2 && !CanBeBinaryOperator) || 13232 (NumParams < 1) || (NumParams > 2))) { 13233 // We have the wrong number of parameters. 13234 unsigned ErrorKind; 13235 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13236 ErrorKind = 2; // 2 -> unary or binary. 13237 } else if (CanBeUnaryOperator) { 13238 ErrorKind = 0; // 0 -> unary 13239 } else { 13240 assert(CanBeBinaryOperator && 13241 "All non-call overloaded operators are unary or binary!"); 13242 ErrorKind = 1; // 1 -> binary 13243 } 13244 13245 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13246 << FnDecl->getDeclName() << NumParams << ErrorKind; 13247 } 13248 13249 // Overloaded operators other than operator() cannot be variadic. 13250 if (Op != OO_Call && 13251 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13252 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13253 << FnDecl->getDeclName(); 13254 } 13255 13256 // Some operators must be non-static member functions. 13257 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13258 return Diag(FnDecl->getLocation(), 13259 diag::err_operator_overload_must_be_member) 13260 << FnDecl->getDeclName(); 13261 } 13262 13263 // C++ [over.inc]p1: 13264 // The user-defined function called operator++ implements the 13265 // prefix and postfix ++ operator. If this function is a member 13266 // function with no parameters, or a non-member function with one 13267 // parameter of class or enumeration type, it defines the prefix 13268 // increment operator ++ for objects of that type. If the function 13269 // is a member function with one parameter (which shall be of type 13270 // int) or a non-member function with two parameters (the second 13271 // of which shall be of type int), it defines the postfix 13272 // increment operator ++ for objects of that type. 13273 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13274 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13275 QualType ParamType = LastParam->getType(); 13276 13277 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13278 !ParamType->isDependentType()) 13279 return Diag(LastParam->getLocation(), 13280 diag::err_operator_overload_post_incdec_must_be_int) 13281 << LastParam->getType() << (Op == OO_MinusMinus); 13282 } 13283 13284 return false; 13285 } 13286 13287 static bool 13288 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13289 FunctionTemplateDecl *TpDecl) { 13290 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13291 13292 // Must have one or two template parameters. 13293 if (TemplateParams->size() == 1) { 13294 NonTypeTemplateParmDecl *PmDecl = 13295 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13296 13297 // The template parameter must be a char parameter pack. 13298 if (PmDecl && PmDecl->isTemplateParameterPack() && 13299 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13300 return false; 13301 13302 } else if (TemplateParams->size() == 2) { 13303 TemplateTypeParmDecl *PmType = 13304 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13305 NonTypeTemplateParmDecl *PmArgs = 13306 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13307 13308 // The second template parameter must be a parameter pack with the 13309 // first template parameter as its type. 13310 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13311 PmArgs->isTemplateParameterPack()) { 13312 const TemplateTypeParmType *TArgs = 13313 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13314 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13315 TArgs->getIndex() == PmType->getIndex()) { 13316 if (!SemaRef.inTemplateInstantiation()) 13317 SemaRef.Diag(TpDecl->getLocation(), 13318 diag::ext_string_literal_operator_template); 13319 return false; 13320 } 13321 } 13322 } 13323 13324 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13325 diag::err_literal_operator_template) 13326 << TpDecl->getTemplateParameters()->getSourceRange(); 13327 return true; 13328 } 13329 13330 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13331 /// of this literal operator function is well-formed. If so, returns 13332 /// false; otherwise, emits appropriate diagnostics and returns true. 13333 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13334 if (isa<CXXMethodDecl>(FnDecl)) { 13335 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13336 << FnDecl->getDeclName(); 13337 return true; 13338 } 13339 13340 if (FnDecl->isExternC()) { 13341 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13342 if (const LinkageSpecDecl *LSD = 13343 FnDecl->getDeclContext()->getExternCContext()) 13344 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13345 return true; 13346 } 13347 13348 // This might be the definition of a literal operator template. 13349 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13350 13351 // This might be a specialization of a literal operator template. 13352 if (!TpDecl) 13353 TpDecl = FnDecl->getPrimaryTemplate(); 13354 13355 // template <char...> type operator "" name() and 13356 // template <class T, T...> type operator "" name() are the only valid 13357 // template signatures, and the only valid signatures with no parameters. 13358 if (TpDecl) { 13359 if (FnDecl->param_size() != 0) { 13360 Diag(FnDecl->getLocation(), 13361 diag::err_literal_operator_template_with_params); 13362 return true; 13363 } 13364 13365 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13366 return true; 13367 13368 } else if (FnDecl->param_size() == 1) { 13369 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13370 13371 QualType ParamType = Param->getType().getUnqualifiedType(); 13372 13373 // Only unsigned long long int, long double, any character type, and const 13374 // char * are allowed as the only parameters. 13375 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13376 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13377 Context.hasSameType(ParamType, Context.CharTy) || 13378 Context.hasSameType(ParamType, Context.WideCharTy) || 13379 Context.hasSameType(ParamType, Context.Char8Ty) || 13380 Context.hasSameType(ParamType, Context.Char16Ty) || 13381 Context.hasSameType(ParamType, Context.Char32Ty)) { 13382 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13383 QualType InnerType = Ptr->getPointeeType(); 13384 13385 // Pointer parameter must be a const char *. 13386 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13387 Context.CharTy) && 13388 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13389 Diag(Param->getSourceRange().getBegin(), 13390 diag::err_literal_operator_param) 13391 << ParamType << "'const char *'" << Param->getSourceRange(); 13392 return true; 13393 } 13394 13395 } else if (ParamType->isRealFloatingType()) { 13396 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13397 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13398 return true; 13399 13400 } else if (ParamType->isIntegerType()) { 13401 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13402 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13403 return true; 13404 13405 } else { 13406 Diag(Param->getSourceRange().getBegin(), 13407 diag::err_literal_operator_invalid_param) 13408 << ParamType << Param->getSourceRange(); 13409 return true; 13410 } 13411 13412 } else if (FnDecl->param_size() == 2) { 13413 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13414 13415 // First, verify that the first parameter is correct. 13416 13417 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13418 13419 // Two parameter function must have a pointer to const as a 13420 // first parameter; let's strip those qualifiers. 13421 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13422 13423 if (!PT) { 13424 Diag((*Param)->getSourceRange().getBegin(), 13425 diag::err_literal_operator_param) 13426 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13427 return true; 13428 } 13429 13430 QualType PointeeType = PT->getPointeeType(); 13431 // First parameter must be const 13432 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13433 Diag((*Param)->getSourceRange().getBegin(), 13434 diag::err_literal_operator_param) 13435 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13436 return true; 13437 } 13438 13439 QualType InnerType = PointeeType.getUnqualifiedType(); 13440 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13441 // const char32_t* are allowed as the first parameter to a two-parameter 13442 // function 13443 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13444 Context.hasSameType(InnerType, Context.WideCharTy) || 13445 Context.hasSameType(InnerType, Context.Char8Ty) || 13446 Context.hasSameType(InnerType, Context.Char16Ty) || 13447 Context.hasSameType(InnerType, Context.Char32Ty))) { 13448 Diag((*Param)->getSourceRange().getBegin(), 13449 diag::err_literal_operator_param) 13450 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13451 return true; 13452 } 13453 13454 // Move on to the second and final parameter. 13455 ++Param; 13456 13457 // The second parameter must be a std::size_t. 13458 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13459 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13460 Diag((*Param)->getSourceRange().getBegin(), 13461 diag::err_literal_operator_param) 13462 << SecondParamType << Context.getSizeType() 13463 << (*Param)->getSourceRange(); 13464 return true; 13465 } 13466 } else { 13467 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13468 return true; 13469 } 13470 13471 // Parameters are good. 13472 13473 // A parameter-declaration-clause containing a default argument is not 13474 // equivalent to any of the permitted forms. 13475 for (auto Param : FnDecl->parameters()) { 13476 if (Param->hasDefaultArg()) { 13477 Diag(Param->getDefaultArgRange().getBegin(), 13478 diag::err_literal_operator_default_argument) 13479 << Param->getDefaultArgRange(); 13480 break; 13481 } 13482 } 13483 13484 StringRef LiteralName 13485 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13486 if (LiteralName[0] != '_' && 13487 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13488 // C++11 [usrlit.suffix]p1: 13489 // Literal suffix identifiers that do not start with an underscore 13490 // are reserved for future standardization. 13491 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13492 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13493 } 13494 13495 return false; 13496 } 13497 13498 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13499 /// linkage specification, including the language and (if present) 13500 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13501 /// language string literal. LBraceLoc, if valid, provides the location of 13502 /// the '{' brace. Otherwise, this linkage specification does not 13503 /// have any braces. 13504 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13505 Expr *LangStr, 13506 SourceLocation LBraceLoc) { 13507 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13508 if (!Lit->isAscii()) { 13509 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13510 << LangStr->getSourceRange(); 13511 return nullptr; 13512 } 13513 13514 StringRef Lang = Lit->getString(); 13515 LinkageSpecDecl::LanguageIDs Language; 13516 if (Lang == "C") 13517 Language = LinkageSpecDecl::lang_c; 13518 else if (Lang == "C++") 13519 Language = LinkageSpecDecl::lang_cxx; 13520 else { 13521 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13522 << LangStr->getSourceRange(); 13523 return nullptr; 13524 } 13525 13526 // FIXME: Add all the various semantics of linkage specifications 13527 13528 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13529 LangStr->getExprLoc(), Language, 13530 LBraceLoc.isValid()); 13531 CurContext->addDecl(D); 13532 PushDeclContext(S, D); 13533 return D; 13534 } 13535 13536 /// ActOnFinishLinkageSpecification - Complete the definition of 13537 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13538 /// valid, it's the position of the closing '}' brace in a linkage 13539 /// specification that uses braces. 13540 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13541 Decl *LinkageSpec, 13542 SourceLocation RBraceLoc) { 13543 if (RBraceLoc.isValid()) { 13544 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13545 LSDecl->setRBraceLoc(RBraceLoc); 13546 } 13547 PopDeclContext(); 13548 return LinkageSpec; 13549 } 13550 13551 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13552 AttributeList *AttrList, 13553 SourceLocation SemiLoc) { 13554 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13555 // Attribute declarations appertain to empty declaration so we handle 13556 // them here. 13557 if (AttrList) 13558 ProcessDeclAttributeList(S, ED, AttrList); 13559 13560 CurContext->addDecl(ED); 13561 return ED; 13562 } 13563 13564 /// Perform semantic analysis for the variable declaration that 13565 /// occurs within a C++ catch clause, returning the newly-created 13566 /// variable. 13567 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13568 TypeSourceInfo *TInfo, 13569 SourceLocation StartLoc, 13570 SourceLocation Loc, 13571 IdentifierInfo *Name) { 13572 bool Invalid = false; 13573 QualType ExDeclType = TInfo->getType(); 13574 13575 // Arrays and functions decay. 13576 if (ExDeclType->isArrayType()) 13577 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13578 else if (ExDeclType->isFunctionType()) 13579 ExDeclType = Context.getPointerType(ExDeclType); 13580 13581 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13582 // The exception-declaration shall not denote a pointer or reference to an 13583 // incomplete type, other than [cv] void*. 13584 // N2844 forbids rvalue references. 13585 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13586 Diag(Loc, diag::err_catch_rvalue_ref); 13587 Invalid = true; 13588 } 13589 13590 if (ExDeclType->isVariablyModifiedType()) { 13591 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13592 Invalid = true; 13593 } 13594 13595 QualType BaseType = ExDeclType; 13596 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13597 unsigned DK = diag::err_catch_incomplete; 13598 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13599 BaseType = Ptr->getPointeeType(); 13600 Mode = 1; 13601 DK = diag::err_catch_incomplete_ptr; 13602 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13603 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13604 BaseType = Ref->getPointeeType(); 13605 Mode = 2; 13606 DK = diag::err_catch_incomplete_ref; 13607 } 13608 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13609 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13610 Invalid = true; 13611 13612 if (!Invalid && !ExDeclType->isDependentType() && 13613 RequireNonAbstractType(Loc, ExDeclType, 13614 diag::err_abstract_type_in_decl, 13615 AbstractVariableType)) 13616 Invalid = true; 13617 13618 // Only the non-fragile NeXT runtime currently supports C++ catches 13619 // of ObjC types, and no runtime supports catching ObjC types by value. 13620 if (!Invalid && getLangOpts().ObjC1) { 13621 QualType T = ExDeclType; 13622 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13623 T = RT->getPointeeType(); 13624 13625 if (T->isObjCObjectType()) { 13626 Diag(Loc, diag::err_objc_object_catch); 13627 Invalid = true; 13628 } else if (T->isObjCObjectPointerType()) { 13629 // FIXME: should this be a test for macosx-fragile specifically? 13630 if (getLangOpts().ObjCRuntime.isFragile()) 13631 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13632 } 13633 } 13634 13635 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13636 ExDeclType, TInfo, SC_None); 13637 ExDecl->setExceptionVariable(true); 13638 13639 // In ARC, infer 'retaining' for variables of retainable type. 13640 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13641 Invalid = true; 13642 13643 if (!Invalid && !ExDeclType->isDependentType()) { 13644 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13645 // Insulate this from anything else we might currently be parsing. 13646 EnterExpressionEvaluationContext scope( 13647 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13648 13649 // C++ [except.handle]p16: 13650 // The object declared in an exception-declaration or, if the 13651 // exception-declaration does not specify a name, a temporary (12.2) is 13652 // copy-initialized (8.5) from the exception object. [...] 13653 // The object is destroyed when the handler exits, after the destruction 13654 // of any automatic objects initialized within the handler. 13655 // 13656 // We just pretend to initialize the object with itself, then make sure 13657 // it can be destroyed later. 13658 QualType initType = Context.getExceptionObjectType(ExDeclType); 13659 13660 InitializedEntity entity = 13661 InitializedEntity::InitializeVariable(ExDecl); 13662 InitializationKind initKind = 13663 InitializationKind::CreateCopy(Loc, SourceLocation()); 13664 13665 Expr *opaqueValue = 13666 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13667 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13668 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13669 if (result.isInvalid()) 13670 Invalid = true; 13671 else { 13672 // If the constructor used was non-trivial, set this as the 13673 // "initializer". 13674 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13675 if (!construct->getConstructor()->isTrivial()) { 13676 Expr *init = MaybeCreateExprWithCleanups(construct); 13677 ExDecl->setInit(init); 13678 } 13679 13680 // And make sure it's destructable. 13681 FinalizeVarWithDestructor(ExDecl, recordType); 13682 } 13683 } 13684 } 13685 13686 if (Invalid) 13687 ExDecl->setInvalidDecl(); 13688 13689 return ExDecl; 13690 } 13691 13692 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13693 /// handler. 13694 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13695 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13696 bool Invalid = D.isInvalidType(); 13697 13698 // Check for unexpanded parameter packs. 13699 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13700 UPPC_ExceptionType)) { 13701 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13702 D.getIdentifierLoc()); 13703 Invalid = true; 13704 } 13705 13706 IdentifierInfo *II = D.getIdentifier(); 13707 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13708 LookupOrdinaryName, 13709 ForVisibleRedeclaration)) { 13710 // The scope should be freshly made just for us. There is just no way 13711 // it contains any previous declaration, except for function parameters in 13712 // a function-try-block's catch statement. 13713 assert(!S->isDeclScope(PrevDecl)); 13714 if (isDeclInScope(PrevDecl, CurContext, S)) { 13715 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13716 << D.getIdentifier(); 13717 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13718 Invalid = true; 13719 } else if (PrevDecl->isTemplateParameter()) 13720 // Maybe we will complain about the shadowed template parameter. 13721 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13722 } 13723 13724 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13725 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13726 << D.getCXXScopeSpec().getRange(); 13727 Invalid = true; 13728 } 13729 13730 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13731 D.getLocStart(), 13732 D.getIdentifierLoc(), 13733 D.getIdentifier()); 13734 if (Invalid) 13735 ExDecl->setInvalidDecl(); 13736 13737 // Add the exception declaration into this scope. 13738 if (II) 13739 PushOnScopeChains(ExDecl, S); 13740 else 13741 CurContext->addDecl(ExDecl); 13742 13743 ProcessDeclAttributes(S, ExDecl, D); 13744 return ExDecl; 13745 } 13746 13747 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13748 Expr *AssertExpr, 13749 Expr *AssertMessageExpr, 13750 SourceLocation RParenLoc) { 13751 StringLiteral *AssertMessage = 13752 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13753 13754 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13755 return nullptr; 13756 13757 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13758 AssertMessage, RParenLoc, false); 13759 } 13760 13761 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13762 Expr *AssertExpr, 13763 StringLiteral *AssertMessage, 13764 SourceLocation RParenLoc, 13765 bool Failed) { 13766 assert(AssertExpr != nullptr && "Expected non-null condition"); 13767 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13768 !Failed) { 13769 // In a static_assert-declaration, the constant-expression shall be a 13770 // constant expression that can be contextually converted to bool. 13771 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13772 if (Converted.isInvalid()) 13773 Failed = true; 13774 13775 llvm::APSInt Cond; 13776 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13777 diag::err_static_assert_expression_is_not_constant, 13778 /*AllowFold=*/false).isInvalid()) 13779 Failed = true; 13780 13781 if (!Failed && !Cond) { 13782 SmallString<256> MsgBuffer; 13783 llvm::raw_svector_ostream Msg(MsgBuffer); 13784 if (AssertMessage) 13785 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13786 13787 Expr *InnerCond = nullptr; 13788 std::string InnerCondDescription; 13789 std::tie(InnerCond, InnerCondDescription) = 13790 findFailedBooleanCondition(Converted.get(), 13791 /*AllowTopLevelCond=*/false); 13792 if (InnerCond) { 13793 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13794 << InnerCondDescription << !AssertMessage 13795 << Msg.str() << InnerCond->getSourceRange(); 13796 } else { 13797 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13798 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13799 } 13800 Failed = true; 13801 } 13802 } 13803 13804 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13805 /*DiscardedValue*/false, 13806 /*IsConstexpr*/true); 13807 if (FullAssertExpr.isInvalid()) 13808 Failed = true; 13809 else 13810 AssertExpr = FullAssertExpr.get(); 13811 13812 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13813 AssertExpr, AssertMessage, RParenLoc, 13814 Failed); 13815 13816 CurContext->addDecl(Decl); 13817 return Decl; 13818 } 13819 13820 /// Perform semantic analysis of the given friend type declaration. 13821 /// 13822 /// \returns A friend declaration that. 13823 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13824 SourceLocation FriendLoc, 13825 TypeSourceInfo *TSInfo) { 13826 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13827 13828 QualType T = TSInfo->getType(); 13829 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13830 13831 // C++03 [class.friend]p2: 13832 // An elaborated-type-specifier shall be used in a friend declaration 13833 // for a class.* 13834 // 13835 // * The class-key of the elaborated-type-specifier is required. 13836 if (!CodeSynthesisContexts.empty()) { 13837 // Do not complain about the form of friend template types during any kind 13838 // of code synthesis. For template instantiation, we will have complained 13839 // when the template was defined. 13840 } else { 13841 if (!T->isElaboratedTypeSpecifier()) { 13842 // If we evaluated the type to a record type, suggest putting 13843 // a tag in front. 13844 if (const RecordType *RT = T->getAs<RecordType>()) { 13845 RecordDecl *RD = RT->getDecl(); 13846 13847 SmallString<16> InsertionText(" "); 13848 InsertionText += RD->getKindName(); 13849 13850 Diag(TypeRange.getBegin(), 13851 getLangOpts().CPlusPlus11 ? 13852 diag::warn_cxx98_compat_unelaborated_friend_type : 13853 diag::ext_unelaborated_friend_type) 13854 << (unsigned) RD->getTagKind() 13855 << T 13856 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13857 InsertionText); 13858 } else { 13859 Diag(FriendLoc, 13860 getLangOpts().CPlusPlus11 ? 13861 diag::warn_cxx98_compat_nonclass_type_friend : 13862 diag::ext_nonclass_type_friend) 13863 << T 13864 << TypeRange; 13865 } 13866 } else if (T->getAs<EnumType>()) { 13867 Diag(FriendLoc, 13868 getLangOpts().CPlusPlus11 ? 13869 diag::warn_cxx98_compat_enum_friend : 13870 diag::ext_enum_friend) 13871 << T 13872 << TypeRange; 13873 } 13874 13875 // C++11 [class.friend]p3: 13876 // A friend declaration that does not declare a function shall have one 13877 // of the following forms: 13878 // friend elaborated-type-specifier ; 13879 // friend simple-type-specifier ; 13880 // friend typename-specifier ; 13881 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13882 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13883 } 13884 13885 // If the type specifier in a friend declaration designates a (possibly 13886 // cv-qualified) class type, that class is declared as a friend; otherwise, 13887 // the friend declaration is ignored. 13888 return FriendDecl::Create(Context, CurContext, 13889 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13890 FriendLoc); 13891 } 13892 13893 /// Handle a friend tag declaration where the scope specifier was 13894 /// templated. 13895 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13896 unsigned TagSpec, SourceLocation TagLoc, 13897 CXXScopeSpec &SS, 13898 IdentifierInfo *Name, 13899 SourceLocation NameLoc, 13900 AttributeList *Attr, 13901 MultiTemplateParamsArg TempParamLists) { 13902 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13903 13904 bool IsMemberSpecialization = false; 13905 bool Invalid = false; 13906 13907 if (TemplateParameterList *TemplateParams = 13908 MatchTemplateParametersToScopeSpecifier( 13909 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13910 IsMemberSpecialization, Invalid)) { 13911 if (TemplateParams->size() > 0) { 13912 // This is a declaration of a class template. 13913 if (Invalid) 13914 return nullptr; 13915 13916 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13917 NameLoc, Attr, TemplateParams, AS_public, 13918 /*ModulePrivateLoc=*/SourceLocation(), 13919 FriendLoc, TempParamLists.size() - 1, 13920 TempParamLists.data()).get(); 13921 } else { 13922 // The "template<>" header is extraneous. 13923 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13924 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13925 IsMemberSpecialization = true; 13926 } 13927 } 13928 13929 if (Invalid) return nullptr; 13930 13931 bool isAllExplicitSpecializations = true; 13932 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13933 if (TempParamLists[I]->size()) { 13934 isAllExplicitSpecializations = false; 13935 break; 13936 } 13937 } 13938 13939 // FIXME: don't ignore attributes. 13940 13941 // If it's explicit specializations all the way down, just forget 13942 // about the template header and build an appropriate non-templated 13943 // friend. TODO: for source fidelity, remember the headers. 13944 if (isAllExplicitSpecializations) { 13945 if (SS.isEmpty()) { 13946 bool Owned = false; 13947 bool IsDependent = false; 13948 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13949 Attr, AS_public, 13950 /*ModulePrivateLoc=*/SourceLocation(), 13951 MultiTemplateParamsArg(), Owned, IsDependent, 13952 /*ScopedEnumKWLoc=*/SourceLocation(), 13953 /*ScopedEnumUsesClassTag=*/false, 13954 /*UnderlyingType=*/TypeResult(), 13955 /*IsTypeSpecifier=*/false, 13956 /*IsTemplateParamOrArg=*/false); 13957 } 13958 13959 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13960 ElaboratedTypeKeyword Keyword 13961 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13962 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13963 *Name, NameLoc); 13964 if (T.isNull()) 13965 return nullptr; 13966 13967 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13968 if (isa<DependentNameType>(T)) { 13969 DependentNameTypeLoc TL = 13970 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13971 TL.setElaboratedKeywordLoc(TagLoc); 13972 TL.setQualifierLoc(QualifierLoc); 13973 TL.setNameLoc(NameLoc); 13974 } else { 13975 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13976 TL.setElaboratedKeywordLoc(TagLoc); 13977 TL.setQualifierLoc(QualifierLoc); 13978 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13979 } 13980 13981 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13982 TSI, FriendLoc, TempParamLists); 13983 Friend->setAccess(AS_public); 13984 CurContext->addDecl(Friend); 13985 return Friend; 13986 } 13987 13988 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13989 13990 13991 13992 // Handle the case of a templated-scope friend class. e.g. 13993 // template <class T> class A<T>::B; 13994 // FIXME: we don't support these right now. 13995 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13996 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13997 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13998 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13999 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14000 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14001 TL.setElaboratedKeywordLoc(TagLoc); 14002 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14003 TL.setNameLoc(NameLoc); 14004 14005 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14006 TSI, FriendLoc, TempParamLists); 14007 Friend->setAccess(AS_public); 14008 Friend->setUnsupportedFriend(true); 14009 CurContext->addDecl(Friend); 14010 return Friend; 14011 } 14012 14013 14014 /// Handle a friend type declaration. This works in tandem with 14015 /// ActOnTag. 14016 /// 14017 /// Notes on friend class templates: 14018 /// 14019 /// We generally treat friend class declarations as if they were 14020 /// declaring a class. So, for example, the elaborated type specifier 14021 /// in a friend declaration is required to obey the restrictions of a 14022 /// class-head (i.e. no typedefs in the scope chain), template 14023 /// parameters are required to match up with simple template-ids, &c. 14024 /// However, unlike when declaring a template specialization, it's 14025 /// okay to refer to a template specialization without an empty 14026 /// template parameter declaration, e.g. 14027 /// friend class A<T>::B<unsigned>; 14028 /// We permit this as a special case; if there are any template 14029 /// parameters present at all, require proper matching, i.e. 14030 /// template <> template \<class T> friend class A<int>::B; 14031 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14032 MultiTemplateParamsArg TempParams) { 14033 SourceLocation Loc = DS.getLocStart(); 14034 14035 assert(DS.isFriendSpecified()); 14036 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14037 14038 // Try to convert the decl specifier to a type. This works for 14039 // friend templates because ActOnTag never produces a ClassTemplateDecl 14040 // for a TUK_Friend. 14041 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14042 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14043 QualType T = TSI->getType(); 14044 if (TheDeclarator.isInvalidType()) 14045 return nullptr; 14046 14047 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14048 return nullptr; 14049 14050 // This is definitely an error in C++98. It's probably meant to 14051 // be forbidden in C++0x, too, but the specification is just 14052 // poorly written. 14053 // 14054 // The problem is with declarations like the following: 14055 // template <T> friend A<T>::foo; 14056 // where deciding whether a class C is a friend or not now hinges 14057 // on whether there exists an instantiation of A that causes 14058 // 'foo' to equal C. There are restrictions on class-heads 14059 // (which we declare (by fiat) elaborated friend declarations to 14060 // be) that makes this tractable. 14061 // 14062 // FIXME: handle "template <> friend class A<T>;", which 14063 // is possibly well-formed? Who even knows? 14064 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14065 Diag(Loc, diag::err_tagless_friend_type_template) 14066 << DS.getSourceRange(); 14067 return nullptr; 14068 } 14069 14070 // C++98 [class.friend]p1: A friend of a class is a function 14071 // or class that is not a member of the class . . . 14072 // This is fixed in DR77, which just barely didn't make the C++03 14073 // deadline. It's also a very silly restriction that seriously 14074 // affects inner classes and which nobody else seems to implement; 14075 // thus we never diagnose it, not even in -pedantic. 14076 // 14077 // But note that we could warn about it: it's always useless to 14078 // friend one of your own members (it's not, however, worthless to 14079 // friend a member of an arbitrary specialization of your template). 14080 14081 Decl *D; 14082 if (!TempParams.empty()) 14083 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14084 TempParams, 14085 TSI, 14086 DS.getFriendSpecLoc()); 14087 else 14088 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14089 14090 if (!D) 14091 return nullptr; 14092 14093 D->setAccess(AS_public); 14094 CurContext->addDecl(D); 14095 14096 return D; 14097 } 14098 14099 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14100 MultiTemplateParamsArg TemplateParams) { 14101 const DeclSpec &DS = D.getDeclSpec(); 14102 14103 assert(DS.isFriendSpecified()); 14104 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14105 14106 SourceLocation Loc = D.getIdentifierLoc(); 14107 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14108 14109 // C++ [class.friend]p1 14110 // A friend of a class is a function or class.... 14111 // Note that this sees through typedefs, which is intended. 14112 // It *doesn't* see through dependent types, which is correct 14113 // according to [temp.arg.type]p3: 14114 // If a declaration acquires a function type through a 14115 // type dependent on a template-parameter and this causes 14116 // a declaration that does not use the syntactic form of a 14117 // function declarator to have a function type, the program 14118 // is ill-formed. 14119 if (!TInfo->getType()->isFunctionType()) { 14120 Diag(Loc, diag::err_unexpected_friend); 14121 14122 // It might be worthwhile to try to recover by creating an 14123 // appropriate declaration. 14124 return nullptr; 14125 } 14126 14127 // C++ [namespace.memdef]p3 14128 // - If a friend declaration in a non-local class first declares a 14129 // class or function, the friend class or function is a member 14130 // of the innermost enclosing namespace. 14131 // - The name of the friend is not found by simple name lookup 14132 // until a matching declaration is provided in that namespace 14133 // scope (either before or after the class declaration granting 14134 // friendship). 14135 // - If a friend function is called, its name may be found by the 14136 // name lookup that considers functions from namespaces and 14137 // classes associated with the types of the function arguments. 14138 // - When looking for a prior declaration of a class or a function 14139 // declared as a friend, scopes outside the innermost enclosing 14140 // namespace scope are not considered. 14141 14142 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14143 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14144 DeclarationName Name = NameInfo.getName(); 14145 assert(Name); 14146 14147 // Check for unexpanded parameter packs. 14148 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14149 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14150 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14151 return nullptr; 14152 14153 // The context we found the declaration in, or in which we should 14154 // create the declaration. 14155 DeclContext *DC; 14156 Scope *DCScope = S; 14157 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14158 ForExternalRedeclaration); 14159 14160 // There are five cases here. 14161 // - There's no scope specifier and we're in a local class. Only look 14162 // for functions declared in the immediately-enclosing block scope. 14163 // We recover from invalid scope qualifiers as if they just weren't there. 14164 FunctionDecl *FunctionContainingLocalClass = nullptr; 14165 if ((SS.isInvalid() || !SS.isSet()) && 14166 (FunctionContainingLocalClass = 14167 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14168 // C++11 [class.friend]p11: 14169 // If a friend declaration appears in a local class and the name 14170 // specified is an unqualified name, a prior declaration is 14171 // looked up without considering scopes that are outside the 14172 // innermost enclosing non-class scope. For a friend function 14173 // declaration, if there is no prior declaration, the program is 14174 // ill-formed. 14175 14176 // Find the innermost enclosing non-class scope. This is the block 14177 // scope containing the local class definition (or for a nested class, 14178 // the outer local class). 14179 DCScope = S->getFnParent(); 14180 14181 // Look up the function name in the scope. 14182 Previous.clear(LookupLocalFriendName); 14183 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14184 14185 if (!Previous.empty()) { 14186 // All possible previous declarations must have the same context: 14187 // either they were declared at block scope or they are members of 14188 // one of the enclosing local classes. 14189 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14190 } else { 14191 // This is ill-formed, but provide the context that we would have 14192 // declared the function in, if we were permitted to, for error recovery. 14193 DC = FunctionContainingLocalClass; 14194 } 14195 adjustContextForLocalExternDecl(DC); 14196 14197 // C++ [class.friend]p6: 14198 // A function can be defined in a friend declaration of a class if and 14199 // only if the class is a non-local class (9.8), the function name is 14200 // unqualified, and the function has namespace scope. 14201 if (D.isFunctionDefinition()) { 14202 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14203 } 14204 14205 // - There's no scope specifier, in which case we just go to the 14206 // appropriate scope and look for a function or function template 14207 // there as appropriate. 14208 } else if (SS.isInvalid() || !SS.isSet()) { 14209 // C++11 [namespace.memdef]p3: 14210 // If the name in a friend declaration is neither qualified nor 14211 // a template-id and the declaration is a function or an 14212 // elaborated-type-specifier, the lookup to determine whether 14213 // the entity has been previously declared shall not consider 14214 // any scopes outside the innermost enclosing namespace. 14215 bool isTemplateId = 14216 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14217 14218 // Find the appropriate context according to the above. 14219 DC = CurContext; 14220 14221 // Skip class contexts. If someone can cite chapter and verse 14222 // for this behavior, that would be nice --- it's what GCC and 14223 // EDG do, and it seems like a reasonable intent, but the spec 14224 // really only says that checks for unqualified existing 14225 // declarations should stop at the nearest enclosing namespace, 14226 // not that they should only consider the nearest enclosing 14227 // namespace. 14228 while (DC->isRecord()) 14229 DC = DC->getParent(); 14230 14231 DeclContext *LookupDC = DC; 14232 while (LookupDC->isTransparentContext()) 14233 LookupDC = LookupDC->getParent(); 14234 14235 while (true) { 14236 LookupQualifiedName(Previous, LookupDC); 14237 14238 if (!Previous.empty()) { 14239 DC = LookupDC; 14240 break; 14241 } 14242 14243 if (isTemplateId) { 14244 if (isa<TranslationUnitDecl>(LookupDC)) break; 14245 } else { 14246 if (LookupDC->isFileContext()) break; 14247 } 14248 LookupDC = LookupDC->getParent(); 14249 } 14250 14251 DCScope = getScopeForDeclContext(S, DC); 14252 14253 // - There's a non-dependent scope specifier, in which case we 14254 // compute it and do a previous lookup there for a function 14255 // or function template. 14256 } else if (!SS.getScopeRep()->isDependent()) { 14257 DC = computeDeclContext(SS); 14258 if (!DC) return nullptr; 14259 14260 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14261 14262 LookupQualifiedName(Previous, DC); 14263 14264 // Ignore things found implicitly in the wrong scope. 14265 // TODO: better diagnostics for this case. Suggesting the right 14266 // qualified scope would be nice... 14267 LookupResult::Filter F = Previous.makeFilter(); 14268 while (F.hasNext()) { 14269 NamedDecl *D = F.next(); 14270 if (!DC->InEnclosingNamespaceSetOf( 14271 D->getDeclContext()->getRedeclContext())) 14272 F.erase(); 14273 } 14274 F.done(); 14275 14276 if (Previous.empty()) { 14277 D.setInvalidType(); 14278 Diag(Loc, diag::err_qualified_friend_not_found) 14279 << Name << TInfo->getType(); 14280 return nullptr; 14281 } 14282 14283 // C++ [class.friend]p1: A friend of a class is a function or 14284 // class that is not a member of the class . . . 14285 if (DC->Equals(CurContext)) 14286 Diag(DS.getFriendSpecLoc(), 14287 getLangOpts().CPlusPlus11 ? 14288 diag::warn_cxx98_compat_friend_is_member : 14289 diag::err_friend_is_member); 14290 14291 if (D.isFunctionDefinition()) { 14292 // C++ [class.friend]p6: 14293 // A function can be defined in a friend declaration of a class if and 14294 // only if the class is a non-local class (9.8), the function name is 14295 // unqualified, and the function has namespace scope. 14296 SemaDiagnosticBuilder DB 14297 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14298 14299 DB << SS.getScopeRep(); 14300 if (DC->isFileContext()) 14301 DB << FixItHint::CreateRemoval(SS.getRange()); 14302 SS.clear(); 14303 } 14304 14305 // - There's a scope specifier that does not match any template 14306 // parameter lists, in which case we use some arbitrary context, 14307 // create a method or method template, and wait for instantiation. 14308 // - There's a scope specifier that does match some template 14309 // parameter lists, which we don't handle right now. 14310 } else { 14311 if (D.isFunctionDefinition()) { 14312 // C++ [class.friend]p6: 14313 // A function can be defined in a friend declaration of a class if and 14314 // only if the class is a non-local class (9.8), the function name is 14315 // unqualified, and the function has namespace scope. 14316 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14317 << SS.getScopeRep(); 14318 } 14319 14320 DC = CurContext; 14321 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14322 } 14323 14324 if (!DC->isRecord()) { 14325 int DiagArg = -1; 14326 switch (D.getName().getKind()) { 14327 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14328 case UnqualifiedIdKind::IK_ConstructorName: 14329 DiagArg = 0; 14330 break; 14331 case UnqualifiedIdKind::IK_DestructorName: 14332 DiagArg = 1; 14333 break; 14334 case UnqualifiedIdKind::IK_ConversionFunctionId: 14335 DiagArg = 2; 14336 break; 14337 case UnqualifiedIdKind::IK_DeductionGuideName: 14338 DiagArg = 3; 14339 break; 14340 case UnqualifiedIdKind::IK_Identifier: 14341 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14342 case UnqualifiedIdKind::IK_LiteralOperatorId: 14343 case UnqualifiedIdKind::IK_OperatorFunctionId: 14344 case UnqualifiedIdKind::IK_TemplateId: 14345 break; 14346 } 14347 // This implies that it has to be an operator or function. 14348 if (DiagArg >= 0) { 14349 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14350 return nullptr; 14351 } 14352 } 14353 14354 // FIXME: This is an egregious hack to cope with cases where the scope stack 14355 // does not contain the declaration context, i.e., in an out-of-line 14356 // definition of a class. 14357 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14358 if (!DCScope) { 14359 FakeDCScope.setEntity(DC); 14360 DCScope = &FakeDCScope; 14361 } 14362 14363 bool AddToScope = true; 14364 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14365 TemplateParams, AddToScope); 14366 if (!ND) return nullptr; 14367 14368 assert(ND->getLexicalDeclContext() == CurContext); 14369 14370 // If we performed typo correction, we might have added a scope specifier 14371 // and changed the decl context. 14372 DC = ND->getDeclContext(); 14373 14374 // Add the function declaration to the appropriate lookup tables, 14375 // adjusting the redeclarations list as necessary. We don't 14376 // want to do this yet if the friending class is dependent. 14377 // 14378 // Also update the scope-based lookup if the target context's 14379 // lookup context is in lexical scope. 14380 if (!CurContext->isDependentContext()) { 14381 DC = DC->getRedeclContext(); 14382 DC->makeDeclVisibleInContext(ND); 14383 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14384 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14385 } 14386 14387 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14388 D.getIdentifierLoc(), ND, 14389 DS.getFriendSpecLoc()); 14390 FrD->setAccess(AS_public); 14391 CurContext->addDecl(FrD); 14392 14393 if (ND->isInvalidDecl()) { 14394 FrD->setInvalidDecl(); 14395 } else { 14396 if (DC->isRecord()) CheckFriendAccess(ND); 14397 14398 FunctionDecl *FD; 14399 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14400 FD = FTD->getTemplatedDecl(); 14401 else 14402 FD = cast<FunctionDecl>(ND); 14403 14404 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14405 // default argument expression, that declaration shall be a definition 14406 // and shall be the only declaration of the function or function 14407 // template in the translation unit. 14408 if (functionDeclHasDefaultArgument(FD)) { 14409 // We can't look at FD->getPreviousDecl() because it may not have been set 14410 // if we're in a dependent context. If the function is known to be a 14411 // redeclaration, we will have narrowed Previous down to the right decl. 14412 if (D.isRedeclaration()) { 14413 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14414 Diag(Previous.getRepresentativeDecl()->getLocation(), 14415 diag::note_previous_declaration); 14416 } else if (!D.isFunctionDefinition()) 14417 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14418 } 14419 14420 // Mark templated-scope function declarations as unsupported. 14421 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14422 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14423 << SS.getScopeRep() << SS.getRange() 14424 << cast<CXXRecordDecl>(CurContext); 14425 FrD->setUnsupportedFriend(true); 14426 } 14427 } 14428 14429 return ND; 14430 } 14431 14432 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14433 AdjustDeclIfTemplate(Dcl); 14434 14435 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14436 if (!Fn) { 14437 Diag(DelLoc, diag::err_deleted_non_function); 14438 return; 14439 } 14440 14441 // Deleted function does not have a body. 14442 Fn->setWillHaveBody(false); 14443 14444 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14445 // Don't consider the implicit declaration we generate for explicit 14446 // specializations. FIXME: Do not generate these implicit declarations. 14447 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14448 Prev->getPreviousDecl()) && 14449 !Prev->isDefined()) { 14450 Diag(DelLoc, diag::err_deleted_decl_not_first); 14451 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14452 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14453 : diag::note_previous_declaration); 14454 } 14455 // If the declaration wasn't the first, we delete the function anyway for 14456 // recovery. 14457 Fn = Fn->getCanonicalDecl(); 14458 } 14459 14460 // dllimport/dllexport cannot be deleted. 14461 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14462 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14463 Fn->setInvalidDecl(); 14464 } 14465 14466 if (Fn->isDeleted()) 14467 return; 14468 14469 // See if we're deleting a function which is already known to override a 14470 // non-deleted virtual function. 14471 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14472 bool IssuedDiagnostic = false; 14473 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14474 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14475 if (!IssuedDiagnostic) { 14476 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14477 IssuedDiagnostic = true; 14478 } 14479 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14480 } 14481 } 14482 // If this function was implicitly deleted because it was defaulted, 14483 // explain why it was deleted. 14484 if (IssuedDiagnostic && MD->isDefaulted()) 14485 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14486 /*Diagnose*/true); 14487 } 14488 14489 // C++11 [basic.start.main]p3: 14490 // A program that defines main as deleted [...] is ill-formed. 14491 if (Fn->isMain()) 14492 Diag(DelLoc, diag::err_deleted_main); 14493 14494 // C++11 [dcl.fct.def.delete]p4: 14495 // A deleted function is implicitly inline. 14496 Fn->setImplicitlyInline(); 14497 Fn->setDeletedAsWritten(); 14498 } 14499 14500 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14501 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14502 14503 if (MD) { 14504 if (MD->getParent()->isDependentType()) { 14505 MD->setDefaulted(); 14506 MD->setExplicitlyDefaulted(); 14507 return; 14508 } 14509 14510 CXXSpecialMember Member = getSpecialMember(MD); 14511 if (Member == CXXInvalid) { 14512 if (!MD->isInvalidDecl()) 14513 Diag(DefaultLoc, diag::err_default_special_members); 14514 return; 14515 } 14516 14517 MD->setDefaulted(); 14518 MD->setExplicitlyDefaulted(); 14519 14520 // Unset that we will have a body for this function. We might not, 14521 // if it turns out to be trivial, and we don't need this marking now 14522 // that we've marked it as defaulted. 14523 MD->setWillHaveBody(false); 14524 14525 // If this definition appears within the record, do the checking when 14526 // the record is complete. 14527 const FunctionDecl *Primary = MD; 14528 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14529 // Ask the template instantiation pattern that actually had the 14530 // '= default' on it. 14531 Primary = Pattern; 14532 14533 // If the method was defaulted on its first declaration, we will have 14534 // already performed the checking in CheckCompletedCXXClass. Such a 14535 // declaration doesn't trigger an implicit definition. 14536 if (Primary->getCanonicalDecl()->isDefaulted()) 14537 return; 14538 14539 CheckExplicitlyDefaultedSpecialMember(MD); 14540 14541 if (!MD->isInvalidDecl()) 14542 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14543 } else { 14544 Diag(DefaultLoc, diag::err_default_special_members); 14545 } 14546 } 14547 14548 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14549 for (Stmt *SubStmt : S->children()) { 14550 if (!SubStmt) 14551 continue; 14552 if (isa<ReturnStmt>(SubStmt)) 14553 Self.Diag(SubStmt->getLocStart(), 14554 diag::err_return_in_constructor_handler); 14555 if (!isa<Expr>(SubStmt)) 14556 SearchForReturnInStmt(Self, SubStmt); 14557 } 14558 } 14559 14560 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14561 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14562 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14563 SearchForReturnInStmt(*this, Handler); 14564 } 14565 } 14566 14567 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14568 const CXXMethodDecl *Old) { 14569 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14570 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14571 14572 if (OldFT->hasExtParameterInfos()) { 14573 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14574 // A parameter of the overriding method should be annotated with noescape 14575 // if the corresponding parameter of the overridden method is annotated. 14576 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14577 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14578 Diag(New->getParamDecl(I)->getLocation(), 14579 diag::warn_overriding_method_missing_noescape); 14580 Diag(Old->getParamDecl(I)->getLocation(), 14581 diag::note_overridden_marked_noescape); 14582 } 14583 } 14584 14585 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14586 14587 // If the calling conventions match, everything is fine 14588 if (NewCC == OldCC) 14589 return false; 14590 14591 // If the calling conventions mismatch because the new function is static, 14592 // suppress the calling convention mismatch error; the error about static 14593 // function override (err_static_overrides_virtual from 14594 // Sema::CheckFunctionDeclaration) is more clear. 14595 if (New->getStorageClass() == SC_Static) 14596 return false; 14597 14598 Diag(New->getLocation(), 14599 diag::err_conflicting_overriding_cc_attributes) 14600 << New->getDeclName() << New->getType() << Old->getType(); 14601 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14602 return true; 14603 } 14604 14605 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14606 const CXXMethodDecl *Old) { 14607 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14608 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14609 14610 if (Context.hasSameType(NewTy, OldTy) || 14611 NewTy->isDependentType() || OldTy->isDependentType()) 14612 return false; 14613 14614 // Check if the return types are covariant 14615 QualType NewClassTy, OldClassTy; 14616 14617 /// Both types must be pointers or references to classes. 14618 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14619 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14620 NewClassTy = NewPT->getPointeeType(); 14621 OldClassTy = OldPT->getPointeeType(); 14622 } 14623 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14624 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14625 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14626 NewClassTy = NewRT->getPointeeType(); 14627 OldClassTy = OldRT->getPointeeType(); 14628 } 14629 } 14630 } 14631 14632 // The return types aren't either both pointers or references to a class type. 14633 if (NewClassTy.isNull()) { 14634 Diag(New->getLocation(), 14635 diag::err_different_return_type_for_overriding_virtual_function) 14636 << New->getDeclName() << NewTy << OldTy 14637 << New->getReturnTypeSourceRange(); 14638 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14639 << Old->getReturnTypeSourceRange(); 14640 14641 return true; 14642 } 14643 14644 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14645 // C++14 [class.virtual]p8: 14646 // If the class type in the covariant return type of D::f differs from 14647 // that of B::f, the class type in the return type of D::f shall be 14648 // complete at the point of declaration of D::f or shall be the class 14649 // type D. 14650 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14651 if (!RT->isBeingDefined() && 14652 RequireCompleteType(New->getLocation(), NewClassTy, 14653 diag::err_covariant_return_incomplete, 14654 New->getDeclName())) 14655 return true; 14656 } 14657 14658 // Check if the new class derives from the old class. 14659 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14660 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14661 << New->getDeclName() << NewTy << OldTy 14662 << New->getReturnTypeSourceRange(); 14663 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14664 << Old->getReturnTypeSourceRange(); 14665 return true; 14666 } 14667 14668 // Check if we the conversion from derived to base is valid. 14669 if (CheckDerivedToBaseConversion( 14670 NewClassTy, OldClassTy, 14671 diag::err_covariant_return_inaccessible_base, 14672 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14673 New->getLocation(), New->getReturnTypeSourceRange(), 14674 New->getDeclName(), nullptr)) { 14675 // FIXME: this note won't trigger for delayed access control 14676 // diagnostics, and it's impossible to get an undelayed error 14677 // here from access control during the original parse because 14678 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14679 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14680 << Old->getReturnTypeSourceRange(); 14681 return true; 14682 } 14683 } 14684 14685 // The qualifiers of the return types must be the same. 14686 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14687 Diag(New->getLocation(), 14688 diag::err_covariant_return_type_different_qualifications) 14689 << New->getDeclName() << NewTy << OldTy 14690 << New->getReturnTypeSourceRange(); 14691 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14692 << Old->getReturnTypeSourceRange(); 14693 return true; 14694 } 14695 14696 14697 // The new class type must have the same or less qualifiers as the old type. 14698 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14699 Diag(New->getLocation(), 14700 diag::err_covariant_return_type_class_type_more_qualified) 14701 << New->getDeclName() << NewTy << OldTy 14702 << New->getReturnTypeSourceRange(); 14703 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14704 << Old->getReturnTypeSourceRange(); 14705 return true; 14706 } 14707 14708 return false; 14709 } 14710 14711 /// Mark the given method pure. 14712 /// 14713 /// \param Method the method to be marked pure. 14714 /// 14715 /// \param InitRange the source range that covers the "0" initializer. 14716 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14717 SourceLocation EndLoc = InitRange.getEnd(); 14718 if (EndLoc.isValid()) 14719 Method->setRangeEnd(EndLoc); 14720 14721 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14722 Method->setPure(); 14723 return false; 14724 } 14725 14726 if (!Method->isInvalidDecl()) 14727 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14728 << Method->getDeclName() << InitRange; 14729 return true; 14730 } 14731 14732 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14733 if (D->getFriendObjectKind()) 14734 Diag(D->getLocation(), diag::err_pure_friend); 14735 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14736 CheckPureMethod(M, ZeroLoc); 14737 else 14738 Diag(D->getLocation(), diag::err_illegal_initializer); 14739 } 14740 14741 /// Determine whether the given declaration is a global variable or 14742 /// static data member. 14743 static bool isNonlocalVariable(const Decl *D) { 14744 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14745 return Var->hasGlobalStorage(); 14746 14747 return false; 14748 } 14749 14750 /// Invoked when we are about to parse an initializer for the declaration 14751 /// 'Dcl'. 14752 /// 14753 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14754 /// static data member of class X, names should be looked up in the scope of 14755 /// class X. If the declaration had a scope specifier, a scope will have 14756 /// been created and passed in for this purpose. Otherwise, S will be null. 14757 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14758 // If there is no declaration, there was an error parsing it. 14759 if (!D || D->isInvalidDecl()) 14760 return; 14761 14762 // We will always have a nested name specifier here, but this declaration 14763 // might not be out of line if the specifier names the current namespace: 14764 // extern int n; 14765 // int ::n = 0; 14766 if (S && D->isOutOfLine()) 14767 EnterDeclaratorContext(S, D->getDeclContext()); 14768 14769 // If we are parsing the initializer for a static data member, push a 14770 // new expression evaluation context that is associated with this static 14771 // data member. 14772 if (isNonlocalVariable(D)) 14773 PushExpressionEvaluationContext( 14774 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14775 } 14776 14777 /// Invoked after we are finished parsing an initializer for the declaration D. 14778 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14779 // If there is no declaration, there was an error parsing it. 14780 if (!D || D->isInvalidDecl()) 14781 return; 14782 14783 if (isNonlocalVariable(D)) 14784 PopExpressionEvaluationContext(); 14785 14786 if (S && D->isOutOfLine()) 14787 ExitDeclaratorContext(S); 14788 } 14789 14790 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14791 /// C++ if/switch/while/for statement. 14792 /// e.g: "if (int x = f()) {...}" 14793 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14794 // C++ 6.4p2: 14795 // The declarator shall not specify a function or an array. 14796 // The type-specifier-seq shall not contain typedef and shall not declare a 14797 // new class or enumeration. 14798 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14799 "Parser allowed 'typedef' as storage class of condition decl."); 14800 14801 Decl *Dcl = ActOnDeclarator(S, D); 14802 if (!Dcl) 14803 return true; 14804 14805 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14806 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14807 << D.getSourceRange(); 14808 return true; 14809 } 14810 14811 return Dcl; 14812 } 14813 14814 void Sema::LoadExternalVTableUses() { 14815 if (!ExternalSource) 14816 return; 14817 14818 SmallVector<ExternalVTableUse, 4> VTables; 14819 ExternalSource->ReadUsedVTables(VTables); 14820 SmallVector<VTableUse, 4> NewUses; 14821 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14822 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14823 = VTablesUsed.find(VTables[I].Record); 14824 // Even if a definition wasn't required before, it may be required now. 14825 if (Pos != VTablesUsed.end()) { 14826 if (!Pos->second && VTables[I].DefinitionRequired) 14827 Pos->second = true; 14828 continue; 14829 } 14830 14831 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14832 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14833 } 14834 14835 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14836 } 14837 14838 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14839 bool DefinitionRequired) { 14840 // Ignore any vtable uses in unevaluated operands or for classes that do 14841 // not have a vtable. 14842 if (!Class->isDynamicClass() || Class->isDependentContext() || 14843 CurContext->isDependentContext() || isUnevaluatedContext()) 14844 return; 14845 14846 // Try to insert this class into the map. 14847 LoadExternalVTableUses(); 14848 Class = Class->getCanonicalDecl(); 14849 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14850 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14851 if (!Pos.second) { 14852 // If we already had an entry, check to see if we are promoting this vtable 14853 // to require a definition. If so, we need to reappend to the VTableUses 14854 // list, since we may have already processed the first entry. 14855 if (DefinitionRequired && !Pos.first->second) { 14856 Pos.first->second = true; 14857 } else { 14858 // Otherwise, we can early exit. 14859 return; 14860 } 14861 } else { 14862 // The Microsoft ABI requires that we perform the destructor body 14863 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14864 // the deleting destructor is emitted with the vtable, not with the 14865 // destructor definition as in the Itanium ABI. 14866 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14867 CXXDestructorDecl *DD = Class->getDestructor(); 14868 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14869 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14870 // If this is an out-of-line declaration, marking it referenced will 14871 // not do anything. Manually call CheckDestructor to look up operator 14872 // delete(). 14873 ContextRAII SavedContext(*this, DD); 14874 CheckDestructor(DD); 14875 } else { 14876 MarkFunctionReferenced(Loc, Class->getDestructor()); 14877 } 14878 } 14879 } 14880 } 14881 14882 // Local classes need to have their virtual members marked 14883 // immediately. For all other classes, we mark their virtual members 14884 // at the end of the translation unit. 14885 if (Class->isLocalClass()) 14886 MarkVirtualMembersReferenced(Loc, Class); 14887 else 14888 VTableUses.push_back(std::make_pair(Class, Loc)); 14889 } 14890 14891 bool Sema::DefineUsedVTables() { 14892 LoadExternalVTableUses(); 14893 if (VTableUses.empty()) 14894 return false; 14895 14896 // Note: The VTableUses vector could grow as a result of marking 14897 // the members of a class as "used", so we check the size each 14898 // time through the loop and prefer indices (which are stable) to 14899 // iterators (which are not). 14900 bool DefinedAnything = false; 14901 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14902 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14903 if (!Class) 14904 continue; 14905 TemplateSpecializationKind ClassTSK = 14906 Class->getTemplateSpecializationKind(); 14907 14908 SourceLocation Loc = VTableUses[I].second; 14909 14910 bool DefineVTable = true; 14911 14912 // If this class has a key function, but that key function is 14913 // defined in another translation unit, we don't need to emit the 14914 // vtable even though we're using it. 14915 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14916 if (KeyFunction && !KeyFunction->hasBody()) { 14917 // The key function is in another translation unit. 14918 DefineVTable = false; 14919 TemplateSpecializationKind TSK = 14920 KeyFunction->getTemplateSpecializationKind(); 14921 assert(TSK != TSK_ExplicitInstantiationDefinition && 14922 TSK != TSK_ImplicitInstantiation && 14923 "Instantiations don't have key functions"); 14924 (void)TSK; 14925 } else if (!KeyFunction) { 14926 // If we have a class with no key function that is the subject 14927 // of an explicit instantiation declaration, suppress the 14928 // vtable; it will live with the explicit instantiation 14929 // definition. 14930 bool IsExplicitInstantiationDeclaration = 14931 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14932 for (auto R : Class->redecls()) { 14933 TemplateSpecializationKind TSK 14934 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14935 if (TSK == TSK_ExplicitInstantiationDeclaration) 14936 IsExplicitInstantiationDeclaration = true; 14937 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14938 IsExplicitInstantiationDeclaration = false; 14939 break; 14940 } 14941 } 14942 14943 if (IsExplicitInstantiationDeclaration) 14944 DefineVTable = false; 14945 } 14946 14947 // The exception specifications for all virtual members may be needed even 14948 // if we are not providing an authoritative form of the vtable in this TU. 14949 // We may choose to emit it available_externally anyway. 14950 if (!DefineVTable) { 14951 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14952 continue; 14953 } 14954 14955 // Mark all of the virtual members of this class as referenced, so 14956 // that we can build a vtable. Then, tell the AST consumer that a 14957 // vtable for this class is required. 14958 DefinedAnything = true; 14959 MarkVirtualMembersReferenced(Loc, Class); 14960 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 14961 if (VTablesUsed[Canonical]) 14962 Consumer.HandleVTable(Class); 14963 14964 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14965 // no key function or the key function is inlined. Don't warn in C++ ABIs 14966 // that lack key functions, since the user won't be able to make one. 14967 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14968 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14969 const FunctionDecl *KeyFunctionDef = nullptr; 14970 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14971 KeyFunctionDef->isInlined())) { 14972 Diag(Class->getLocation(), 14973 ClassTSK == TSK_ExplicitInstantiationDefinition 14974 ? diag::warn_weak_template_vtable 14975 : diag::warn_weak_vtable) 14976 << Class; 14977 } 14978 } 14979 } 14980 VTableUses.clear(); 14981 14982 return DefinedAnything; 14983 } 14984 14985 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14986 const CXXRecordDecl *RD) { 14987 for (const auto *I : RD->methods()) 14988 if (I->isVirtual() && !I->isPure()) 14989 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14990 } 14991 14992 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14993 const CXXRecordDecl *RD) { 14994 // Mark all functions which will appear in RD's vtable as used. 14995 CXXFinalOverriderMap FinalOverriders; 14996 RD->getFinalOverriders(FinalOverriders); 14997 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14998 E = FinalOverriders.end(); 14999 I != E; ++I) { 15000 for (OverridingMethods::const_iterator OI = I->second.begin(), 15001 OE = I->second.end(); 15002 OI != OE; ++OI) { 15003 assert(OI->second.size() > 0 && "no final overrider"); 15004 CXXMethodDecl *Overrider = OI->second.front().Method; 15005 15006 // C++ [basic.def.odr]p2: 15007 // [...] A virtual member function is used if it is not pure. [...] 15008 if (!Overrider->isPure()) 15009 MarkFunctionReferenced(Loc, Overrider); 15010 } 15011 } 15012 15013 // Only classes that have virtual bases need a VTT. 15014 if (RD->getNumVBases() == 0) 15015 return; 15016 15017 for (const auto &I : RD->bases()) { 15018 const CXXRecordDecl *Base = 15019 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15020 if (Base->getNumVBases() == 0) 15021 continue; 15022 MarkVirtualMembersReferenced(Loc, Base); 15023 } 15024 } 15025 15026 /// SetIvarInitializers - This routine builds initialization ASTs for the 15027 /// Objective-C implementation whose ivars need be initialized. 15028 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15029 if (!getLangOpts().CPlusPlus) 15030 return; 15031 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15032 SmallVector<ObjCIvarDecl*, 8> ivars; 15033 CollectIvarsToConstructOrDestruct(OID, ivars); 15034 if (ivars.empty()) 15035 return; 15036 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15037 for (unsigned i = 0; i < ivars.size(); i++) { 15038 FieldDecl *Field = ivars[i]; 15039 if (Field->isInvalidDecl()) 15040 continue; 15041 15042 CXXCtorInitializer *Member; 15043 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15044 InitializationKind InitKind = 15045 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15046 15047 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15048 ExprResult MemberInit = 15049 InitSeq.Perform(*this, InitEntity, InitKind, None); 15050 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15051 // Note, MemberInit could actually come back empty if no initialization 15052 // is required (e.g., because it would call a trivial default constructor) 15053 if (!MemberInit.get() || MemberInit.isInvalid()) 15054 continue; 15055 15056 Member = 15057 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15058 SourceLocation(), 15059 MemberInit.getAs<Expr>(), 15060 SourceLocation()); 15061 AllToInit.push_back(Member); 15062 15063 // Be sure that the destructor is accessible and is marked as referenced. 15064 if (const RecordType *RecordTy = 15065 Context.getBaseElementType(Field->getType()) 15066 ->getAs<RecordType>()) { 15067 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15068 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15069 MarkFunctionReferenced(Field->getLocation(), Destructor); 15070 CheckDestructorAccess(Field->getLocation(), Destructor, 15071 PDiag(diag::err_access_dtor_ivar) 15072 << Context.getBaseElementType(Field->getType())); 15073 } 15074 } 15075 } 15076 ObjCImplementation->setIvarInitializers(Context, 15077 AllToInit.data(), AllToInit.size()); 15078 } 15079 } 15080 15081 static 15082 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15083 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15084 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15085 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15086 Sema &S) { 15087 if (Ctor->isInvalidDecl()) 15088 return; 15089 15090 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15091 15092 // Target may not be determinable yet, for instance if this is a dependent 15093 // call in an uninstantiated template. 15094 if (Target) { 15095 const FunctionDecl *FNTarget = nullptr; 15096 (void)Target->hasBody(FNTarget); 15097 Target = const_cast<CXXConstructorDecl*>( 15098 cast_or_null<CXXConstructorDecl>(FNTarget)); 15099 } 15100 15101 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15102 // Avoid dereferencing a null pointer here. 15103 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15104 15105 if (!Current.insert(Canonical).second) 15106 return; 15107 15108 // We know that beyond here, we aren't chaining into a cycle. 15109 if (!Target || !Target->isDelegatingConstructor() || 15110 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15111 Valid.insert(Current.begin(), Current.end()); 15112 Current.clear(); 15113 // We've hit a cycle. 15114 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15115 Current.count(TCanonical)) { 15116 // If we haven't diagnosed this cycle yet, do so now. 15117 if (!Invalid.count(TCanonical)) { 15118 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15119 diag::warn_delegating_ctor_cycle) 15120 << Ctor; 15121 15122 // Don't add a note for a function delegating directly to itself. 15123 if (TCanonical != Canonical) 15124 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15125 15126 CXXConstructorDecl *C = Target; 15127 while (C->getCanonicalDecl() != Canonical) { 15128 const FunctionDecl *FNTarget = nullptr; 15129 (void)C->getTargetConstructor()->hasBody(FNTarget); 15130 assert(FNTarget && "Ctor cycle through bodiless function"); 15131 15132 C = const_cast<CXXConstructorDecl*>( 15133 cast<CXXConstructorDecl>(FNTarget)); 15134 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15135 } 15136 } 15137 15138 Invalid.insert(Current.begin(), Current.end()); 15139 Current.clear(); 15140 } else { 15141 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15142 } 15143 } 15144 15145 15146 void Sema::CheckDelegatingCtorCycles() { 15147 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15148 15149 for (DelegatingCtorDeclsType::iterator 15150 I = DelegatingCtorDecls.begin(ExternalSource), 15151 E = DelegatingCtorDecls.end(); 15152 I != E; ++I) 15153 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15154 15155 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15156 (*CI)->setInvalidDecl(); 15157 } 15158 15159 namespace { 15160 /// AST visitor that finds references to the 'this' expression. 15161 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15162 Sema &S; 15163 15164 public: 15165 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15166 15167 bool VisitCXXThisExpr(CXXThisExpr *E) { 15168 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15169 << E->isImplicit(); 15170 return false; 15171 } 15172 }; 15173 } 15174 15175 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15176 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15177 if (!TSInfo) 15178 return false; 15179 15180 TypeLoc TL = TSInfo->getTypeLoc(); 15181 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15182 if (!ProtoTL) 15183 return false; 15184 15185 // C++11 [expr.prim.general]p3: 15186 // [The expression this] shall not appear before the optional 15187 // cv-qualifier-seq and it shall not appear within the declaration of a 15188 // static member function (although its type and value category are defined 15189 // within a static member function as they are within a non-static member 15190 // function). [ Note: this is because declaration matching does not occur 15191 // until the complete declarator is known. - end note ] 15192 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15193 FindCXXThisExpr Finder(*this); 15194 15195 // If the return type came after the cv-qualifier-seq, check it now. 15196 if (Proto->hasTrailingReturn() && 15197 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15198 return true; 15199 15200 // Check the exception specification. 15201 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15202 return true; 15203 15204 return checkThisInStaticMemberFunctionAttributes(Method); 15205 } 15206 15207 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15208 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15209 if (!TSInfo) 15210 return false; 15211 15212 TypeLoc TL = TSInfo->getTypeLoc(); 15213 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15214 if (!ProtoTL) 15215 return false; 15216 15217 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15218 FindCXXThisExpr Finder(*this); 15219 15220 switch (Proto->getExceptionSpecType()) { 15221 case EST_Unparsed: 15222 case EST_Uninstantiated: 15223 case EST_Unevaluated: 15224 case EST_BasicNoexcept: 15225 case EST_DynamicNone: 15226 case EST_MSAny: 15227 case EST_None: 15228 break; 15229 15230 case EST_DependentNoexcept: 15231 case EST_NoexceptFalse: 15232 case EST_NoexceptTrue: 15233 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15234 return true; 15235 LLVM_FALLTHROUGH; 15236 15237 case EST_Dynamic: 15238 for (const auto &E : Proto->exceptions()) { 15239 if (!Finder.TraverseType(E)) 15240 return true; 15241 } 15242 break; 15243 } 15244 15245 return false; 15246 } 15247 15248 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15249 FindCXXThisExpr Finder(*this); 15250 15251 // Check attributes. 15252 for (const auto *A : Method->attrs()) { 15253 // FIXME: This should be emitted by tblgen. 15254 Expr *Arg = nullptr; 15255 ArrayRef<Expr *> Args; 15256 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15257 Arg = G->getArg(); 15258 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15259 Arg = G->getArg(); 15260 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15261 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15262 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15263 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15264 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15265 Arg = ETLF->getSuccessValue(); 15266 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15267 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15268 Arg = STLF->getSuccessValue(); 15269 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15270 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15271 Arg = LR->getArg(); 15272 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15273 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15274 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15275 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15276 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15277 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15278 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15279 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15280 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15281 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15282 15283 if (Arg && !Finder.TraverseStmt(Arg)) 15284 return true; 15285 15286 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15287 if (!Finder.TraverseStmt(Args[I])) 15288 return true; 15289 } 15290 } 15291 15292 return false; 15293 } 15294 15295 void Sema::checkExceptionSpecification( 15296 bool IsTopLevel, ExceptionSpecificationType EST, 15297 ArrayRef<ParsedType> DynamicExceptions, 15298 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15299 SmallVectorImpl<QualType> &Exceptions, 15300 FunctionProtoType::ExceptionSpecInfo &ESI) { 15301 Exceptions.clear(); 15302 ESI.Type = EST; 15303 if (EST == EST_Dynamic) { 15304 Exceptions.reserve(DynamicExceptions.size()); 15305 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15306 // FIXME: Preserve type source info. 15307 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15308 15309 if (IsTopLevel) { 15310 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15311 collectUnexpandedParameterPacks(ET, Unexpanded); 15312 if (!Unexpanded.empty()) { 15313 DiagnoseUnexpandedParameterPacks( 15314 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15315 Unexpanded); 15316 continue; 15317 } 15318 } 15319 15320 // Check that the type is valid for an exception spec, and 15321 // drop it if not. 15322 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15323 Exceptions.push_back(ET); 15324 } 15325 ESI.Exceptions = Exceptions; 15326 return; 15327 } 15328 15329 if (isComputedNoexcept(EST)) { 15330 assert((NoexceptExpr->isTypeDependent() || 15331 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15332 Context.BoolTy) && 15333 "Parser should have made sure that the expression is boolean"); 15334 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15335 ESI.Type = EST_BasicNoexcept; 15336 return; 15337 } 15338 15339 ESI.NoexceptExpr = NoexceptExpr; 15340 return; 15341 } 15342 } 15343 15344 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15345 ExceptionSpecificationType EST, 15346 SourceRange SpecificationRange, 15347 ArrayRef<ParsedType> DynamicExceptions, 15348 ArrayRef<SourceRange> DynamicExceptionRanges, 15349 Expr *NoexceptExpr) { 15350 if (!MethodD) 15351 return; 15352 15353 // Dig out the method we're referring to. 15354 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15355 MethodD = FunTmpl->getTemplatedDecl(); 15356 15357 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15358 if (!Method) 15359 return; 15360 15361 // Check the exception specification. 15362 llvm::SmallVector<QualType, 4> Exceptions; 15363 FunctionProtoType::ExceptionSpecInfo ESI; 15364 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15365 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15366 ESI); 15367 15368 // Update the exception specification on the function type. 15369 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15370 15371 if (Method->isStatic()) 15372 checkThisInStaticMemberFunctionExceptionSpec(Method); 15373 15374 if (Method->isVirtual()) { 15375 // Check overrides, which we previously had to delay. 15376 for (const CXXMethodDecl *O : Method->overridden_methods()) 15377 CheckOverridingFunctionExceptionSpec(Method, O); 15378 } 15379 } 15380 15381 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15382 /// 15383 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15384 SourceLocation DeclStart, 15385 Declarator &D, Expr *BitWidth, 15386 InClassInitStyle InitStyle, 15387 AccessSpecifier AS, 15388 AttributeList *MSPropertyAttr) { 15389 IdentifierInfo *II = D.getIdentifier(); 15390 if (!II) { 15391 Diag(DeclStart, diag::err_anonymous_property); 15392 return nullptr; 15393 } 15394 SourceLocation Loc = D.getIdentifierLoc(); 15395 15396 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15397 QualType T = TInfo->getType(); 15398 if (getLangOpts().CPlusPlus) { 15399 CheckExtraCXXDefaultArguments(D); 15400 15401 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15402 UPPC_DataMemberType)) { 15403 D.setInvalidType(); 15404 T = Context.IntTy; 15405 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15406 } 15407 } 15408 15409 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15410 15411 if (D.getDeclSpec().isInlineSpecified()) 15412 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15413 << getLangOpts().CPlusPlus17; 15414 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15415 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15416 diag::err_invalid_thread) 15417 << DeclSpec::getSpecifierName(TSCS); 15418 15419 // Check to see if this name was declared as a member previously 15420 NamedDecl *PrevDecl = nullptr; 15421 LookupResult Previous(*this, II, Loc, LookupMemberName, 15422 ForVisibleRedeclaration); 15423 LookupName(Previous, S); 15424 switch (Previous.getResultKind()) { 15425 case LookupResult::Found: 15426 case LookupResult::FoundUnresolvedValue: 15427 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15428 break; 15429 15430 case LookupResult::FoundOverloaded: 15431 PrevDecl = Previous.getRepresentativeDecl(); 15432 break; 15433 15434 case LookupResult::NotFound: 15435 case LookupResult::NotFoundInCurrentInstantiation: 15436 case LookupResult::Ambiguous: 15437 break; 15438 } 15439 15440 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15441 // Maybe we will complain about the shadowed template parameter. 15442 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15443 // Just pretend that we didn't see the previous declaration. 15444 PrevDecl = nullptr; 15445 } 15446 15447 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15448 PrevDecl = nullptr; 15449 15450 SourceLocation TSSL = D.getLocStart(); 15451 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 15452 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15453 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15454 ProcessDeclAttributes(TUScope, NewPD, D); 15455 NewPD->setAccess(AS); 15456 15457 if (NewPD->isInvalidDecl()) 15458 Record->setInvalidDecl(); 15459 15460 if (D.getDeclSpec().isModulePrivateSpecified()) 15461 NewPD->setModulePrivate(); 15462 15463 if (NewPD->isInvalidDecl() && PrevDecl) { 15464 // Don't introduce NewFD into scope; there's already something 15465 // with the same name in the same scope. 15466 } else if (II) { 15467 PushOnScopeChains(NewPD, S); 15468 } else 15469 Record->addDecl(NewPD); 15470 15471 return NewPD; 15472 } 15473