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/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/DeclVisitor.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/RecursiveASTVisitor.h" 26 #include "clang/AST/StmtVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/AST/TypeOrdering.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 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 (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 216 EEnd = Proto->exception_end(); 217 E != EEnd; ++E) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 219 Exceptions.push_back(*E); 220 } 221 222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249 } 250 251 bool 252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.takeAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295 } 296 297 /// ActOnParamDefaultArgument - Check whether the default argument 298 /// provided for a function parameter is well-formed. If so, attach it 299 /// to the parameter declaration. 300 void 301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // Check that the default argument is well-formed 324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 325 if (DefaultArgChecker.Visit(DefaultArg)) { 326 Param->setInvalidDecl(); 327 return; 328 } 329 330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 331 } 332 333 /// ActOnParamUnparsedDefaultArgument - We've seen a default 334 /// argument for a function parameter, but we can't parse it yet 335 /// because we're inside a class definition. Note that this default 336 /// argument will be parsed later. 337 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 338 SourceLocation EqualLoc, 339 SourceLocation ArgLoc) { 340 if (!param) 341 return; 342 343 ParmVarDecl *Param = cast<ParmVarDecl>(param); 344 Param->setUnparsedDefaultArg(); 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346 } 347 348 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349 /// the default argument for the parameter param failed. 350 void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 Param->setInvalidDecl(); 356 UnparsedDefaultArgLocs.erase(Param); 357 } 358 359 /// CheckExtraCXXDefaultArguments - Check for any extra default 360 /// arguments in the declarator, which is not a function declaration 361 /// or definition and therefore is not permitted to have default 362 /// arguments. This routine should be invoked for every declarator 363 /// that is not a function declaration or definition. 364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 384 ++argIdx) { 385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.Params[argIdx].DefaultArgTokens = 0; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(0); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403 } 404 405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414 } 415 416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417 /// function, once we already know that they have the same 418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419 /// error, false otherwise. 420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 NamedDecl *ND = Old; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->getLexicalDeclContext(); 455 if (!ScopeDC->isFunctionOrMethod()) 456 ScopeDC = New->getDeclContext(); 457 if (S && !isDeclInScope(ND, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 464 if (OldParamHasDfl && NewParamHasDfl) { 465 466 unsigned DiagDefaultParamID = 467 diag::err_param_default_argument_redefinition; 468 469 // MSVC accepts that default parameters be redefined for member functions 470 // of template class. The new default parameter's value is ignored. 471 Invalid = true; 472 if (getLangOpts().MicrosoftExt) { 473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 474 if (MD && MD->getParent()->getDescribedClassTemplate()) { 475 // Merge the old default argument into the new parameter. 476 NewParam->setHasInheritedDefaultArg(); 477 if (OldParam->hasUninstantiatedDefaultArg()) 478 NewParam->setUninstantiatedDefaultArg( 479 OldParam->getUninstantiatedDefaultArg()); 480 else 481 NewParam->setDefaultArg(OldParam->getInit()); 482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 483 Invalid = false; 484 } 485 } 486 487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 488 // hint here. Alternatively, we could walk the type-source information 489 // for NewParam to find the last source location in the type... but it 490 // isn't worth the effort right now. This is the kind of test case that 491 // is hard to get right: 492 // int f(int); 493 // void g(int (*fp)(int) = f); 494 // void g(int (*fp)(int) = &f); 495 Diag(NewParam->getLocation(), DiagDefaultParamID) 496 << NewParam->getDefaultArgRange(); 497 498 // Look for the function declaration where the default argument was 499 // actually written, which may be a declaration prior to Old. 500 for (FunctionDecl *Older = Old->getPreviousDecl(); 501 Older; Older = Older->getPreviousDecl()) { 502 if (!Older->getParamDecl(p)->hasDefaultArg()) 503 break; 504 505 OldParam = Older->getParamDecl(p); 506 } 507 508 Diag(OldParam->getLocation(), diag::note_previous_definition) 509 << OldParam->getDefaultArgRange(); 510 } else if (OldParamHasDfl) { 511 // Merge the old default argument into the new parameter. 512 // It's important to use getInit() here; getDefaultArg() 513 // strips off any top-level ExprWithCleanups. 514 NewParam->setHasInheritedDefaultArg(); 515 if (OldParam->hasUninstantiatedDefaultArg()) 516 NewParam->setUninstantiatedDefaultArg( 517 OldParam->getUninstantiatedDefaultArg()); 518 else 519 NewParam->setDefaultArg(OldParam->getInit()); 520 } else if (NewParamHasDfl) { 521 if (New->getDescribedFunctionTemplate()) { 522 // Paragraph 4, quoted above, only applies to non-template functions. 523 Diag(NewParam->getLocation(), 524 diag::err_param_default_argument_template_redecl) 525 << NewParam->getDefaultArgRange(); 526 Diag(Old->getLocation(), diag::note_template_prev_declaration) 527 << false; 528 } else if (New->getTemplateSpecializationKind() 529 != TSK_ImplicitInstantiation && 530 New->getTemplateSpecializationKind() != TSK_Undeclared) { 531 // C++ [temp.expr.spec]p21: 532 // Default function arguments shall not be specified in a declaration 533 // or a definition for one of the following explicit specializations: 534 // - the explicit specialization of a function template; 535 // - the explicit specialization of a member function template; 536 // - the explicit specialization of a member function of a class 537 // template where the class template specialization to which the 538 // member function specialization belongs is implicitly 539 // instantiated. 540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 542 << New->getDeclName() 543 << NewParam->getDefaultArgRange(); 544 } else if (New->getDeclContext()->isDependentContext()) { 545 // C++ [dcl.fct.default]p6 (DR217): 546 // Default arguments for a member function of a class template shall 547 // be specified on the initial declaration of the member function 548 // within the class template. 549 // 550 // Reading the tea leaves a bit in DR217 and its reference to DR205 551 // leads me to the conclusion that one cannot add default function 552 // arguments for an out-of-line definition of a member function of a 553 // dependent type. 554 int WhichKind = 2; 555 if (CXXRecordDecl *Record 556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 557 if (Record->getDescribedClassTemplate()) 558 WhichKind = 0; 559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 560 WhichKind = 1; 561 else 562 WhichKind = 2; 563 } 564 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_member_template_redecl) 567 << WhichKind 568 << NewParam->getDefaultArgRange(); 569 } 570 } 571 } 572 573 // DR1344: If a default argument is added outside a class definition and that 574 // default argument makes the function a special member function, the program 575 // is ill-formed. This can only happen for constructors. 576 if (isa<CXXConstructorDecl>(New) && 577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 580 if (NewSM != OldSM) { 581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 582 assert(NewParam->hasDefaultArg()); 583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 584 << NewParam->getDefaultArgRange() << NewSM; 585 Diag(Old->getLocation(), diag::note_previous_declaration); 586 } 587 } 588 589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 590 // template has a constexpr specifier then all its declarations shall 591 // contain the constexpr specifier. 592 if (New->isConstexpr() != Old->isConstexpr()) { 593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 594 << New << New->isConstexpr(); 595 Diag(Old->getLocation(), diag::note_previous_declaration); 596 Invalid = true; 597 } 598 599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 600 // argument expression, that declaration shall be a definition and shall be 601 // the only declaration of the function or function template in the 602 // translation unit. 603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 604 functionDeclHasDefaultArgument(Old)) { 605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 606 Diag(Old->getLocation(), diag::note_previous_declaration); 607 Invalid = true; 608 } 609 610 if (CheckEquivalentExceptionSpec(Old, New)) 611 Invalid = true; 612 613 return Invalid; 614 } 615 616 /// \brief Merge the exception specifications of two variable declarations. 617 /// 618 /// This is called when there's a redeclaration of a VarDecl. The function 619 /// checks if the redeclaration might have an exception specification and 620 /// validates compatibility and merges the specs if necessary. 621 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 622 // Shortcut if exceptions are disabled. 623 if (!getLangOpts().CXXExceptions) 624 return; 625 626 assert(Context.hasSameType(New->getType(), Old->getType()) && 627 "Should only be called if types are otherwise the same."); 628 629 QualType NewType = New->getType(); 630 QualType OldType = Old->getType(); 631 632 // We're only interested in pointers and references to functions, as well 633 // as pointers to member functions. 634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 635 NewType = R->getPointeeType(); 636 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 637 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 638 NewType = P->getPointeeType(); 639 OldType = OldType->getAs<PointerType>()->getPointeeType(); 640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 641 NewType = M->getPointeeType(); 642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 643 } 644 645 if (!NewType->isFunctionProtoType()) 646 return; 647 648 // There's lots of special cases for functions. For function pointers, system 649 // libraries are hopefully not as broken so that we don't need these 650 // workarounds. 651 if (CheckEquivalentExceptionSpec( 652 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 653 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 654 New->setInvalidDecl(); 655 } 656 } 657 658 /// CheckCXXDefaultArguments - Verify that the default arguments for a 659 /// function declaration are well-formed according to C++ 660 /// [dcl.fct.default]. 661 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 662 unsigned NumParams = FD->getNumParams(); 663 unsigned p; 664 665 // Find first parameter with a default argument 666 for (p = 0; p < NumParams; ++p) { 667 ParmVarDecl *Param = FD->getParamDecl(p); 668 if (Param->hasDefaultArg()) 669 break; 670 } 671 672 // C++ [dcl.fct.default]p4: 673 // In a given function declaration, all parameters 674 // subsequent to a parameter with a default argument shall 675 // have default arguments supplied in this or previous 676 // declarations. A default argument shall not be redefined 677 // by a later declaration (not even to the same value). 678 unsigned LastMissingDefaultArg = 0; 679 for (; p < NumParams; ++p) { 680 ParmVarDecl *Param = FD->getParamDecl(p); 681 if (!Param->hasDefaultArg()) { 682 if (Param->isInvalidDecl()) 683 /* We already complained about this parameter. */; 684 else if (Param->getIdentifier()) 685 Diag(Param->getLocation(), 686 diag::err_param_default_argument_missing_name) 687 << Param->getIdentifier(); 688 else 689 Diag(Param->getLocation(), 690 diag::err_param_default_argument_missing); 691 692 LastMissingDefaultArg = p; 693 } 694 } 695 696 if (LastMissingDefaultArg > 0) { 697 // Some default arguments were missing. Clear out all of the 698 // default arguments up to (and including) the last missing 699 // default argument, so that we leave the function parameters 700 // in a semantically valid state. 701 for (p = 0; p <= LastMissingDefaultArg; ++p) { 702 ParmVarDecl *Param = FD->getParamDecl(p); 703 if (Param->hasDefaultArg()) { 704 Param->setDefaultArg(0); 705 } 706 } 707 } 708 } 709 710 // CheckConstexprParameterTypes - Check whether a function's parameter types 711 // are all literal types. If so, return true. If not, produce a suitable 712 // diagnostic and return false. 713 static bool CheckConstexprParameterTypes(Sema &SemaRef, 714 const FunctionDecl *FD) { 715 unsigned ArgIndex = 0; 716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 717 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 718 e = FT->param_type_end(); 719 i != e; ++i, ++ArgIndex) { 720 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 721 SourceLocation ParamLoc = PD->getLocation(); 722 if (!(*i)->isDependentType() && 723 SemaRef.RequireLiteralType(ParamLoc, *i, 724 diag::err_constexpr_non_literal_param, 725 ArgIndex+1, PD->getSourceRange(), 726 isa<CXXConstructorDecl>(FD))) 727 return false; 728 } 729 return true; 730 } 731 732 /// \brief Get diagnostic %select index for tag kind for 733 /// record diagnostic message. 734 /// WARNING: Indexes apply to particular diagnostics only! 735 /// 736 /// \returns diagnostic %select index. 737 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 738 switch (Tag) { 739 case TTK_Struct: return 0; 740 case TTK_Interface: return 1; 741 case TTK_Class: return 2; 742 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 743 } 744 } 745 746 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 747 // the requirements of a constexpr function definition or a constexpr 748 // constructor definition. If so, return true. If not, produce appropriate 749 // diagnostics and return false. 750 // 751 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 752 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 753 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 754 if (MD && MD->isInstance()) { 755 // C++11 [dcl.constexpr]p4: 756 // The definition of a constexpr constructor shall satisfy the following 757 // constraints: 758 // - the class shall not have any virtual base classes; 759 const CXXRecordDecl *RD = MD->getParent(); 760 if (RD->getNumVBases()) { 761 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 762 << isa<CXXConstructorDecl>(NewFD) 763 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 764 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 765 E = RD->vbases_end(); I != E; ++I) 766 Diag(I->getLocStart(), 767 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 768 return false; 769 } 770 } 771 772 if (!isa<CXXConstructorDecl>(NewFD)) { 773 // C++11 [dcl.constexpr]p3: 774 // The definition of a constexpr function shall satisfy the following 775 // constraints: 776 // - it shall not be virtual; 777 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 778 if (Method && Method->isVirtual()) { 779 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 780 781 // If it's not obvious why this function is virtual, find an overridden 782 // function which uses the 'virtual' keyword. 783 const CXXMethodDecl *WrittenVirtual = Method; 784 while (!WrittenVirtual->isVirtualAsWritten()) 785 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 786 if (WrittenVirtual != Method) 787 Diag(WrittenVirtual->getLocation(), 788 diag::note_overridden_virtual_function); 789 return false; 790 } 791 792 // - its return type shall be a literal type; 793 QualType RT = NewFD->getReturnType(); 794 if (!RT->isDependentType() && 795 RequireLiteralType(NewFD->getLocation(), RT, 796 diag::err_constexpr_non_literal_return)) 797 return false; 798 } 799 800 // - each of its parameter types shall be a literal type; 801 if (!CheckConstexprParameterTypes(*this, NewFD)) 802 return false; 803 804 return true; 805 } 806 807 /// Check the given declaration statement is legal within a constexpr function 808 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 809 /// 810 /// \return true if the body is OK (maybe only as an extension), false if we 811 /// have diagnosed a problem. 812 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 813 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 814 // C++11 [dcl.constexpr]p3 and p4: 815 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 816 // contain only 817 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 818 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 819 switch ((*DclIt)->getKind()) { 820 case Decl::StaticAssert: 821 case Decl::Using: 822 case Decl::UsingShadow: 823 case Decl::UsingDirective: 824 case Decl::UnresolvedUsingTypename: 825 case Decl::UnresolvedUsingValue: 826 // - static_assert-declarations 827 // - using-declarations, 828 // - using-directives, 829 continue; 830 831 case Decl::Typedef: 832 case Decl::TypeAlias: { 833 // - typedef declarations and alias-declarations that do not define 834 // classes or enumerations, 835 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 836 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 837 // Don't allow variably-modified types in constexpr functions. 838 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 839 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 840 << TL.getSourceRange() << TL.getType() 841 << isa<CXXConstructorDecl>(Dcl); 842 return false; 843 } 844 continue; 845 } 846 847 case Decl::Enum: 848 case Decl::CXXRecord: 849 // C++1y allows types to be defined, not just declared. 850 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 851 SemaRef.Diag(DS->getLocStart(), 852 SemaRef.getLangOpts().CPlusPlus1y 853 ? diag::warn_cxx11_compat_constexpr_type_definition 854 : diag::ext_constexpr_type_definition) 855 << isa<CXXConstructorDecl>(Dcl); 856 continue; 857 858 case Decl::EnumConstant: 859 case Decl::IndirectField: 860 case Decl::ParmVar: 861 // These can only appear with other declarations which are banned in 862 // C++11 and permitted in C++1y, so ignore them. 863 continue; 864 865 case Decl::Var: { 866 // C++1y [dcl.constexpr]p3 allows anything except: 867 // a definition of a variable of non-literal type or of static or 868 // thread storage duration or for which no initialization is performed. 869 VarDecl *VD = cast<VarDecl>(*DclIt); 870 if (VD->isThisDeclarationADefinition()) { 871 if (VD->isStaticLocal()) { 872 SemaRef.Diag(VD->getLocation(), 873 diag::err_constexpr_local_var_static) 874 << isa<CXXConstructorDecl>(Dcl) 875 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 876 return false; 877 } 878 if (!VD->getType()->isDependentType() && 879 SemaRef.RequireLiteralType( 880 VD->getLocation(), VD->getType(), 881 diag::err_constexpr_local_var_non_literal_type, 882 isa<CXXConstructorDecl>(Dcl))) 883 return false; 884 if (!VD->getType()->isDependentType() && 885 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 886 SemaRef.Diag(VD->getLocation(), 887 diag::err_constexpr_local_var_no_init) 888 << isa<CXXConstructorDecl>(Dcl); 889 return false; 890 } 891 } 892 SemaRef.Diag(VD->getLocation(), 893 SemaRef.getLangOpts().CPlusPlus1y 894 ? diag::warn_cxx11_compat_constexpr_local_var 895 : diag::ext_constexpr_local_var) 896 << isa<CXXConstructorDecl>(Dcl); 897 continue; 898 } 899 900 case Decl::NamespaceAlias: 901 case Decl::Function: 902 // These are disallowed in C++11 and permitted in C++1y. Allow them 903 // everywhere as an extension. 904 if (!Cxx1yLoc.isValid()) 905 Cxx1yLoc = DS->getLocStart(); 906 continue; 907 908 default: 909 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 910 << isa<CXXConstructorDecl>(Dcl); 911 return false; 912 } 913 } 914 915 return true; 916 } 917 918 /// Check that the given field is initialized within a constexpr constructor. 919 /// 920 /// \param Dcl The constexpr constructor being checked. 921 /// \param Field The field being checked. This may be a member of an anonymous 922 /// struct or union nested within the class being checked. 923 /// \param Inits All declarations, including anonymous struct/union members and 924 /// indirect members, for which any initialization was provided. 925 /// \param Diagnosed Set to true if an error is produced. 926 static void CheckConstexprCtorInitializer(Sema &SemaRef, 927 const FunctionDecl *Dcl, 928 FieldDecl *Field, 929 llvm::SmallSet<Decl*, 16> &Inits, 930 bool &Diagnosed) { 931 if (Field->isInvalidDecl()) 932 return; 933 934 if (Field->isUnnamedBitfield()) 935 return; 936 937 // Anonymous unions with no variant members and empty anonymous structs do not 938 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 939 // indirect fields don't need initializing. 940 if (Field->isAnonymousStructOrUnion() && 941 (Field->getType()->isUnionType() 942 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 943 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 944 return; 945 946 if (!Inits.count(Field)) { 947 if (!Diagnosed) { 948 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 949 Diagnosed = true; 950 } 951 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 952 } else if (Field->isAnonymousStructOrUnion()) { 953 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 954 for (auto *I : RD->fields()) 955 // If an anonymous union contains an anonymous struct of which any member 956 // is initialized, all members must be initialized. 957 if (!RD->isUnion() || Inits.count(I)) 958 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 959 } 960 } 961 962 /// Check the provided statement is allowed in a constexpr function 963 /// definition. 964 static bool 965 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 966 SmallVectorImpl<SourceLocation> &ReturnStmts, 967 SourceLocation &Cxx1yLoc) { 968 // - its function-body shall be [...] a compound-statement that contains only 969 switch (S->getStmtClass()) { 970 case Stmt::NullStmtClass: 971 // - null statements, 972 return true; 973 974 case Stmt::DeclStmtClass: 975 // - static_assert-declarations 976 // - using-declarations, 977 // - using-directives, 978 // - typedef declarations and alias-declarations that do not define 979 // classes or enumerations, 980 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 981 return false; 982 return true; 983 984 case Stmt::ReturnStmtClass: 985 // - and exactly one return statement; 986 if (isa<CXXConstructorDecl>(Dcl)) { 987 // C++1y allows return statements in constexpr constructors. 988 if (!Cxx1yLoc.isValid()) 989 Cxx1yLoc = S->getLocStart(); 990 return true; 991 } 992 993 ReturnStmts.push_back(S->getLocStart()); 994 return true; 995 996 case Stmt::CompoundStmtClass: { 997 // C++1y allows compound-statements. 998 if (!Cxx1yLoc.isValid()) 999 Cxx1yLoc = S->getLocStart(); 1000 1001 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1002 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 1003 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1004 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 1005 Cxx1yLoc)) 1006 return false; 1007 } 1008 return true; 1009 } 1010 1011 case Stmt::AttributedStmtClass: 1012 if (!Cxx1yLoc.isValid()) 1013 Cxx1yLoc = S->getLocStart(); 1014 return true; 1015 1016 case Stmt::IfStmtClass: { 1017 // C++1y allows if-statements. 1018 if (!Cxx1yLoc.isValid()) 1019 Cxx1yLoc = S->getLocStart(); 1020 1021 IfStmt *If = cast<IfStmt>(S); 1022 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1023 Cxx1yLoc)) 1024 return false; 1025 if (If->getElse() && 1026 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1027 Cxx1yLoc)) 1028 return false; 1029 return true; 1030 } 1031 1032 case Stmt::WhileStmtClass: 1033 case Stmt::DoStmtClass: 1034 case Stmt::ForStmtClass: 1035 case Stmt::CXXForRangeStmtClass: 1036 case Stmt::ContinueStmtClass: 1037 // C++1y allows all of these. We don't allow them as extensions in C++11, 1038 // because they don't make sense without variable mutation. 1039 if (!SemaRef.getLangOpts().CPlusPlus1y) 1040 break; 1041 if (!Cxx1yLoc.isValid()) 1042 Cxx1yLoc = S->getLocStart(); 1043 for (Stmt::child_range Children = S->children(); Children; ++Children) 1044 if (*Children && 1045 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1046 Cxx1yLoc)) 1047 return false; 1048 return true; 1049 1050 case Stmt::SwitchStmtClass: 1051 case Stmt::CaseStmtClass: 1052 case Stmt::DefaultStmtClass: 1053 case Stmt::BreakStmtClass: 1054 // C++1y allows switch-statements, and since they don't need variable 1055 // mutation, we can reasonably allow them in C++11 as an extension. 1056 if (!Cxx1yLoc.isValid()) 1057 Cxx1yLoc = S->getLocStart(); 1058 for (Stmt::child_range Children = S->children(); Children; ++Children) 1059 if (*Children && 1060 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1061 Cxx1yLoc)) 1062 return false; 1063 return true; 1064 1065 default: 1066 if (!isa<Expr>(S)) 1067 break; 1068 1069 // C++1y allows expression-statements. 1070 if (!Cxx1yLoc.isValid()) 1071 Cxx1yLoc = S->getLocStart(); 1072 return true; 1073 } 1074 1075 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1076 << isa<CXXConstructorDecl>(Dcl); 1077 return false; 1078 } 1079 1080 /// Check the body for the given constexpr function declaration only contains 1081 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1082 /// 1083 /// \return true if the body is OK, false if we have diagnosed a problem. 1084 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1085 if (isa<CXXTryStmt>(Body)) { 1086 // C++11 [dcl.constexpr]p3: 1087 // The definition of a constexpr function shall satisfy the following 1088 // constraints: [...] 1089 // - its function-body shall be = delete, = default, or a 1090 // compound-statement 1091 // 1092 // C++11 [dcl.constexpr]p4: 1093 // In the definition of a constexpr constructor, [...] 1094 // - its function-body shall not be a function-try-block; 1095 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1096 << isa<CXXConstructorDecl>(Dcl); 1097 return false; 1098 } 1099 1100 SmallVector<SourceLocation, 4> ReturnStmts; 1101 1102 // - its function-body shall be [...] a compound-statement that contains only 1103 // [... list of cases ...] 1104 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1105 SourceLocation Cxx1yLoc; 1106 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1107 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1108 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1109 return false; 1110 } 1111 1112 if (Cxx1yLoc.isValid()) 1113 Diag(Cxx1yLoc, 1114 getLangOpts().CPlusPlus1y 1115 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1116 : diag::ext_constexpr_body_invalid_stmt) 1117 << isa<CXXConstructorDecl>(Dcl); 1118 1119 if (const CXXConstructorDecl *Constructor 1120 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1121 const CXXRecordDecl *RD = Constructor->getParent(); 1122 // DR1359: 1123 // - every non-variant non-static data member and base class sub-object 1124 // shall be initialized; 1125 // DR1460: 1126 // - if the class is a union having variant members, exactly one of them 1127 // shall be initialized; 1128 if (RD->isUnion()) { 1129 if (Constructor->getNumCtorInitializers() == 0 && 1130 RD->hasVariantMembers()) { 1131 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1132 return false; 1133 } 1134 } else if (!Constructor->isDependentContext() && 1135 !Constructor->isDelegatingConstructor()) { 1136 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1137 1138 // Skip detailed checking if we have enough initializers, and we would 1139 // allow at most one initializer per member. 1140 bool AnyAnonStructUnionMembers = false; 1141 unsigned Fields = 0; 1142 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1143 E = RD->field_end(); I != E; ++I, ++Fields) { 1144 if (I->isAnonymousStructOrUnion()) { 1145 AnyAnonStructUnionMembers = true; 1146 break; 1147 } 1148 } 1149 // DR1460: 1150 // - if the class is a union-like class, but is not a union, for each of 1151 // its anonymous union members having variant members, exactly one of 1152 // them shall be initialized; 1153 if (AnyAnonStructUnionMembers || 1154 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1155 // Check initialization of non-static data members. Base classes are 1156 // always initialized so do not need to be checked. Dependent bases 1157 // might not have initializers in the member initializer list. 1158 llvm::SmallSet<Decl*, 16> Inits; 1159 for (CXXConstructorDecl::init_const_iterator 1160 I = Constructor->init_begin(), E = Constructor->init_end(); 1161 I != E; ++I) { 1162 if (FieldDecl *FD = (*I)->getMember()) 1163 Inits.insert(FD); 1164 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1165 Inits.insert(ID->chain_begin(), ID->chain_end()); 1166 } 1167 1168 bool Diagnosed = false; 1169 for (auto *I : RD->fields()) 1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1171 if (Diagnosed) 1172 return false; 1173 } 1174 } 1175 } else { 1176 if (ReturnStmts.empty()) { 1177 // C++1y doesn't require constexpr functions to contain a 'return' 1178 // statement. We still do, unless the return type is void, because 1179 // otherwise if there's no return statement, the function cannot 1180 // be used in a core constant expression. 1181 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType(); 1182 Diag(Dcl->getLocation(), 1183 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1184 : diag::err_constexpr_body_no_return); 1185 return OK; 1186 } 1187 if (ReturnStmts.size() > 1) { 1188 Diag(ReturnStmts.back(), 1189 getLangOpts().CPlusPlus1y 1190 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1191 : diag::ext_constexpr_body_multiple_return); 1192 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1193 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1194 } 1195 } 1196 1197 // C++11 [dcl.constexpr]p5: 1198 // if no function argument values exist such that the function invocation 1199 // substitution would produce a constant expression, the program is 1200 // ill-formed; no diagnostic required. 1201 // C++11 [dcl.constexpr]p3: 1202 // - every constructor call and implicit conversion used in initializing the 1203 // return value shall be one of those allowed in a constant expression. 1204 // C++11 [dcl.constexpr]p4: 1205 // - every constructor involved in initializing non-static data members and 1206 // base class sub-objects shall be a constexpr constructor. 1207 SmallVector<PartialDiagnosticAt, 8> Diags; 1208 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1209 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1210 << isa<CXXConstructorDecl>(Dcl); 1211 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1212 Diag(Diags[I].first, Diags[I].second); 1213 // Don't return false here: we allow this for compatibility in 1214 // system headers. 1215 } 1216 1217 return true; 1218 } 1219 1220 /// isCurrentClassName - Determine whether the identifier II is the 1221 /// name of the class type currently being defined. In the case of 1222 /// nested classes, this will only return true if II is the name of 1223 /// the innermost class. 1224 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1225 const CXXScopeSpec *SS) { 1226 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1227 1228 CXXRecordDecl *CurDecl; 1229 if (SS && SS->isSet() && !SS->isInvalid()) { 1230 DeclContext *DC = computeDeclContext(*SS, true); 1231 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1232 } else 1233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1234 1235 if (CurDecl && CurDecl->getIdentifier()) 1236 return &II == CurDecl->getIdentifier(); 1237 return false; 1238 } 1239 1240 /// \brief Determine whether the identifier II is a typo for the name of 1241 /// the class type currently being defined. If so, update it to the identifier 1242 /// that should have been used. 1243 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1244 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1245 1246 if (!getLangOpts().SpellChecking) 1247 return false; 1248 1249 CXXRecordDecl *CurDecl; 1250 if (SS && SS->isSet() && !SS->isInvalid()) { 1251 DeclContext *DC = computeDeclContext(*SS, true); 1252 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1253 } else 1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1255 1256 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1257 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1258 < II->getLength()) { 1259 II = CurDecl->getIdentifier(); 1260 return true; 1261 } 1262 1263 return false; 1264 } 1265 1266 /// \brief Determine whether the given class is a base class of the given 1267 /// class, including looking at dependent bases. 1268 static bool findCircularInheritance(const CXXRecordDecl *Class, 1269 const CXXRecordDecl *Current) { 1270 SmallVector<const CXXRecordDecl*, 8> Queue; 1271 1272 Class = Class->getCanonicalDecl(); 1273 while (true) { 1274 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1275 E = Current->bases_end(); 1276 I != E; ++I) { 1277 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1278 if (!Base) 1279 continue; 1280 1281 Base = Base->getDefinition(); 1282 if (!Base) 1283 continue; 1284 1285 if (Base->getCanonicalDecl() == Class) 1286 return true; 1287 1288 Queue.push_back(Base); 1289 } 1290 1291 if (Queue.empty()) 1292 return false; 1293 1294 Current = Queue.pop_back_val(); 1295 } 1296 1297 return false; 1298 } 1299 1300 /// \brief Check the validity of a C++ base class specifier. 1301 /// 1302 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1303 /// and returns NULL otherwise. 1304 CXXBaseSpecifier * 1305 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1306 SourceRange SpecifierRange, 1307 bool Virtual, AccessSpecifier Access, 1308 TypeSourceInfo *TInfo, 1309 SourceLocation EllipsisLoc) { 1310 QualType BaseType = TInfo->getType(); 1311 1312 // C++ [class.union]p1: 1313 // A union shall not have base classes. 1314 if (Class->isUnion()) { 1315 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1316 << SpecifierRange; 1317 return 0; 1318 } 1319 1320 if (EllipsisLoc.isValid() && 1321 !TInfo->getType()->containsUnexpandedParameterPack()) { 1322 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1323 << TInfo->getTypeLoc().getSourceRange(); 1324 EllipsisLoc = SourceLocation(); 1325 } 1326 1327 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1328 1329 if (BaseType->isDependentType()) { 1330 // Make sure that we don't have circular inheritance among our dependent 1331 // bases. For non-dependent bases, the check for completeness below handles 1332 // this. 1333 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1334 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1335 ((BaseDecl = BaseDecl->getDefinition()) && 1336 findCircularInheritance(Class, BaseDecl))) { 1337 Diag(BaseLoc, diag::err_circular_inheritance) 1338 << BaseType << Context.getTypeDeclType(Class); 1339 1340 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1341 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1342 << BaseType; 1343 1344 return 0; 1345 } 1346 } 1347 1348 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1349 Class->getTagKind() == TTK_Class, 1350 Access, TInfo, EllipsisLoc); 1351 } 1352 1353 // Base specifiers must be record types. 1354 if (!BaseType->isRecordType()) { 1355 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1356 return 0; 1357 } 1358 1359 // C++ [class.union]p1: 1360 // A union shall not be used as a base class. 1361 if (BaseType->isUnionType()) { 1362 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1363 return 0; 1364 } 1365 1366 // C++ [class.derived]p2: 1367 // The class-name in a base-specifier shall not be an incompletely 1368 // defined class. 1369 if (RequireCompleteType(BaseLoc, BaseType, 1370 diag::err_incomplete_base_class, SpecifierRange)) { 1371 Class->setInvalidDecl(); 1372 return 0; 1373 } 1374 1375 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1376 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1377 assert(BaseDecl && "Record type has no declaration"); 1378 BaseDecl = BaseDecl->getDefinition(); 1379 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1380 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1381 assert(CXXBaseDecl && "Base type is not a C++ type"); 1382 1383 // A class which contains a flexible array member is not suitable for use as a 1384 // base class: 1385 // - If the layout determines that a base comes before another base, 1386 // the flexible array member would index into the subsequent base. 1387 // - If the layout determines that base comes before the derived class, 1388 // the flexible array member would index into the derived class. 1389 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1390 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1391 << CXXBaseDecl->getDeclName(); 1392 return 0; 1393 } 1394 1395 // C++ [class]p3: 1396 // If a class is marked final and it appears as a base-type-specifier in 1397 // base-clause, the program is ill-formed. 1398 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1399 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1400 << CXXBaseDecl->getDeclName() 1401 << FA->isSpelledAsSealed(); 1402 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1403 << CXXBaseDecl->getDeclName(); 1404 return 0; 1405 } 1406 1407 if (BaseDecl->isInvalidDecl()) 1408 Class->setInvalidDecl(); 1409 1410 // Create the base specifier. 1411 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1412 Class->getTagKind() == TTK_Class, 1413 Access, TInfo, EllipsisLoc); 1414 } 1415 1416 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1417 /// one entry in the base class list of a class specifier, for 1418 /// example: 1419 /// class foo : public bar, virtual private baz { 1420 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1421 BaseResult 1422 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1423 ParsedAttributes &Attributes, 1424 bool Virtual, AccessSpecifier Access, 1425 ParsedType basetype, SourceLocation BaseLoc, 1426 SourceLocation EllipsisLoc) { 1427 if (!classdecl) 1428 return true; 1429 1430 AdjustDeclIfTemplate(classdecl); 1431 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1432 if (!Class) 1433 return true; 1434 1435 // We do not support any C++11 attributes on base-specifiers yet. 1436 // Diagnose any attributes we see. 1437 if (!Attributes.empty()) { 1438 for (AttributeList *Attr = Attributes.getList(); Attr; 1439 Attr = Attr->getNext()) { 1440 if (Attr->isInvalid() || 1441 Attr->getKind() == AttributeList::IgnoredAttribute) 1442 continue; 1443 Diag(Attr->getLoc(), 1444 Attr->getKind() == AttributeList::UnknownAttribute 1445 ? diag::warn_unknown_attribute_ignored 1446 : diag::err_base_specifier_attribute) 1447 << Attr->getName(); 1448 } 1449 } 1450 1451 TypeSourceInfo *TInfo = 0; 1452 GetTypeFromParser(basetype, &TInfo); 1453 1454 if (EllipsisLoc.isInvalid() && 1455 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1456 UPPC_BaseType)) 1457 return true; 1458 1459 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1460 Virtual, Access, TInfo, 1461 EllipsisLoc)) 1462 return BaseSpec; 1463 else 1464 Class->setInvalidDecl(); 1465 1466 return true; 1467 } 1468 1469 /// \brief Performs the actual work of attaching the given base class 1470 /// specifiers to a C++ class. 1471 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1472 unsigned NumBases) { 1473 if (NumBases == 0) 1474 return false; 1475 1476 // Used to keep track of which base types we have already seen, so 1477 // that we can properly diagnose redundant direct base types. Note 1478 // that the key is always the unqualified canonical type of the base 1479 // class. 1480 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1481 1482 // Copy non-redundant base specifiers into permanent storage. 1483 unsigned NumGoodBases = 0; 1484 bool Invalid = false; 1485 for (unsigned idx = 0; idx < NumBases; ++idx) { 1486 QualType NewBaseType 1487 = Context.getCanonicalType(Bases[idx]->getType()); 1488 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1489 1490 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1491 if (KnownBase) { 1492 // C++ [class.mi]p3: 1493 // A class shall not be specified as a direct base class of a 1494 // derived class more than once. 1495 Diag(Bases[idx]->getLocStart(), 1496 diag::err_duplicate_base_class) 1497 << KnownBase->getType() 1498 << Bases[idx]->getSourceRange(); 1499 1500 // Delete the duplicate base class specifier; we're going to 1501 // overwrite its pointer later. 1502 Context.Deallocate(Bases[idx]); 1503 1504 Invalid = true; 1505 } else { 1506 // Okay, add this new base class. 1507 KnownBase = Bases[idx]; 1508 Bases[NumGoodBases++] = Bases[idx]; 1509 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1510 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1511 if (Class->isInterface() && 1512 (!RD->isInterface() || 1513 KnownBase->getAccessSpecifier() != AS_public)) { 1514 // The Microsoft extension __interface does not permit bases that 1515 // are not themselves public interfaces. 1516 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1517 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1518 << RD->getSourceRange(); 1519 Invalid = true; 1520 } 1521 if (RD->hasAttr<WeakAttr>()) 1522 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1523 } 1524 } 1525 } 1526 1527 // Attach the remaining base class specifiers to the derived class. 1528 Class->setBases(Bases, NumGoodBases); 1529 1530 // Delete the remaining (good) base class specifiers, since their 1531 // data has been copied into the CXXRecordDecl. 1532 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1533 Context.Deallocate(Bases[idx]); 1534 1535 return Invalid; 1536 } 1537 1538 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1539 /// class, after checking whether there are any duplicate base 1540 /// classes. 1541 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1542 unsigned NumBases) { 1543 if (!ClassDecl || !Bases || !NumBases) 1544 return; 1545 1546 AdjustDeclIfTemplate(ClassDecl); 1547 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1548 } 1549 1550 /// \brief Determine whether the type \p Derived is a C++ class that is 1551 /// derived from the type \p Base. 1552 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1553 if (!getLangOpts().CPlusPlus) 1554 return false; 1555 1556 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1557 if (!DerivedRD) 1558 return false; 1559 1560 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1561 if (!BaseRD) 1562 return false; 1563 1564 // If either the base or the derived type is invalid, don't try to 1565 // check whether one is derived from the other. 1566 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1567 return false; 1568 1569 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1570 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1571 } 1572 1573 /// \brief Determine whether the type \p Derived is a C++ class that is 1574 /// derived from the type \p Base. 1575 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1576 if (!getLangOpts().CPlusPlus) 1577 return false; 1578 1579 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1580 if (!DerivedRD) 1581 return false; 1582 1583 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1584 if (!BaseRD) 1585 return false; 1586 1587 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1588 } 1589 1590 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1591 CXXCastPath &BasePathArray) { 1592 assert(BasePathArray.empty() && "Base path array must be empty!"); 1593 assert(Paths.isRecordingPaths() && "Must record paths!"); 1594 1595 const CXXBasePath &Path = Paths.front(); 1596 1597 // We first go backward and check if we have a virtual base. 1598 // FIXME: It would be better if CXXBasePath had the base specifier for 1599 // the nearest virtual base. 1600 unsigned Start = 0; 1601 for (unsigned I = Path.size(); I != 0; --I) { 1602 if (Path[I - 1].Base->isVirtual()) { 1603 Start = I - 1; 1604 break; 1605 } 1606 } 1607 1608 // Now add all bases. 1609 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1610 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1611 } 1612 1613 /// \brief Determine whether the given base path includes a virtual 1614 /// base class. 1615 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1616 for (CXXCastPath::const_iterator B = BasePath.begin(), 1617 BEnd = BasePath.end(); 1618 B != BEnd; ++B) 1619 if ((*B)->isVirtual()) 1620 return true; 1621 1622 return false; 1623 } 1624 1625 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1626 /// conversion (where Derived and Base are class types) is 1627 /// well-formed, meaning that the conversion is unambiguous (and 1628 /// that all of the base classes are accessible). Returns true 1629 /// and emits a diagnostic if the code is ill-formed, returns false 1630 /// otherwise. Loc is the location where this routine should point to 1631 /// if there is an error, and Range is the source range to highlight 1632 /// if there is an error. 1633 bool 1634 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1635 unsigned InaccessibleBaseID, 1636 unsigned AmbigiousBaseConvID, 1637 SourceLocation Loc, SourceRange Range, 1638 DeclarationName Name, 1639 CXXCastPath *BasePath) { 1640 // First, determine whether the path from Derived to Base is 1641 // ambiguous. This is slightly more expensive than checking whether 1642 // the Derived to Base conversion exists, because here we need to 1643 // explore multiple paths to determine if there is an ambiguity. 1644 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1645 /*DetectVirtual=*/false); 1646 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1647 assert(DerivationOkay && 1648 "Can only be used with a derived-to-base conversion"); 1649 (void)DerivationOkay; 1650 1651 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1652 if (InaccessibleBaseID) { 1653 // Check that the base class can be accessed. 1654 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1655 InaccessibleBaseID)) { 1656 case AR_inaccessible: 1657 return true; 1658 case AR_accessible: 1659 case AR_dependent: 1660 case AR_delayed: 1661 break; 1662 } 1663 } 1664 1665 // Build a base path if necessary. 1666 if (BasePath) 1667 BuildBasePathArray(Paths, *BasePath); 1668 return false; 1669 } 1670 1671 if (AmbigiousBaseConvID) { 1672 // We know that the derived-to-base conversion is ambiguous, and 1673 // we're going to produce a diagnostic. Perform the derived-to-base 1674 // search just one more time to compute all of the possible paths so 1675 // that we can print them out. This is more expensive than any of 1676 // the previous derived-to-base checks we've done, but at this point 1677 // performance isn't as much of an issue. 1678 Paths.clear(); 1679 Paths.setRecordingPaths(true); 1680 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1681 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1682 (void)StillOkay; 1683 1684 // Build up a textual representation of the ambiguous paths, e.g., 1685 // D -> B -> A, that will be used to illustrate the ambiguous 1686 // conversions in the diagnostic. We only print one of the paths 1687 // to each base class subobject. 1688 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1689 1690 Diag(Loc, AmbigiousBaseConvID) 1691 << Derived << Base << PathDisplayStr << Range << Name; 1692 } 1693 return true; 1694 } 1695 1696 bool 1697 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1698 SourceLocation Loc, SourceRange Range, 1699 CXXCastPath *BasePath, 1700 bool IgnoreAccess) { 1701 return CheckDerivedToBaseConversion(Derived, Base, 1702 IgnoreAccess ? 0 1703 : diag::err_upcast_to_inaccessible_base, 1704 diag::err_ambiguous_derived_to_base_conv, 1705 Loc, Range, DeclarationName(), 1706 BasePath); 1707 } 1708 1709 1710 /// @brief Builds a string representing ambiguous paths from a 1711 /// specific derived class to different subobjects of the same base 1712 /// class. 1713 /// 1714 /// This function builds a string that can be used in error messages 1715 /// to show the different paths that one can take through the 1716 /// inheritance hierarchy to go from the derived class to different 1717 /// subobjects of a base class. The result looks something like this: 1718 /// @code 1719 /// struct D -> struct B -> struct A 1720 /// struct D -> struct C -> struct A 1721 /// @endcode 1722 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1723 std::string PathDisplayStr; 1724 std::set<unsigned> DisplayedPaths; 1725 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1726 Path != Paths.end(); ++Path) { 1727 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1728 // We haven't displayed a path to this particular base 1729 // class subobject yet. 1730 PathDisplayStr += "\n "; 1731 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1732 for (CXXBasePath::const_iterator Element = Path->begin(); 1733 Element != Path->end(); ++Element) 1734 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1735 } 1736 } 1737 1738 return PathDisplayStr; 1739 } 1740 1741 //===----------------------------------------------------------------------===// 1742 // C++ class member Handling 1743 //===----------------------------------------------------------------------===// 1744 1745 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1746 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1747 SourceLocation ASLoc, 1748 SourceLocation ColonLoc, 1749 AttributeList *Attrs) { 1750 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1751 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1752 ASLoc, ColonLoc); 1753 CurContext->addHiddenDecl(ASDecl); 1754 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1755 } 1756 1757 /// CheckOverrideControl - Check C++11 override control semantics. 1758 void Sema::CheckOverrideControl(NamedDecl *D) { 1759 if (D->isInvalidDecl()) 1760 return; 1761 1762 // We only care about "override" and "final" declarations. 1763 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1764 return; 1765 1766 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1767 1768 // We can't check dependent instance methods. 1769 if (MD && MD->isInstance() && 1770 (MD->getParent()->hasAnyDependentBases() || 1771 MD->getType()->isDependentType())) 1772 return; 1773 1774 if (MD && !MD->isVirtual()) { 1775 // If we have a non-virtual method, check if if hides a virtual method. 1776 // (In that case, it's most likely the method has the wrong type.) 1777 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1778 FindHiddenVirtualMethods(MD, OverloadedMethods); 1779 1780 if (!OverloadedMethods.empty()) { 1781 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1782 Diag(OA->getLocation(), 1783 diag::override_keyword_hides_virtual_member_function) 1784 << "override" << (OverloadedMethods.size() > 1); 1785 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1786 Diag(FA->getLocation(), 1787 diag::override_keyword_hides_virtual_member_function) 1788 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1789 << (OverloadedMethods.size() > 1); 1790 } 1791 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1792 MD->setInvalidDecl(); 1793 return; 1794 } 1795 // Fall through into the general case diagnostic. 1796 // FIXME: We might want to attempt typo correction here. 1797 } 1798 1799 if (!MD || !MD->isVirtual()) { 1800 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1801 Diag(OA->getLocation(), 1802 diag::override_keyword_only_allowed_on_virtual_member_functions) 1803 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1804 D->dropAttr<OverrideAttr>(); 1805 } 1806 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1807 Diag(FA->getLocation(), 1808 diag::override_keyword_only_allowed_on_virtual_member_functions) 1809 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1810 << FixItHint::CreateRemoval(FA->getLocation()); 1811 D->dropAttr<FinalAttr>(); 1812 } 1813 return; 1814 } 1815 1816 // C++11 [class.virtual]p5: 1817 // If a virtual function is marked with the virt-specifier override and 1818 // does not override a member function of a base class, the program is 1819 // ill-formed. 1820 bool HasOverriddenMethods = 1821 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1822 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1823 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1824 << MD->getDeclName(); 1825 } 1826 1827 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1828 /// function overrides a virtual member function marked 'final', according to 1829 /// C++11 [class.virtual]p4. 1830 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1831 const CXXMethodDecl *Old) { 1832 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1833 if (!FA) 1834 return false; 1835 1836 Diag(New->getLocation(), diag::err_final_function_overridden) 1837 << New->getDeclName() 1838 << FA->isSpelledAsSealed(); 1839 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1840 return true; 1841 } 1842 1843 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1844 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1845 // FIXME: Destruction of ObjC lifetime types has side-effects. 1846 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1847 return !RD->isCompleteDefinition() || 1848 !RD->hasTrivialDefaultConstructor() || 1849 !RD->hasTrivialDestructor(); 1850 return false; 1851 } 1852 1853 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1854 for (AttributeList* it = list; it != 0; it = it->getNext()) 1855 if (it->isDeclspecPropertyAttribute()) 1856 return it; 1857 return 0; 1858 } 1859 1860 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1861 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1862 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1863 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1864 /// present (but parsing it has been deferred). 1865 NamedDecl * 1866 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1867 MultiTemplateParamsArg TemplateParameterLists, 1868 Expr *BW, const VirtSpecifiers &VS, 1869 InClassInitStyle InitStyle) { 1870 const DeclSpec &DS = D.getDeclSpec(); 1871 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1872 DeclarationName Name = NameInfo.getName(); 1873 SourceLocation Loc = NameInfo.getLoc(); 1874 1875 // For anonymous bitfields, the location should point to the type. 1876 if (Loc.isInvalid()) 1877 Loc = D.getLocStart(); 1878 1879 Expr *BitWidth = static_cast<Expr*>(BW); 1880 1881 assert(isa<CXXRecordDecl>(CurContext)); 1882 assert(!DS.isFriendSpecified()); 1883 1884 bool isFunc = D.isDeclarationOfFunction(); 1885 1886 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1887 // The Microsoft extension __interface only permits public member functions 1888 // and prohibits constructors, destructors, operators, non-public member 1889 // functions, static methods and data members. 1890 unsigned InvalidDecl; 1891 bool ShowDeclName = true; 1892 if (!isFunc) 1893 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1894 else if (AS != AS_public) 1895 InvalidDecl = 2; 1896 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1897 InvalidDecl = 3; 1898 else switch (Name.getNameKind()) { 1899 case DeclarationName::CXXConstructorName: 1900 InvalidDecl = 4; 1901 ShowDeclName = false; 1902 break; 1903 1904 case DeclarationName::CXXDestructorName: 1905 InvalidDecl = 5; 1906 ShowDeclName = false; 1907 break; 1908 1909 case DeclarationName::CXXOperatorName: 1910 case DeclarationName::CXXConversionFunctionName: 1911 InvalidDecl = 6; 1912 break; 1913 1914 default: 1915 InvalidDecl = 0; 1916 break; 1917 } 1918 1919 if (InvalidDecl) { 1920 if (ShowDeclName) 1921 Diag(Loc, diag::err_invalid_member_in_interface) 1922 << (InvalidDecl-1) << Name; 1923 else 1924 Diag(Loc, diag::err_invalid_member_in_interface) 1925 << (InvalidDecl-1) << ""; 1926 return 0; 1927 } 1928 } 1929 1930 // C++ 9.2p6: A member shall not be declared to have automatic storage 1931 // duration (auto, register) or with the extern storage-class-specifier. 1932 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1933 // data members and cannot be applied to names declared const or static, 1934 // and cannot be applied to reference members. 1935 switch (DS.getStorageClassSpec()) { 1936 case DeclSpec::SCS_unspecified: 1937 case DeclSpec::SCS_typedef: 1938 case DeclSpec::SCS_static: 1939 break; 1940 case DeclSpec::SCS_mutable: 1941 if (isFunc) { 1942 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1943 1944 // FIXME: It would be nicer if the keyword was ignored only for this 1945 // declarator. Otherwise we could get follow-up errors. 1946 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1947 } 1948 break; 1949 default: 1950 Diag(DS.getStorageClassSpecLoc(), 1951 diag::err_storageclass_invalid_for_member); 1952 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1953 break; 1954 } 1955 1956 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1957 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1958 !isFunc); 1959 1960 if (DS.isConstexprSpecified() && isInstField) { 1961 SemaDiagnosticBuilder B = 1962 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1963 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1964 if (InitStyle == ICIS_NoInit) { 1965 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1966 D.getMutableDeclSpec().ClearConstexprSpec(); 1967 const char *PrevSpec; 1968 unsigned DiagID; 1969 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1970 PrevSpec, DiagID, getLangOpts()); 1971 (void)Failed; 1972 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1973 } else { 1974 B << 1; 1975 const char *PrevSpec; 1976 unsigned DiagID; 1977 if (D.getMutableDeclSpec().SetStorageClassSpec( 1978 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 1979 Context.getPrintingPolicy())) { 1980 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1981 "This is the only DeclSpec that should fail to be applied"); 1982 B << 1; 1983 } else { 1984 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1985 isInstField = false; 1986 } 1987 } 1988 } 1989 1990 NamedDecl *Member; 1991 if (isInstField) { 1992 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1993 1994 // Data members must have identifiers for names. 1995 if (!Name.isIdentifier()) { 1996 Diag(Loc, diag::err_bad_variable_name) 1997 << Name; 1998 return 0; 1999 } 2000 2001 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2002 2003 // Member field could not be with "template" keyword. 2004 // So TemplateParameterLists should be empty in this case. 2005 if (TemplateParameterLists.size()) { 2006 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2007 if (TemplateParams->size()) { 2008 // There is no such thing as a member field template. 2009 Diag(D.getIdentifierLoc(), diag::err_template_member) 2010 << II 2011 << SourceRange(TemplateParams->getTemplateLoc(), 2012 TemplateParams->getRAngleLoc()); 2013 } else { 2014 // There is an extraneous 'template<>' for this member. 2015 Diag(TemplateParams->getTemplateLoc(), 2016 diag::err_template_member_noparams) 2017 << II 2018 << SourceRange(TemplateParams->getTemplateLoc(), 2019 TemplateParams->getRAngleLoc()); 2020 } 2021 return 0; 2022 } 2023 2024 if (SS.isSet() && !SS.isInvalid()) { 2025 // The user provided a superfluous scope specifier inside a class 2026 // definition: 2027 // 2028 // class X { 2029 // int X::member; 2030 // }; 2031 if (DeclContext *DC = computeDeclContext(SS, false)) 2032 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2033 else 2034 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2035 << Name << SS.getRange(); 2036 2037 SS.clear(); 2038 } 2039 2040 AttributeList *MSPropertyAttr = 2041 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2042 if (MSPropertyAttr) { 2043 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2044 BitWidth, InitStyle, AS, MSPropertyAttr); 2045 if (!Member) 2046 return 0; 2047 isInstField = false; 2048 } else { 2049 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2050 BitWidth, InitStyle, AS); 2051 assert(Member && "HandleField never returns null"); 2052 } 2053 } else { 2054 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2055 2056 Member = HandleDeclarator(S, D, TemplateParameterLists); 2057 if (!Member) 2058 return 0; 2059 2060 // Non-instance-fields can't have a bitfield. 2061 if (BitWidth) { 2062 if (Member->isInvalidDecl()) { 2063 // don't emit another diagnostic. 2064 } else if (isa<VarDecl>(Member)) { 2065 // C++ 9.6p3: A bit-field shall not be a static member. 2066 // "static member 'A' cannot be a bit-field" 2067 Diag(Loc, diag::err_static_not_bitfield) 2068 << Name << BitWidth->getSourceRange(); 2069 } else if (isa<TypedefDecl>(Member)) { 2070 // "typedef member 'x' cannot be a bit-field" 2071 Diag(Loc, diag::err_typedef_not_bitfield) 2072 << Name << BitWidth->getSourceRange(); 2073 } else { 2074 // A function typedef ("typedef int f(); f a;"). 2075 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2076 Diag(Loc, diag::err_not_integral_type_bitfield) 2077 << Name << cast<ValueDecl>(Member)->getType() 2078 << BitWidth->getSourceRange(); 2079 } 2080 2081 BitWidth = 0; 2082 Member->setInvalidDecl(); 2083 } 2084 2085 Member->setAccess(AS); 2086 2087 // If we have declared a member function template or static data member 2088 // template, set the access of the templated declaration as well. 2089 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2090 FunTmpl->getTemplatedDecl()->setAccess(AS); 2091 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2092 VarTmpl->getTemplatedDecl()->setAccess(AS); 2093 } 2094 2095 if (VS.isOverrideSpecified()) 2096 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2097 if (VS.isFinalSpecified()) 2098 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2099 VS.isFinalSpelledSealed())); 2100 2101 if (VS.getLastLocation().isValid()) { 2102 // Update the end location of a method that has a virt-specifiers. 2103 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2104 MD->setRangeEnd(VS.getLastLocation()); 2105 } 2106 2107 CheckOverrideControl(Member); 2108 2109 assert((Name || isInstField) && "No identifier for non-field ?"); 2110 2111 if (isInstField) { 2112 FieldDecl *FD = cast<FieldDecl>(Member); 2113 FieldCollector->Add(FD); 2114 2115 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2116 FD->getLocation()) 2117 != DiagnosticsEngine::Ignored) { 2118 // Remember all explicit private FieldDecls that have a name, no side 2119 // effects and are not part of a dependent type declaration. 2120 if (!FD->isImplicit() && FD->getDeclName() && 2121 FD->getAccess() == AS_private && 2122 !FD->hasAttr<UnusedAttr>() && 2123 !FD->getParent()->isDependentContext() && 2124 !InitializationHasSideEffects(*FD)) 2125 UnusedPrivateFields.insert(FD); 2126 } 2127 } 2128 2129 return Member; 2130 } 2131 2132 namespace { 2133 class UninitializedFieldVisitor 2134 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2135 Sema &S; 2136 // List of Decls to generate a warning on. Also remove Decls that become 2137 // initialized. 2138 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2139 // If non-null, add a note to the warning pointing back to the constructor. 2140 const CXXConstructorDecl *Constructor; 2141 public: 2142 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2143 UninitializedFieldVisitor(Sema &S, 2144 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2145 const CXXConstructorDecl *Constructor) 2146 : Inherited(S.Context), S(S), Decls(Decls), 2147 Constructor(Constructor) { } 2148 2149 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2150 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2151 return; 2152 2153 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2154 // or union. 2155 MemberExpr *FieldME = ME; 2156 2157 Expr *Base = ME; 2158 while (isa<MemberExpr>(Base)) { 2159 ME = cast<MemberExpr>(Base); 2160 2161 if (isa<VarDecl>(ME->getMemberDecl())) 2162 return; 2163 2164 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2165 if (!FD->isAnonymousStructOrUnion()) 2166 FieldME = ME; 2167 2168 Base = ME->getBase(); 2169 } 2170 2171 if (!isa<CXXThisExpr>(Base)) 2172 return; 2173 2174 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2175 2176 if (!Decls.count(FoundVD)) 2177 return; 2178 2179 const bool IsReference = FoundVD->getType()->isReferenceType(); 2180 2181 // Prevent double warnings on use of unbounded references. 2182 if (IsReference != CheckReferenceOnly) 2183 return; 2184 2185 unsigned diag = IsReference 2186 ? diag::warn_reference_field_is_uninit 2187 : diag::warn_field_is_uninit; 2188 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2189 if (Constructor) 2190 S.Diag(Constructor->getLocation(), 2191 diag::note_uninit_in_this_constructor) 2192 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2193 2194 } 2195 2196 void HandleValue(Expr *E) { 2197 E = E->IgnoreParens(); 2198 2199 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2200 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2201 return; 2202 } 2203 2204 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2205 HandleValue(CO->getTrueExpr()); 2206 HandleValue(CO->getFalseExpr()); 2207 return; 2208 } 2209 2210 if (BinaryConditionalOperator *BCO = 2211 dyn_cast<BinaryConditionalOperator>(E)) { 2212 HandleValue(BCO->getCommon()); 2213 HandleValue(BCO->getFalseExpr()); 2214 return; 2215 } 2216 2217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2218 switch (BO->getOpcode()) { 2219 default: 2220 return; 2221 case(BO_PtrMemD): 2222 case(BO_PtrMemI): 2223 HandleValue(BO->getLHS()); 2224 return; 2225 case(BO_Comma): 2226 HandleValue(BO->getRHS()); 2227 return; 2228 } 2229 } 2230 } 2231 2232 void VisitMemberExpr(MemberExpr *ME) { 2233 // All uses of unbounded reference fields will warn. 2234 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2235 2236 Inherited::VisitMemberExpr(ME); 2237 } 2238 2239 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2240 if (E->getCastKind() == CK_LValueToRValue) 2241 HandleValue(E->getSubExpr()); 2242 2243 Inherited::VisitImplicitCastExpr(E); 2244 } 2245 2246 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2247 if (E->getConstructor()->isCopyConstructor()) 2248 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2249 if (ICE->getCastKind() == CK_NoOp) 2250 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2251 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2252 2253 Inherited::VisitCXXConstructExpr(E); 2254 } 2255 2256 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2257 Expr *Callee = E->getCallee(); 2258 if (isa<MemberExpr>(Callee)) 2259 HandleValue(Callee); 2260 2261 Inherited::VisitCXXMemberCallExpr(E); 2262 } 2263 2264 void VisitBinaryOperator(BinaryOperator *E) { 2265 // If a field assignment is detected, remove the field from the 2266 // uninitiailized field set. 2267 if (E->getOpcode() == BO_Assign) 2268 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2269 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2270 if (!FD->getType()->isReferenceType()) 2271 Decls.erase(FD); 2272 2273 Inherited::VisitBinaryOperator(E); 2274 } 2275 }; 2276 static void CheckInitExprContainsUninitializedFields( 2277 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2278 const CXXConstructorDecl *Constructor) { 2279 if (Decls.size() == 0) 2280 return; 2281 2282 if (!E) 2283 return; 2284 2285 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2286 E = Default->getExpr(); 2287 if (!E) 2288 return; 2289 // In class initializers will point to the constructor. 2290 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2291 } else { 2292 UninitializedFieldVisitor(S, Decls, 0).Visit(E); 2293 } 2294 } 2295 2296 // Diagnose value-uses of fields to initialize themselves, e.g. 2297 // foo(foo) 2298 // where foo is not also a parameter to the constructor. 2299 // Also diagnose across field uninitialized use such as 2300 // x(y), y(x) 2301 // TODO: implement -Wuninitialized and fold this into that framework. 2302 static void DiagnoseUninitializedFields( 2303 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2304 2305 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 2306 Constructor->getLocation()) 2307 == DiagnosticsEngine::Ignored) { 2308 return; 2309 } 2310 2311 if (Constructor->isInvalidDecl()) 2312 return; 2313 2314 const CXXRecordDecl *RD = Constructor->getParent(); 2315 2316 // Holds fields that are uninitialized. 2317 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2318 2319 // At the beginning, all fields are uninitialized. 2320 for (auto *I : RD->decls()) { 2321 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2322 UninitializedFields.insert(FD); 2323 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2324 UninitializedFields.insert(IFD->getAnonField()); 2325 } 2326 } 2327 2328 for (CXXConstructorDecl::init_const_iterator FieldInit = 2329 Constructor->init_begin(), 2330 FieldInitEnd = Constructor->init_end(); 2331 FieldInit != FieldInitEnd; ++FieldInit) { 2332 2333 Expr *InitExpr = (*FieldInit)->getInit(); 2334 2335 CheckInitExprContainsUninitializedFields( 2336 SemaRef, InitExpr, UninitializedFields, Constructor); 2337 2338 if (FieldDecl *Field = (*FieldInit)->getAnyMember()) 2339 UninitializedFields.erase(Field); 2340 } 2341 } 2342 } // namespace 2343 2344 /// \brief Enter a new C++ default initializer scope. After calling this, the 2345 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2346 /// parsing or instantiating the initializer failed. 2347 void Sema::ActOnStartCXXInClassMemberInitializer() { 2348 // Create a synthetic function scope to represent the call to the constructor 2349 // that notionally surrounds a use of this initializer. 2350 PushFunctionScope(); 2351 } 2352 2353 /// \brief This is invoked after parsing an in-class initializer for a 2354 /// non-static C++ class member, and after instantiating an in-class initializer 2355 /// in a class template. Such actions are deferred until the class is complete. 2356 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2357 SourceLocation InitLoc, 2358 Expr *InitExpr) { 2359 // Pop the notional constructor scope we created earlier. 2360 PopFunctionScopeInfo(0, D); 2361 2362 FieldDecl *FD = cast<FieldDecl>(D); 2363 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2364 "must set init style when field is created"); 2365 2366 if (!InitExpr) { 2367 FD->setInvalidDecl(); 2368 FD->removeInClassInitializer(); 2369 return; 2370 } 2371 2372 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2373 FD->setInvalidDecl(); 2374 FD->removeInClassInitializer(); 2375 return; 2376 } 2377 2378 ExprResult Init = InitExpr; 2379 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2380 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2381 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2382 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2383 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2384 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2385 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2386 if (Init.isInvalid()) { 2387 FD->setInvalidDecl(); 2388 return; 2389 } 2390 } 2391 2392 // C++11 [class.base.init]p7: 2393 // The initialization of each base and member constitutes a 2394 // full-expression. 2395 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2396 if (Init.isInvalid()) { 2397 FD->setInvalidDecl(); 2398 return; 2399 } 2400 2401 InitExpr = Init.release(); 2402 2403 FD->setInClassInitializer(InitExpr); 2404 } 2405 2406 /// \brief Find the direct and/or virtual base specifiers that 2407 /// correspond to the given base type, for use in base initialization 2408 /// within a constructor. 2409 static bool FindBaseInitializer(Sema &SemaRef, 2410 CXXRecordDecl *ClassDecl, 2411 QualType BaseType, 2412 const CXXBaseSpecifier *&DirectBaseSpec, 2413 const CXXBaseSpecifier *&VirtualBaseSpec) { 2414 // First, check for a direct base class. 2415 DirectBaseSpec = 0; 2416 for (CXXRecordDecl::base_class_const_iterator Base 2417 = ClassDecl->bases_begin(); 2418 Base != ClassDecl->bases_end(); ++Base) { 2419 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2420 // We found a direct base of this type. That's what we're 2421 // initializing. 2422 DirectBaseSpec = &*Base; 2423 break; 2424 } 2425 } 2426 2427 // Check for a virtual base class. 2428 // FIXME: We might be able to short-circuit this if we know in advance that 2429 // there are no virtual bases. 2430 VirtualBaseSpec = 0; 2431 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2432 // We haven't found a base yet; search the class hierarchy for a 2433 // virtual base class. 2434 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2435 /*DetectVirtual=*/false); 2436 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2437 BaseType, Paths)) { 2438 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2439 Path != Paths.end(); ++Path) { 2440 if (Path->back().Base->isVirtual()) { 2441 VirtualBaseSpec = Path->back().Base; 2442 break; 2443 } 2444 } 2445 } 2446 } 2447 2448 return DirectBaseSpec || VirtualBaseSpec; 2449 } 2450 2451 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2452 MemInitResult 2453 Sema::ActOnMemInitializer(Decl *ConstructorD, 2454 Scope *S, 2455 CXXScopeSpec &SS, 2456 IdentifierInfo *MemberOrBase, 2457 ParsedType TemplateTypeTy, 2458 const DeclSpec &DS, 2459 SourceLocation IdLoc, 2460 Expr *InitList, 2461 SourceLocation EllipsisLoc) { 2462 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2463 DS, IdLoc, InitList, 2464 EllipsisLoc); 2465 } 2466 2467 /// \brief Handle a C++ member initializer using parentheses syntax. 2468 MemInitResult 2469 Sema::ActOnMemInitializer(Decl *ConstructorD, 2470 Scope *S, 2471 CXXScopeSpec &SS, 2472 IdentifierInfo *MemberOrBase, 2473 ParsedType TemplateTypeTy, 2474 const DeclSpec &DS, 2475 SourceLocation IdLoc, 2476 SourceLocation LParenLoc, 2477 ArrayRef<Expr *> Args, 2478 SourceLocation RParenLoc, 2479 SourceLocation EllipsisLoc) { 2480 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2481 Args, RParenLoc); 2482 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2483 DS, IdLoc, List, EllipsisLoc); 2484 } 2485 2486 namespace { 2487 2488 // Callback to only accept typo corrections that can be a valid C++ member 2489 // intializer: either a non-static field member or a base class. 2490 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2491 public: 2492 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2493 : ClassDecl(ClassDecl) {} 2494 2495 bool ValidateCandidate(const TypoCorrection &candidate) override { 2496 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2497 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2498 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2499 return isa<TypeDecl>(ND); 2500 } 2501 return false; 2502 } 2503 2504 private: 2505 CXXRecordDecl *ClassDecl; 2506 }; 2507 2508 } 2509 2510 /// \brief Handle a C++ member initializer. 2511 MemInitResult 2512 Sema::BuildMemInitializer(Decl *ConstructorD, 2513 Scope *S, 2514 CXXScopeSpec &SS, 2515 IdentifierInfo *MemberOrBase, 2516 ParsedType TemplateTypeTy, 2517 const DeclSpec &DS, 2518 SourceLocation IdLoc, 2519 Expr *Init, 2520 SourceLocation EllipsisLoc) { 2521 if (!ConstructorD) 2522 return true; 2523 2524 AdjustDeclIfTemplate(ConstructorD); 2525 2526 CXXConstructorDecl *Constructor 2527 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2528 if (!Constructor) { 2529 // The user wrote a constructor initializer on a function that is 2530 // not a C++ constructor. Ignore the error for now, because we may 2531 // have more member initializers coming; we'll diagnose it just 2532 // once in ActOnMemInitializers. 2533 return true; 2534 } 2535 2536 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2537 2538 // C++ [class.base.init]p2: 2539 // Names in a mem-initializer-id are looked up in the scope of the 2540 // constructor's class and, if not found in that scope, are looked 2541 // up in the scope containing the constructor's definition. 2542 // [Note: if the constructor's class contains a member with the 2543 // same name as a direct or virtual base class of the class, a 2544 // mem-initializer-id naming the member or base class and composed 2545 // of a single identifier refers to the class member. A 2546 // mem-initializer-id for the hidden base class may be specified 2547 // using a qualified name. ] 2548 if (!SS.getScopeRep() && !TemplateTypeTy) { 2549 // Look for a member, first. 2550 DeclContext::lookup_result Result 2551 = ClassDecl->lookup(MemberOrBase); 2552 if (!Result.empty()) { 2553 ValueDecl *Member; 2554 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2555 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2556 if (EllipsisLoc.isValid()) 2557 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2558 << MemberOrBase 2559 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2560 2561 return BuildMemberInitializer(Member, Init, IdLoc); 2562 } 2563 } 2564 } 2565 // It didn't name a member, so see if it names a class. 2566 QualType BaseType; 2567 TypeSourceInfo *TInfo = 0; 2568 2569 if (TemplateTypeTy) { 2570 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2571 } else if (DS.getTypeSpecType() == TST_decltype) { 2572 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2573 } else { 2574 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2575 LookupParsedName(R, S, &SS); 2576 2577 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2578 if (!TyD) { 2579 if (R.isAmbiguous()) return true; 2580 2581 // We don't want access-control diagnostics here. 2582 R.suppressDiagnostics(); 2583 2584 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2585 bool NotUnknownSpecialization = false; 2586 DeclContext *DC = computeDeclContext(SS, false); 2587 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2588 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2589 2590 if (!NotUnknownSpecialization) { 2591 // When the scope specifier can refer to a member of an unknown 2592 // specialization, we take it as a type name. 2593 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2594 SS.getWithLocInContext(Context), 2595 *MemberOrBase, IdLoc); 2596 if (BaseType.isNull()) 2597 return true; 2598 2599 R.clear(); 2600 R.setLookupName(MemberOrBase); 2601 } 2602 } 2603 2604 // If no results were found, try to correct typos. 2605 TypoCorrection Corr; 2606 MemInitializerValidatorCCC Validator(ClassDecl); 2607 if (R.empty() && BaseType.isNull() && 2608 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2609 Validator, ClassDecl))) { 2610 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2611 // We have found a non-static data member with a similar 2612 // name to what was typed; complain and initialize that 2613 // member. 2614 diagnoseTypo(Corr, 2615 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2616 << MemberOrBase << true); 2617 return BuildMemberInitializer(Member, Init, IdLoc); 2618 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2619 const CXXBaseSpecifier *DirectBaseSpec; 2620 const CXXBaseSpecifier *VirtualBaseSpec; 2621 if (FindBaseInitializer(*this, ClassDecl, 2622 Context.getTypeDeclType(Type), 2623 DirectBaseSpec, VirtualBaseSpec)) { 2624 // We have found a direct or virtual base class with a 2625 // similar name to what was typed; complain and initialize 2626 // that base class. 2627 diagnoseTypo(Corr, 2628 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2629 << MemberOrBase << false, 2630 PDiag() /*Suppress note, we provide our own.*/); 2631 2632 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2633 : VirtualBaseSpec; 2634 Diag(BaseSpec->getLocStart(), 2635 diag::note_base_class_specified_here) 2636 << BaseSpec->getType() 2637 << BaseSpec->getSourceRange(); 2638 2639 TyD = Type; 2640 } 2641 } 2642 } 2643 2644 if (!TyD && BaseType.isNull()) { 2645 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2646 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2647 return true; 2648 } 2649 } 2650 2651 if (BaseType.isNull()) { 2652 BaseType = Context.getTypeDeclType(TyD); 2653 if (SS.isSet()) 2654 // FIXME: preserve source range information 2655 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2656 BaseType); 2657 } 2658 } 2659 2660 if (!TInfo) 2661 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2662 2663 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2664 } 2665 2666 /// Checks a member initializer expression for cases where reference (or 2667 /// pointer) members are bound to by-value parameters (or their addresses). 2668 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2669 Expr *Init, 2670 SourceLocation IdLoc) { 2671 QualType MemberTy = Member->getType(); 2672 2673 // We only handle pointers and references currently. 2674 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2675 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2676 return; 2677 2678 const bool IsPointer = MemberTy->isPointerType(); 2679 if (IsPointer) { 2680 if (const UnaryOperator *Op 2681 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2682 // The only case we're worried about with pointers requires taking the 2683 // address. 2684 if (Op->getOpcode() != UO_AddrOf) 2685 return; 2686 2687 Init = Op->getSubExpr(); 2688 } else { 2689 // We only handle address-of expression initializers for pointers. 2690 return; 2691 } 2692 } 2693 2694 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2695 // We only warn when referring to a non-reference parameter declaration. 2696 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2697 if (!Parameter || Parameter->getType()->isReferenceType()) 2698 return; 2699 2700 S.Diag(Init->getExprLoc(), 2701 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2702 : diag::warn_bind_ref_member_to_parameter) 2703 << Member << Parameter << Init->getSourceRange(); 2704 } else { 2705 // Other initializers are fine. 2706 return; 2707 } 2708 2709 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2710 << (unsigned)IsPointer; 2711 } 2712 2713 MemInitResult 2714 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2715 SourceLocation IdLoc) { 2716 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2717 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2718 assert((DirectMember || IndirectMember) && 2719 "Member must be a FieldDecl or IndirectFieldDecl"); 2720 2721 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2722 return true; 2723 2724 if (Member->isInvalidDecl()) 2725 return true; 2726 2727 MultiExprArg Args; 2728 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2729 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2730 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2731 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2732 } else { 2733 // Template instantiation doesn't reconstruct ParenListExprs for us. 2734 Args = Init; 2735 } 2736 2737 SourceRange InitRange = Init->getSourceRange(); 2738 2739 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2740 // Can't check initialization for a member of dependent type or when 2741 // any of the arguments are type-dependent expressions. 2742 DiscardCleanupsInEvaluationContext(); 2743 } else { 2744 bool InitList = false; 2745 if (isa<InitListExpr>(Init)) { 2746 InitList = true; 2747 Args = Init; 2748 } 2749 2750 // Initialize the member. 2751 InitializedEntity MemberEntity = 2752 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2753 : InitializedEntity::InitializeMember(IndirectMember, 0); 2754 InitializationKind Kind = 2755 InitList ? InitializationKind::CreateDirectList(IdLoc) 2756 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2757 InitRange.getEnd()); 2758 2759 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2760 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2761 if (MemberInit.isInvalid()) 2762 return true; 2763 2764 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2765 2766 // C++11 [class.base.init]p7: 2767 // The initialization of each base and member constitutes a 2768 // full-expression. 2769 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2770 if (MemberInit.isInvalid()) 2771 return true; 2772 2773 Init = MemberInit.get(); 2774 } 2775 2776 if (DirectMember) { 2777 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2778 InitRange.getBegin(), Init, 2779 InitRange.getEnd()); 2780 } else { 2781 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2782 InitRange.getBegin(), Init, 2783 InitRange.getEnd()); 2784 } 2785 } 2786 2787 MemInitResult 2788 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2789 CXXRecordDecl *ClassDecl) { 2790 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2791 if (!LangOpts.CPlusPlus11) 2792 return Diag(NameLoc, diag::err_delegating_ctor) 2793 << TInfo->getTypeLoc().getLocalSourceRange(); 2794 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2795 2796 bool InitList = true; 2797 MultiExprArg Args = Init; 2798 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2799 InitList = false; 2800 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2801 } 2802 2803 SourceRange InitRange = Init->getSourceRange(); 2804 // Initialize the object. 2805 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2806 QualType(ClassDecl->getTypeForDecl(), 0)); 2807 InitializationKind Kind = 2808 InitList ? InitializationKind::CreateDirectList(NameLoc) 2809 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2810 InitRange.getEnd()); 2811 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2812 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2813 Args, 0); 2814 if (DelegationInit.isInvalid()) 2815 return true; 2816 2817 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2818 "Delegating constructor with no target?"); 2819 2820 // C++11 [class.base.init]p7: 2821 // The initialization of each base and member constitutes a 2822 // full-expression. 2823 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2824 InitRange.getBegin()); 2825 if (DelegationInit.isInvalid()) 2826 return true; 2827 2828 // If we are in a dependent context, template instantiation will 2829 // perform this type-checking again. Just save the arguments that we 2830 // received in a ParenListExpr. 2831 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2832 // of the information that we have about the base 2833 // initializer. However, deconstructing the ASTs is a dicey process, 2834 // and this approach is far more likely to get the corner cases right. 2835 if (CurContext->isDependentContext()) 2836 DelegationInit = Owned(Init); 2837 2838 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2839 DelegationInit.takeAs<Expr>(), 2840 InitRange.getEnd()); 2841 } 2842 2843 MemInitResult 2844 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2845 Expr *Init, CXXRecordDecl *ClassDecl, 2846 SourceLocation EllipsisLoc) { 2847 SourceLocation BaseLoc 2848 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2849 2850 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2851 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2852 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2853 2854 // C++ [class.base.init]p2: 2855 // [...] Unless the mem-initializer-id names a nonstatic data 2856 // member of the constructor's class or a direct or virtual base 2857 // of that class, the mem-initializer is ill-formed. A 2858 // mem-initializer-list can initialize a base class using any 2859 // name that denotes that base class type. 2860 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2861 2862 SourceRange InitRange = Init->getSourceRange(); 2863 if (EllipsisLoc.isValid()) { 2864 // This is a pack expansion. 2865 if (!BaseType->containsUnexpandedParameterPack()) { 2866 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2867 << SourceRange(BaseLoc, InitRange.getEnd()); 2868 2869 EllipsisLoc = SourceLocation(); 2870 } 2871 } else { 2872 // Check for any unexpanded parameter packs. 2873 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2874 return true; 2875 2876 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2877 return true; 2878 } 2879 2880 // Check for direct and virtual base classes. 2881 const CXXBaseSpecifier *DirectBaseSpec = 0; 2882 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2883 if (!Dependent) { 2884 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2885 BaseType)) 2886 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2887 2888 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2889 VirtualBaseSpec); 2890 2891 // C++ [base.class.init]p2: 2892 // Unless the mem-initializer-id names a nonstatic data member of the 2893 // constructor's class or a direct or virtual base of that class, the 2894 // mem-initializer is ill-formed. 2895 if (!DirectBaseSpec && !VirtualBaseSpec) { 2896 // If the class has any dependent bases, then it's possible that 2897 // one of those types will resolve to the same type as 2898 // BaseType. Therefore, just treat this as a dependent base 2899 // class initialization. FIXME: Should we try to check the 2900 // initialization anyway? It seems odd. 2901 if (ClassDecl->hasAnyDependentBases()) 2902 Dependent = true; 2903 else 2904 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2905 << BaseType << Context.getTypeDeclType(ClassDecl) 2906 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2907 } 2908 } 2909 2910 if (Dependent) { 2911 DiscardCleanupsInEvaluationContext(); 2912 2913 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2914 /*IsVirtual=*/false, 2915 InitRange.getBegin(), Init, 2916 InitRange.getEnd(), EllipsisLoc); 2917 } 2918 2919 // C++ [base.class.init]p2: 2920 // If a mem-initializer-id is ambiguous because it designates both 2921 // a direct non-virtual base class and an inherited virtual base 2922 // class, the mem-initializer is ill-formed. 2923 if (DirectBaseSpec && VirtualBaseSpec) 2924 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2925 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2926 2927 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2928 if (!BaseSpec) 2929 BaseSpec = VirtualBaseSpec; 2930 2931 // Initialize the base. 2932 bool InitList = true; 2933 MultiExprArg Args = Init; 2934 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2935 InitList = false; 2936 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2937 } 2938 2939 InitializedEntity BaseEntity = 2940 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2941 InitializationKind Kind = 2942 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2943 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2944 InitRange.getEnd()); 2945 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2946 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2947 if (BaseInit.isInvalid()) 2948 return true; 2949 2950 // C++11 [class.base.init]p7: 2951 // The initialization of each base and member constitutes a 2952 // full-expression. 2953 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2954 if (BaseInit.isInvalid()) 2955 return true; 2956 2957 // If we are in a dependent context, template instantiation will 2958 // perform this type-checking again. Just save the arguments that we 2959 // received in a ParenListExpr. 2960 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2961 // of the information that we have about the base 2962 // initializer. However, deconstructing the ASTs is a dicey process, 2963 // and this approach is far more likely to get the corner cases right. 2964 if (CurContext->isDependentContext()) 2965 BaseInit = Owned(Init); 2966 2967 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2968 BaseSpec->isVirtual(), 2969 InitRange.getBegin(), 2970 BaseInit.takeAs<Expr>(), 2971 InitRange.getEnd(), EllipsisLoc); 2972 } 2973 2974 // Create a static_cast\<T&&>(expr). 2975 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2976 if (T.isNull()) T = E->getType(); 2977 QualType TargetType = SemaRef.BuildReferenceType( 2978 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2979 SourceLocation ExprLoc = E->getLocStart(); 2980 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2981 TargetType, ExprLoc); 2982 2983 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2984 SourceRange(ExprLoc, ExprLoc), 2985 E->getSourceRange()).take(); 2986 } 2987 2988 /// ImplicitInitializerKind - How an implicit base or member initializer should 2989 /// initialize its base or member. 2990 enum ImplicitInitializerKind { 2991 IIK_Default, 2992 IIK_Copy, 2993 IIK_Move, 2994 IIK_Inherit 2995 }; 2996 2997 static bool 2998 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2999 ImplicitInitializerKind ImplicitInitKind, 3000 CXXBaseSpecifier *BaseSpec, 3001 bool IsInheritedVirtualBase, 3002 CXXCtorInitializer *&CXXBaseInit) { 3003 InitializedEntity InitEntity 3004 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3005 IsInheritedVirtualBase); 3006 3007 ExprResult BaseInit; 3008 3009 switch (ImplicitInitKind) { 3010 case IIK_Inherit: { 3011 const CXXRecordDecl *Inherited = 3012 Constructor->getInheritedConstructor()->getParent(); 3013 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3014 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3015 // C++11 [class.inhctor]p8: 3016 // Each expression in the expression-list is of the form 3017 // static_cast<T&&>(p), where p is the name of the corresponding 3018 // constructor parameter and T is the declared type of p. 3019 SmallVector<Expr*, 16> Args; 3020 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3021 ParmVarDecl *PD = Constructor->getParamDecl(I); 3022 ExprResult ArgExpr = 3023 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3024 VK_LValue, SourceLocation()); 3025 if (ArgExpr.isInvalid()) 3026 return true; 3027 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 3028 } 3029 3030 InitializationKind InitKind = InitializationKind::CreateDirect( 3031 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3032 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3033 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3034 break; 3035 } 3036 } 3037 // Fall through. 3038 case IIK_Default: { 3039 InitializationKind InitKind 3040 = InitializationKind::CreateDefault(Constructor->getLocation()); 3041 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3042 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3043 break; 3044 } 3045 3046 case IIK_Move: 3047 case IIK_Copy: { 3048 bool Moving = ImplicitInitKind == IIK_Move; 3049 ParmVarDecl *Param = Constructor->getParamDecl(0); 3050 QualType ParamType = Param->getType().getNonReferenceType(); 3051 3052 Expr *CopyCtorArg = 3053 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3054 SourceLocation(), Param, false, 3055 Constructor->getLocation(), ParamType, 3056 VK_LValue, 0); 3057 3058 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3059 3060 // Cast to the base class to avoid ambiguities. 3061 QualType ArgTy = 3062 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3063 ParamType.getQualifiers()); 3064 3065 if (Moving) { 3066 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3067 } 3068 3069 CXXCastPath BasePath; 3070 BasePath.push_back(BaseSpec); 3071 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3072 CK_UncheckedDerivedToBase, 3073 Moving ? VK_XValue : VK_LValue, 3074 &BasePath).take(); 3075 3076 InitializationKind InitKind 3077 = InitializationKind::CreateDirect(Constructor->getLocation(), 3078 SourceLocation(), SourceLocation()); 3079 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3080 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3081 break; 3082 } 3083 } 3084 3085 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3086 if (BaseInit.isInvalid()) 3087 return true; 3088 3089 CXXBaseInit = 3090 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3091 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3092 SourceLocation()), 3093 BaseSpec->isVirtual(), 3094 SourceLocation(), 3095 BaseInit.takeAs<Expr>(), 3096 SourceLocation(), 3097 SourceLocation()); 3098 3099 return false; 3100 } 3101 3102 static bool RefersToRValueRef(Expr *MemRef) { 3103 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3104 return Referenced->getType()->isRValueReferenceType(); 3105 } 3106 3107 static bool 3108 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3109 ImplicitInitializerKind ImplicitInitKind, 3110 FieldDecl *Field, IndirectFieldDecl *Indirect, 3111 CXXCtorInitializer *&CXXMemberInit) { 3112 if (Field->isInvalidDecl()) 3113 return true; 3114 3115 SourceLocation Loc = Constructor->getLocation(); 3116 3117 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3118 bool Moving = ImplicitInitKind == IIK_Move; 3119 ParmVarDecl *Param = Constructor->getParamDecl(0); 3120 QualType ParamType = Param->getType().getNonReferenceType(); 3121 3122 // Suppress copying zero-width bitfields. 3123 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3124 return false; 3125 3126 Expr *MemberExprBase = 3127 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3128 SourceLocation(), Param, false, 3129 Loc, ParamType, VK_LValue, 0); 3130 3131 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3132 3133 if (Moving) { 3134 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3135 } 3136 3137 // Build a reference to this field within the parameter. 3138 CXXScopeSpec SS; 3139 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3140 Sema::LookupMemberName); 3141 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3142 : cast<ValueDecl>(Field), AS_public); 3143 MemberLookup.resolveKind(); 3144 ExprResult CtorArg 3145 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3146 ParamType, Loc, 3147 /*IsArrow=*/false, 3148 SS, 3149 /*TemplateKWLoc=*/SourceLocation(), 3150 /*FirstQualifierInScope=*/0, 3151 MemberLookup, 3152 /*TemplateArgs=*/0); 3153 if (CtorArg.isInvalid()) 3154 return true; 3155 3156 // C++11 [class.copy]p15: 3157 // - if a member m has rvalue reference type T&&, it is direct-initialized 3158 // with static_cast<T&&>(x.m); 3159 if (RefersToRValueRef(CtorArg.get())) { 3160 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3161 } 3162 3163 // When the field we are copying is an array, create index variables for 3164 // each dimension of the array. We use these index variables to subscript 3165 // the source array, and other clients (e.g., CodeGen) will perform the 3166 // necessary iteration with these index variables. 3167 SmallVector<VarDecl *, 4> IndexVariables; 3168 QualType BaseType = Field->getType(); 3169 QualType SizeType = SemaRef.Context.getSizeType(); 3170 bool InitializingArray = false; 3171 while (const ConstantArrayType *Array 3172 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3173 InitializingArray = true; 3174 // Create the iteration variable for this array index. 3175 IdentifierInfo *IterationVarName = 0; 3176 { 3177 SmallString<8> Str; 3178 llvm::raw_svector_ostream OS(Str); 3179 OS << "__i" << IndexVariables.size(); 3180 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3181 } 3182 VarDecl *IterationVar 3183 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3184 IterationVarName, SizeType, 3185 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3186 SC_None); 3187 IndexVariables.push_back(IterationVar); 3188 3189 // Create a reference to the iteration variable. 3190 ExprResult IterationVarRef 3191 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3192 assert(!IterationVarRef.isInvalid() && 3193 "Reference to invented variable cannot fail!"); 3194 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3195 assert(!IterationVarRef.isInvalid() && 3196 "Conversion of invented variable cannot fail!"); 3197 3198 // Subscript the array with this iteration variable. 3199 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3200 IterationVarRef.take(), 3201 Loc); 3202 if (CtorArg.isInvalid()) 3203 return true; 3204 3205 BaseType = Array->getElementType(); 3206 } 3207 3208 // The array subscript expression is an lvalue, which is wrong for moving. 3209 if (Moving && InitializingArray) 3210 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3211 3212 // Construct the entity that we will be initializing. For an array, this 3213 // will be first element in the array, which may require several levels 3214 // of array-subscript entities. 3215 SmallVector<InitializedEntity, 4> Entities; 3216 Entities.reserve(1 + IndexVariables.size()); 3217 if (Indirect) 3218 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3219 else 3220 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3221 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3222 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3223 0, 3224 Entities.back())); 3225 3226 // Direct-initialize to use the copy constructor. 3227 InitializationKind InitKind = 3228 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3229 3230 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3231 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3232 3233 ExprResult MemberInit 3234 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3235 MultiExprArg(&CtorArgE, 1)); 3236 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3237 if (MemberInit.isInvalid()) 3238 return true; 3239 3240 if (Indirect) { 3241 assert(IndexVariables.size() == 0 && 3242 "Indirect field improperly initialized"); 3243 CXXMemberInit 3244 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3245 Loc, Loc, 3246 MemberInit.takeAs<Expr>(), 3247 Loc); 3248 } else 3249 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3250 Loc, MemberInit.takeAs<Expr>(), 3251 Loc, 3252 IndexVariables.data(), 3253 IndexVariables.size()); 3254 return false; 3255 } 3256 3257 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3258 "Unhandled implicit init kind!"); 3259 3260 QualType FieldBaseElementType = 3261 SemaRef.Context.getBaseElementType(Field->getType()); 3262 3263 if (FieldBaseElementType->isRecordType()) { 3264 InitializedEntity InitEntity 3265 = Indirect? InitializedEntity::InitializeMember(Indirect) 3266 : InitializedEntity::InitializeMember(Field); 3267 InitializationKind InitKind = 3268 InitializationKind::CreateDefault(Loc); 3269 3270 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3271 ExprResult MemberInit = 3272 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3273 3274 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3275 if (MemberInit.isInvalid()) 3276 return true; 3277 3278 if (Indirect) 3279 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3280 Indirect, Loc, 3281 Loc, 3282 MemberInit.get(), 3283 Loc); 3284 else 3285 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3286 Field, Loc, Loc, 3287 MemberInit.get(), 3288 Loc); 3289 return false; 3290 } 3291 3292 if (!Field->getParent()->isUnion()) { 3293 if (FieldBaseElementType->isReferenceType()) { 3294 SemaRef.Diag(Constructor->getLocation(), 3295 diag::err_uninitialized_member_in_ctor) 3296 << (int)Constructor->isImplicit() 3297 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3298 << 0 << Field->getDeclName(); 3299 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3300 return true; 3301 } 3302 3303 if (FieldBaseElementType.isConstQualified()) { 3304 SemaRef.Diag(Constructor->getLocation(), 3305 diag::err_uninitialized_member_in_ctor) 3306 << (int)Constructor->isImplicit() 3307 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3308 << 1 << Field->getDeclName(); 3309 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3310 return true; 3311 } 3312 } 3313 3314 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3315 FieldBaseElementType->isObjCRetainableType() && 3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3317 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3318 // ARC: 3319 // Default-initialize Objective-C pointers to NULL. 3320 CXXMemberInit 3321 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3322 Loc, Loc, 3323 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3324 Loc); 3325 return false; 3326 } 3327 3328 // Nothing to initialize. 3329 CXXMemberInit = 0; 3330 return false; 3331 } 3332 3333 namespace { 3334 struct BaseAndFieldInfo { 3335 Sema &S; 3336 CXXConstructorDecl *Ctor; 3337 bool AnyErrorsInInits; 3338 ImplicitInitializerKind IIK; 3339 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3340 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3341 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3342 3343 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3344 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3345 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3346 if (Generated && Ctor->isCopyConstructor()) 3347 IIK = IIK_Copy; 3348 else if (Generated && Ctor->isMoveConstructor()) 3349 IIK = IIK_Move; 3350 else if (Ctor->getInheritedConstructor()) 3351 IIK = IIK_Inherit; 3352 else 3353 IIK = IIK_Default; 3354 } 3355 3356 bool isImplicitCopyOrMove() const { 3357 switch (IIK) { 3358 case IIK_Copy: 3359 case IIK_Move: 3360 return true; 3361 3362 case IIK_Default: 3363 case IIK_Inherit: 3364 return false; 3365 } 3366 3367 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3368 } 3369 3370 bool addFieldInitializer(CXXCtorInitializer *Init) { 3371 AllToInit.push_back(Init); 3372 3373 // Check whether this initializer makes the field "used". 3374 if (Init->getInit()->HasSideEffects(S.Context)) 3375 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3376 3377 return false; 3378 } 3379 3380 bool isInactiveUnionMember(FieldDecl *Field) { 3381 RecordDecl *Record = Field->getParent(); 3382 if (!Record->isUnion()) 3383 return false; 3384 3385 if (FieldDecl *Active = 3386 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3387 return Active != Field->getCanonicalDecl(); 3388 3389 // In an implicit copy or move constructor, ignore any in-class initializer. 3390 if (isImplicitCopyOrMove()) 3391 return true; 3392 3393 // If there's no explicit initialization, the field is active only if it 3394 // has an in-class initializer... 3395 if (Field->hasInClassInitializer()) 3396 return false; 3397 // ... or it's an anonymous struct or union whose class has an in-class 3398 // initializer. 3399 if (!Field->isAnonymousStructOrUnion()) 3400 return true; 3401 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3402 return !FieldRD->hasInClassInitializer(); 3403 } 3404 3405 /// \brief Determine whether the given field is, or is within, a union member 3406 /// that is inactive (because there was an initializer given for a different 3407 /// member of the union, or because the union was not initialized at all). 3408 bool isWithinInactiveUnionMember(FieldDecl *Field, 3409 IndirectFieldDecl *Indirect) { 3410 if (!Indirect) 3411 return isInactiveUnionMember(Field); 3412 3413 for (auto *C : Indirect->chain()) { 3414 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3415 if (Field && isInactiveUnionMember(Field)) 3416 return true; 3417 } 3418 return false; 3419 } 3420 }; 3421 } 3422 3423 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3424 /// array type. 3425 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3426 if (T->isIncompleteArrayType()) 3427 return true; 3428 3429 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3430 if (!ArrayT->getSize()) 3431 return true; 3432 3433 T = ArrayT->getElementType(); 3434 } 3435 3436 return false; 3437 } 3438 3439 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3440 FieldDecl *Field, 3441 IndirectFieldDecl *Indirect = 0) { 3442 if (Field->isInvalidDecl()) 3443 return false; 3444 3445 // Overwhelmingly common case: we have a direct initializer for this field. 3446 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3447 return Info.addFieldInitializer(Init); 3448 3449 // C++11 [class.base.init]p8: 3450 // if the entity is a non-static data member that has a 3451 // brace-or-equal-initializer and either 3452 // -- the constructor's class is a union and no other variant member of that 3453 // union is designated by a mem-initializer-id or 3454 // -- the constructor's class is not a union, and, if the entity is a member 3455 // of an anonymous union, no other member of that union is designated by 3456 // a mem-initializer-id, 3457 // the entity is initialized as specified in [dcl.init]. 3458 // 3459 // We also apply the same rules to handle anonymous structs within anonymous 3460 // unions. 3461 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3462 return false; 3463 3464 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3465 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3466 Info.Ctor->getLocation(), Field); 3467 CXXCtorInitializer *Init; 3468 if (Indirect) 3469 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3470 SourceLocation(), 3471 SourceLocation(), DIE, 3472 SourceLocation()); 3473 else 3474 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3475 SourceLocation(), 3476 SourceLocation(), DIE, 3477 SourceLocation()); 3478 return Info.addFieldInitializer(Init); 3479 } 3480 3481 // Don't initialize incomplete or zero-length arrays. 3482 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3483 return false; 3484 3485 // Don't try to build an implicit initializer if there were semantic 3486 // errors in any of the initializers (and therefore we might be 3487 // missing some that the user actually wrote). 3488 if (Info.AnyErrorsInInits) 3489 return false; 3490 3491 CXXCtorInitializer *Init = 0; 3492 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3493 Indirect, Init)) 3494 return true; 3495 3496 if (!Init) 3497 return false; 3498 3499 return Info.addFieldInitializer(Init); 3500 } 3501 3502 bool 3503 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3504 CXXCtorInitializer *Initializer) { 3505 assert(Initializer->isDelegatingInitializer()); 3506 Constructor->setNumCtorInitializers(1); 3507 CXXCtorInitializer **initializer = 3508 new (Context) CXXCtorInitializer*[1]; 3509 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3510 Constructor->setCtorInitializers(initializer); 3511 3512 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3513 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3514 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3515 } 3516 3517 DelegatingCtorDecls.push_back(Constructor); 3518 3519 return false; 3520 } 3521 3522 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3523 ArrayRef<CXXCtorInitializer *> Initializers) { 3524 if (Constructor->isDependentContext()) { 3525 // Just store the initializers as written, they will be checked during 3526 // instantiation. 3527 if (!Initializers.empty()) { 3528 Constructor->setNumCtorInitializers(Initializers.size()); 3529 CXXCtorInitializer **baseOrMemberInitializers = 3530 new (Context) CXXCtorInitializer*[Initializers.size()]; 3531 memcpy(baseOrMemberInitializers, Initializers.data(), 3532 Initializers.size() * sizeof(CXXCtorInitializer*)); 3533 Constructor->setCtorInitializers(baseOrMemberInitializers); 3534 } 3535 3536 // Let template instantiation know whether we had errors. 3537 if (AnyErrors) 3538 Constructor->setInvalidDecl(); 3539 3540 return false; 3541 } 3542 3543 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3544 3545 // We need to build the initializer AST according to order of construction 3546 // and not what user specified in the Initializers list. 3547 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3548 if (!ClassDecl) 3549 return true; 3550 3551 bool HadError = false; 3552 3553 for (unsigned i = 0; i < Initializers.size(); i++) { 3554 CXXCtorInitializer *Member = Initializers[i]; 3555 3556 if (Member->isBaseInitializer()) 3557 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3558 else { 3559 Info.AllBaseFields[Member->getAnyMember()] = Member; 3560 3561 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3562 for (auto *C : F->chain()) { 3563 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3564 if (FD && FD->getParent()->isUnion()) 3565 Info.ActiveUnionMember.insert(std::make_pair( 3566 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3567 } 3568 } else if (FieldDecl *FD = Member->getMember()) { 3569 if (FD->getParent()->isUnion()) 3570 Info.ActiveUnionMember.insert(std::make_pair( 3571 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3572 } 3573 } 3574 } 3575 3576 // Keep track of the direct virtual bases. 3577 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3578 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3579 E = ClassDecl->bases_end(); I != E; ++I) { 3580 if (I->isVirtual()) 3581 DirectVBases.insert(I); 3582 } 3583 3584 // Push virtual bases before others. 3585 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3586 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3587 3588 if (CXXCtorInitializer *Value 3589 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3590 // [class.base.init]p7, per DR257: 3591 // A mem-initializer where the mem-initializer-id names a virtual base 3592 // class is ignored during execution of a constructor of any class that 3593 // is not the most derived class. 3594 if (ClassDecl->isAbstract()) { 3595 // FIXME: Provide a fixit to remove the base specifier. This requires 3596 // tracking the location of the associated comma for a base specifier. 3597 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3598 << VBase->getType() << ClassDecl; 3599 DiagnoseAbstractType(ClassDecl); 3600 } 3601 3602 Info.AllToInit.push_back(Value); 3603 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3604 // [class.base.init]p8, per DR257: 3605 // If a given [...] base class is not named by a mem-initializer-id 3606 // [...] and the entity is not a virtual base class of an abstract 3607 // class, then [...] the entity is default-initialized. 3608 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3609 CXXCtorInitializer *CXXBaseInit; 3610 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3611 VBase, IsInheritedVirtualBase, 3612 CXXBaseInit)) { 3613 HadError = true; 3614 continue; 3615 } 3616 3617 Info.AllToInit.push_back(CXXBaseInit); 3618 } 3619 } 3620 3621 // Non-virtual bases. 3622 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3623 E = ClassDecl->bases_end(); Base != E; ++Base) { 3624 // Virtuals are in the virtual base list and already constructed. 3625 if (Base->isVirtual()) 3626 continue; 3627 3628 if (CXXCtorInitializer *Value 3629 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3630 Info.AllToInit.push_back(Value); 3631 } else if (!AnyErrors) { 3632 CXXCtorInitializer *CXXBaseInit; 3633 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3634 Base, /*IsInheritedVirtualBase=*/false, 3635 CXXBaseInit)) { 3636 HadError = true; 3637 continue; 3638 } 3639 3640 Info.AllToInit.push_back(CXXBaseInit); 3641 } 3642 } 3643 3644 // Fields. 3645 for (auto *Mem : ClassDecl->decls()) { 3646 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3647 // C++ [class.bit]p2: 3648 // A declaration for a bit-field that omits the identifier declares an 3649 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3650 // initialized. 3651 if (F->isUnnamedBitfield()) 3652 continue; 3653 3654 // If we're not generating the implicit copy/move constructor, then we'll 3655 // handle anonymous struct/union fields based on their individual 3656 // indirect fields. 3657 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3658 continue; 3659 3660 if (CollectFieldInitializer(*this, Info, F)) 3661 HadError = true; 3662 continue; 3663 } 3664 3665 // Beyond this point, we only consider default initialization. 3666 if (Info.isImplicitCopyOrMove()) 3667 continue; 3668 3669 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3670 if (F->getType()->isIncompleteArrayType()) { 3671 assert(ClassDecl->hasFlexibleArrayMember() && 3672 "Incomplete array type is not valid"); 3673 continue; 3674 } 3675 3676 // Initialize each field of an anonymous struct individually. 3677 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3678 HadError = true; 3679 3680 continue; 3681 } 3682 } 3683 3684 unsigned NumInitializers = Info.AllToInit.size(); 3685 if (NumInitializers > 0) { 3686 Constructor->setNumCtorInitializers(NumInitializers); 3687 CXXCtorInitializer **baseOrMemberInitializers = 3688 new (Context) CXXCtorInitializer*[NumInitializers]; 3689 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3690 NumInitializers * sizeof(CXXCtorInitializer*)); 3691 Constructor->setCtorInitializers(baseOrMemberInitializers); 3692 3693 // Constructors implicitly reference the base and member 3694 // destructors. 3695 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3696 Constructor->getParent()); 3697 } 3698 3699 return HadError; 3700 } 3701 3702 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3703 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3704 const RecordDecl *RD = RT->getDecl(); 3705 if (RD->isAnonymousStructOrUnion()) { 3706 for (auto *Field : RD->fields()) 3707 PopulateKeysForFields(Field, IdealInits); 3708 return; 3709 } 3710 } 3711 IdealInits.push_back(Field); 3712 } 3713 3714 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3715 return Context.getCanonicalType(BaseType).getTypePtr(); 3716 } 3717 3718 static const void *GetKeyForMember(ASTContext &Context, 3719 CXXCtorInitializer *Member) { 3720 if (!Member->isAnyMemberInitializer()) 3721 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3722 3723 return Member->getAnyMember(); 3724 } 3725 3726 static void DiagnoseBaseOrMemInitializerOrder( 3727 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3728 ArrayRef<CXXCtorInitializer *> Inits) { 3729 if (Constructor->getDeclContext()->isDependentContext()) 3730 return; 3731 3732 // Don't check initializers order unless the warning is enabled at the 3733 // location of at least one initializer. 3734 bool ShouldCheckOrder = false; 3735 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3736 CXXCtorInitializer *Init = Inits[InitIndex]; 3737 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3738 Init->getSourceLocation()) 3739 != DiagnosticsEngine::Ignored) { 3740 ShouldCheckOrder = true; 3741 break; 3742 } 3743 } 3744 if (!ShouldCheckOrder) 3745 return; 3746 3747 // Build the list of bases and members in the order that they'll 3748 // actually be initialized. The explicit initializers should be in 3749 // this same order but may be missing things. 3750 SmallVector<const void*, 32> IdealInitKeys; 3751 3752 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3753 3754 // 1. Virtual bases. 3755 for (CXXRecordDecl::base_class_const_iterator VBase = 3756 ClassDecl->vbases_begin(), 3757 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3758 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3759 3760 // 2. Non-virtual bases. 3761 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3762 E = ClassDecl->bases_end(); Base != E; ++Base) { 3763 if (Base->isVirtual()) 3764 continue; 3765 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3766 } 3767 3768 // 3. Direct fields. 3769 for (auto *Field : ClassDecl->fields()) { 3770 if (Field->isUnnamedBitfield()) 3771 continue; 3772 3773 PopulateKeysForFields(Field, IdealInitKeys); 3774 } 3775 3776 unsigned NumIdealInits = IdealInitKeys.size(); 3777 unsigned IdealIndex = 0; 3778 3779 CXXCtorInitializer *PrevInit = 0; 3780 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3781 CXXCtorInitializer *Init = Inits[InitIndex]; 3782 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3783 3784 // Scan forward to try to find this initializer in the idealized 3785 // initializers list. 3786 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3787 if (InitKey == IdealInitKeys[IdealIndex]) 3788 break; 3789 3790 // If we didn't find this initializer, it must be because we 3791 // scanned past it on a previous iteration. That can only 3792 // happen if we're out of order; emit a warning. 3793 if (IdealIndex == NumIdealInits && PrevInit) { 3794 Sema::SemaDiagnosticBuilder D = 3795 SemaRef.Diag(PrevInit->getSourceLocation(), 3796 diag::warn_initializer_out_of_order); 3797 3798 if (PrevInit->isAnyMemberInitializer()) 3799 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3800 else 3801 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3802 3803 if (Init->isAnyMemberInitializer()) 3804 D << 0 << Init->getAnyMember()->getDeclName(); 3805 else 3806 D << 1 << Init->getTypeSourceInfo()->getType(); 3807 3808 // Move back to the initializer's location in the ideal list. 3809 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3810 if (InitKey == IdealInitKeys[IdealIndex]) 3811 break; 3812 3813 assert(IdealIndex != NumIdealInits && 3814 "initializer not found in initializer list"); 3815 } 3816 3817 PrevInit = Init; 3818 } 3819 } 3820 3821 namespace { 3822 bool CheckRedundantInit(Sema &S, 3823 CXXCtorInitializer *Init, 3824 CXXCtorInitializer *&PrevInit) { 3825 if (!PrevInit) { 3826 PrevInit = Init; 3827 return false; 3828 } 3829 3830 if (FieldDecl *Field = Init->getAnyMember()) 3831 S.Diag(Init->getSourceLocation(), 3832 diag::err_multiple_mem_initialization) 3833 << Field->getDeclName() 3834 << Init->getSourceRange(); 3835 else { 3836 const Type *BaseClass = Init->getBaseClass(); 3837 assert(BaseClass && "neither field nor base"); 3838 S.Diag(Init->getSourceLocation(), 3839 diag::err_multiple_base_initialization) 3840 << QualType(BaseClass, 0) 3841 << Init->getSourceRange(); 3842 } 3843 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3844 << 0 << PrevInit->getSourceRange(); 3845 3846 return true; 3847 } 3848 3849 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3850 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3851 3852 bool CheckRedundantUnionInit(Sema &S, 3853 CXXCtorInitializer *Init, 3854 RedundantUnionMap &Unions) { 3855 FieldDecl *Field = Init->getAnyMember(); 3856 RecordDecl *Parent = Field->getParent(); 3857 NamedDecl *Child = Field; 3858 3859 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3860 if (Parent->isUnion()) { 3861 UnionEntry &En = Unions[Parent]; 3862 if (En.first && En.first != Child) { 3863 S.Diag(Init->getSourceLocation(), 3864 diag::err_multiple_mem_union_initialization) 3865 << Field->getDeclName() 3866 << Init->getSourceRange(); 3867 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3868 << 0 << En.second->getSourceRange(); 3869 return true; 3870 } 3871 if (!En.first) { 3872 En.first = Child; 3873 En.second = Init; 3874 } 3875 if (!Parent->isAnonymousStructOrUnion()) 3876 return false; 3877 } 3878 3879 Child = Parent; 3880 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3881 } 3882 3883 return false; 3884 } 3885 } 3886 3887 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3888 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3889 SourceLocation ColonLoc, 3890 ArrayRef<CXXCtorInitializer*> MemInits, 3891 bool AnyErrors) { 3892 if (!ConstructorDecl) 3893 return; 3894 3895 AdjustDeclIfTemplate(ConstructorDecl); 3896 3897 CXXConstructorDecl *Constructor 3898 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3899 3900 if (!Constructor) { 3901 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3902 return; 3903 } 3904 3905 // Mapping for the duplicate initializers check. 3906 // For member initializers, this is keyed with a FieldDecl*. 3907 // For base initializers, this is keyed with a Type*. 3908 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3909 3910 // Mapping for the inconsistent anonymous-union initializers check. 3911 RedundantUnionMap MemberUnions; 3912 3913 bool HadError = false; 3914 for (unsigned i = 0; i < MemInits.size(); i++) { 3915 CXXCtorInitializer *Init = MemInits[i]; 3916 3917 // Set the source order index. 3918 Init->setSourceOrder(i); 3919 3920 if (Init->isAnyMemberInitializer()) { 3921 FieldDecl *Field = Init->getAnyMember(); 3922 if (CheckRedundantInit(*this, Init, Members[Field]) || 3923 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3924 HadError = true; 3925 } else if (Init->isBaseInitializer()) { 3926 const void *Key = 3927 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3928 if (CheckRedundantInit(*this, Init, Members[Key])) 3929 HadError = true; 3930 } else { 3931 assert(Init->isDelegatingInitializer()); 3932 // This must be the only initializer 3933 if (MemInits.size() != 1) { 3934 Diag(Init->getSourceLocation(), 3935 diag::err_delegating_initializer_alone) 3936 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3937 // We will treat this as being the only initializer. 3938 } 3939 SetDelegatingInitializer(Constructor, MemInits[i]); 3940 // Return immediately as the initializer is set. 3941 return; 3942 } 3943 } 3944 3945 if (HadError) 3946 return; 3947 3948 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3949 3950 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3951 3952 DiagnoseUninitializedFields(*this, Constructor); 3953 } 3954 3955 void 3956 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3957 CXXRecordDecl *ClassDecl) { 3958 // Ignore dependent contexts. Also ignore unions, since their members never 3959 // have destructors implicitly called. 3960 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3961 return; 3962 3963 // FIXME: all the access-control diagnostics are positioned on the 3964 // field/base declaration. That's probably good; that said, the 3965 // user might reasonably want to know why the destructor is being 3966 // emitted, and we currently don't say. 3967 3968 // Non-static data members. 3969 for (auto *Field : ClassDecl->fields()) { 3970 if (Field->isInvalidDecl()) 3971 continue; 3972 3973 // Don't destroy incomplete or zero-length arrays. 3974 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3975 continue; 3976 3977 QualType FieldType = Context.getBaseElementType(Field->getType()); 3978 3979 const RecordType* RT = FieldType->getAs<RecordType>(); 3980 if (!RT) 3981 continue; 3982 3983 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3984 if (FieldClassDecl->isInvalidDecl()) 3985 continue; 3986 if (FieldClassDecl->hasIrrelevantDestructor()) 3987 continue; 3988 // The destructor for an implicit anonymous union member is never invoked. 3989 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3990 continue; 3991 3992 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3993 assert(Dtor && "No dtor found for FieldClassDecl!"); 3994 CheckDestructorAccess(Field->getLocation(), Dtor, 3995 PDiag(diag::err_access_dtor_field) 3996 << Field->getDeclName() 3997 << FieldType); 3998 3999 MarkFunctionReferenced(Location, Dtor); 4000 DiagnoseUseOfDecl(Dtor, Location); 4001 } 4002 4003 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4004 4005 // Bases. 4006 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4007 E = ClassDecl->bases_end(); Base != E; ++Base) { 4008 // Bases are always records in a well-formed non-dependent class. 4009 const RecordType *RT = Base->getType()->getAs<RecordType>(); 4010 4011 // Remember direct virtual bases. 4012 if (Base->isVirtual()) 4013 DirectVirtualBases.insert(RT); 4014 4015 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4016 // If our base class is invalid, we probably can't get its dtor anyway. 4017 if (BaseClassDecl->isInvalidDecl()) 4018 continue; 4019 if (BaseClassDecl->hasIrrelevantDestructor()) 4020 continue; 4021 4022 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4023 assert(Dtor && "No dtor found for BaseClassDecl!"); 4024 4025 // FIXME: caret should be on the start of the class name 4026 CheckDestructorAccess(Base->getLocStart(), Dtor, 4027 PDiag(diag::err_access_dtor_base) 4028 << Base->getType() 4029 << Base->getSourceRange(), 4030 Context.getTypeDeclType(ClassDecl)); 4031 4032 MarkFunctionReferenced(Location, Dtor); 4033 DiagnoseUseOfDecl(Dtor, Location); 4034 } 4035 4036 // Virtual bases. 4037 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 4038 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 4039 4040 // Bases are always records in a well-formed non-dependent class. 4041 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 4042 4043 // Ignore direct virtual bases. 4044 if (DirectVirtualBases.count(RT)) 4045 continue; 4046 4047 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4048 // If our base class is invalid, we probably can't get its dtor anyway. 4049 if (BaseClassDecl->isInvalidDecl()) 4050 continue; 4051 if (BaseClassDecl->hasIrrelevantDestructor()) 4052 continue; 4053 4054 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4055 assert(Dtor && "No dtor found for BaseClassDecl!"); 4056 if (CheckDestructorAccess( 4057 ClassDecl->getLocation(), Dtor, 4058 PDiag(diag::err_access_dtor_vbase) 4059 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 4060 Context.getTypeDeclType(ClassDecl)) == 4061 AR_accessible) { 4062 CheckDerivedToBaseConversion( 4063 Context.getTypeDeclType(ClassDecl), VBase->getType(), 4064 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4065 SourceRange(), DeclarationName(), 0); 4066 } 4067 4068 MarkFunctionReferenced(Location, Dtor); 4069 DiagnoseUseOfDecl(Dtor, Location); 4070 } 4071 } 4072 4073 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4074 if (!CDtorDecl) 4075 return; 4076 4077 if (CXXConstructorDecl *Constructor 4078 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4079 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4080 DiagnoseUninitializedFields(*this, Constructor); 4081 } 4082 } 4083 4084 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4085 unsigned DiagID, AbstractDiagSelID SelID) { 4086 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4087 unsigned DiagID; 4088 AbstractDiagSelID SelID; 4089 4090 public: 4091 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4092 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4093 4094 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4095 if (Suppressed) return; 4096 if (SelID == -1) 4097 S.Diag(Loc, DiagID) << T; 4098 else 4099 S.Diag(Loc, DiagID) << SelID << T; 4100 } 4101 } Diagnoser(DiagID, SelID); 4102 4103 return RequireNonAbstractType(Loc, T, Diagnoser); 4104 } 4105 4106 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4107 TypeDiagnoser &Diagnoser) { 4108 if (!getLangOpts().CPlusPlus) 4109 return false; 4110 4111 if (const ArrayType *AT = Context.getAsArrayType(T)) 4112 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4113 4114 if (const PointerType *PT = T->getAs<PointerType>()) { 4115 // Find the innermost pointer type. 4116 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4117 PT = T; 4118 4119 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4120 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4121 } 4122 4123 const RecordType *RT = T->getAs<RecordType>(); 4124 if (!RT) 4125 return false; 4126 4127 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4128 4129 // We can't answer whether something is abstract until it has a 4130 // definition. If it's currently being defined, we'll walk back 4131 // over all the declarations when we have a full definition. 4132 const CXXRecordDecl *Def = RD->getDefinition(); 4133 if (!Def || Def->isBeingDefined()) 4134 return false; 4135 4136 if (!RD->isAbstract()) 4137 return false; 4138 4139 Diagnoser.diagnose(*this, Loc, T); 4140 DiagnoseAbstractType(RD); 4141 4142 return true; 4143 } 4144 4145 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4146 // Check if we've already emitted the list of pure virtual functions 4147 // for this class. 4148 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4149 return; 4150 4151 // If the diagnostic is suppressed, don't emit the notes. We're only 4152 // going to emit them once, so try to attach them to a diagnostic we're 4153 // actually going to show. 4154 if (Diags.isLastDiagnosticIgnored()) 4155 return; 4156 4157 CXXFinalOverriderMap FinalOverriders; 4158 RD->getFinalOverriders(FinalOverriders); 4159 4160 // Keep a set of seen pure methods so we won't diagnose the same method 4161 // more than once. 4162 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4163 4164 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4165 MEnd = FinalOverriders.end(); 4166 M != MEnd; 4167 ++M) { 4168 for (OverridingMethods::iterator SO = M->second.begin(), 4169 SOEnd = M->second.end(); 4170 SO != SOEnd; ++SO) { 4171 // C++ [class.abstract]p4: 4172 // A class is abstract if it contains or inherits at least one 4173 // pure virtual function for which the final overrider is pure 4174 // virtual. 4175 4176 // 4177 if (SO->second.size() != 1) 4178 continue; 4179 4180 if (!SO->second.front().Method->isPure()) 4181 continue; 4182 4183 if (!SeenPureMethods.insert(SO->second.front().Method)) 4184 continue; 4185 4186 Diag(SO->second.front().Method->getLocation(), 4187 diag::note_pure_virtual_function) 4188 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4189 } 4190 } 4191 4192 if (!PureVirtualClassDiagSet) 4193 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4194 PureVirtualClassDiagSet->insert(RD); 4195 } 4196 4197 namespace { 4198 struct AbstractUsageInfo { 4199 Sema &S; 4200 CXXRecordDecl *Record; 4201 CanQualType AbstractType; 4202 bool Invalid; 4203 4204 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4205 : S(S), Record(Record), 4206 AbstractType(S.Context.getCanonicalType( 4207 S.Context.getTypeDeclType(Record))), 4208 Invalid(false) {} 4209 4210 void DiagnoseAbstractType() { 4211 if (Invalid) return; 4212 S.DiagnoseAbstractType(Record); 4213 Invalid = true; 4214 } 4215 4216 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4217 }; 4218 4219 struct CheckAbstractUsage { 4220 AbstractUsageInfo &Info; 4221 const NamedDecl *Ctx; 4222 4223 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4224 : Info(Info), Ctx(Ctx) {} 4225 4226 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4227 switch (TL.getTypeLocClass()) { 4228 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4229 #define TYPELOC(CLASS, PARENT) \ 4230 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4231 #include "clang/AST/TypeLocNodes.def" 4232 } 4233 } 4234 4235 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4236 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4237 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4238 if (!TL.getParam(I)) 4239 continue; 4240 4241 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4242 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4243 } 4244 } 4245 4246 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4247 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4248 } 4249 4250 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4251 // Visit the type parameters from a permissive context. 4252 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4253 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4254 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4255 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4256 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4257 // TODO: other template argument types? 4258 } 4259 } 4260 4261 // Visit pointee types from a permissive context. 4262 #define CheckPolymorphic(Type) \ 4263 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4264 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4265 } 4266 CheckPolymorphic(PointerTypeLoc) 4267 CheckPolymorphic(ReferenceTypeLoc) 4268 CheckPolymorphic(MemberPointerTypeLoc) 4269 CheckPolymorphic(BlockPointerTypeLoc) 4270 CheckPolymorphic(AtomicTypeLoc) 4271 4272 /// Handle all the types we haven't given a more specific 4273 /// implementation for above. 4274 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4275 // Every other kind of type that we haven't called out already 4276 // that has an inner type is either (1) sugar or (2) contains that 4277 // inner type in some way as a subobject. 4278 if (TypeLoc Next = TL.getNextTypeLoc()) 4279 return Visit(Next, Sel); 4280 4281 // If there's no inner type and we're in a permissive context, 4282 // don't diagnose. 4283 if (Sel == Sema::AbstractNone) return; 4284 4285 // Check whether the type matches the abstract type. 4286 QualType T = TL.getType(); 4287 if (T->isArrayType()) { 4288 Sel = Sema::AbstractArrayType; 4289 T = Info.S.Context.getBaseElementType(T); 4290 } 4291 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4292 if (CT != Info.AbstractType) return; 4293 4294 // It matched; do some magic. 4295 if (Sel == Sema::AbstractArrayType) { 4296 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4297 << T << TL.getSourceRange(); 4298 } else { 4299 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4300 << Sel << T << TL.getSourceRange(); 4301 } 4302 Info.DiagnoseAbstractType(); 4303 } 4304 }; 4305 4306 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4307 Sema::AbstractDiagSelID Sel) { 4308 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4309 } 4310 4311 } 4312 4313 /// Check for invalid uses of an abstract type in a method declaration. 4314 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4315 CXXMethodDecl *MD) { 4316 // No need to do the check on definitions, which require that 4317 // the return/param types be complete. 4318 if (MD->doesThisDeclarationHaveABody()) 4319 return; 4320 4321 // For safety's sake, just ignore it if we don't have type source 4322 // information. This should never happen for non-implicit methods, 4323 // but... 4324 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4325 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4326 } 4327 4328 /// Check for invalid uses of an abstract type within a class definition. 4329 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4330 CXXRecordDecl *RD) { 4331 for (auto *D : RD->decls()) { 4332 if (D->isImplicit()) continue; 4333 4334 // Methods and method templates. 4335 if (isa<CXXMethodDecl>(D)) { 4336 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4337 } else if (isa<FunctionTemplateDecl>(D)) { 4338 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4339 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4340 4341 // Fields and static variables. 4342 } else if (isa<FieldDecl>(D)) { 4343 FieldDecl *FD = cast<FieldDecl>(D); 4344 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4345 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4346 } else if (isa<VarDecl>(D)) { 4347 VarDecl *VD = cast<VarDecl>(D); 4348 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4349 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4350 4351 // Nested classes and class templates. 4352 } else if (isa<CXXRecordDecl>(D)) { 4353 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4354 } else if (isa<ClassTemplateDecl>(D)) { 4355 CheckAbstractClassUsage(Info, 4356 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4357 } 4358 } 4359 } 4360 4361 /// \brief Perform semantic checks on a class definition that has been 4362 /// completing, introducing implicitly-declared members, checking for 4363 /// abstract types, etc. 4364 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4365 if (!Record) 4366 return; 4367 4368 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4369 AbstractUsageInfo Info(*this, Record); 4370 CheckAbstractClassUsage(Info, Record); 4371 } 4372 4373 // If this is not an aggregate type and has no user-declared constructor, 4374 // complain about any non-static data members of reference or const scalar 4375 // type, since they will never get initializers. 4376 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4377 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4378 !Record->isLambda()) { 4379 bool Complained = false; 4380 for (const auto *F : Record->fields()) { 4381 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4382 continue; 4383 4384 if (F->getType()->isReferenceType() || 4385 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4386 if (!Complained) { 4387 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4388 << Record->getTagKind() << Record; 4389 Complained = true; 4390 } 4391 4392 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4393 << F->getType()->isReferenceType() 4394 << F->getDeclName(); 4395 } 4396 } 4397 } 4398 4399 if (Record->isDynamicClass() && !Record->isDependentType()) 4400 DynamicClasses.push_back(Record); 4401 4402 if (Record->getIdentifier()) { 4403 // C++ [class.mem]p13: 4404 // If T is the name of a class, then each of the following shall have a 4405 // name different from T: 4406 // - every member of every anonymous union that is a member of class T. 4407 // 4408 // C++ [class.mem]p14: 4409 // In addition, if class T has a user-declared constructor (12.1), every 4410 // non-static data member of class T shall have a name different from T. 4411 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4412 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4413 ++I) { 4414 NamedDecl *D = *I; 4415 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4416 isa<IndirectFieldDecl>(D)) { 4417 Diag(D->getLocation(), diag::err_member_name_of_class) 4418 << D->getDeclName(); 4419 break; 4420 } 4421 } 4422 } 4423 4424 // Warn if the class has virtual methods but non-virtual public destructor. 4425 if (Record->isPolymorphic() && !Record->isDependentType()) { 4426 CXXDestructorDecl *dtor = Record->getDestructor(); 4427 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4428 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4429 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4430 } 4431 4432 if (Record->isAbstract()) { 4433 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4434 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4435 << FA->isSpelledAsSealed(); 4436 DiagnoseAbstractType(Record); 4437 } 4438 } 4439 4440 if (!Record->isDependentType()) { 4441 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4442 MEnd = Record->method_end(); 4443 M != MEnd; ++M) { 4444 // See if a method overloads virtual methods in a base 4445 // class without overriding any. 4446 if (!M->isStatic()) 4447 DiagnoseHiddenVirtualMethods(*M); 4448 4449 // Check whether the explicitly-defaulted special members are valid. 4450 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4451 CheckExplicitlyDefaultedSpecialMember(*M); 4452 4453 // For an explicitly defaulted or deleted special member, we defer 4454 // determining triviality until the class is complete. That time is now! 4455 if (!M->isImplicit() && !M->isUserProvided()) { 4456 CXXSpecialMember CSM = getSpecialMember(*M); 4457 if (CSM != CXXInvalid) { 4458 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4459 4460 // Inform the class that we've finished declaring this member. 4461 Record->finishedDefaultedOrDeletedMember(*M); 4462 } 4463 } 4464 } 4465 } 4466 4467 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4468 // function that is not a constructor declares that member function to be 4469 // const. [...] The class of which that function is a member shall be 4470 // a literal type. 4471 // 4472 // If the class has virtual bases, any constexpr members will already have 4473 // been diagnosed by the checks performed on the member declaration, so 4474 // suppress this (less useful) diagnostic. 4475 // 4476 // We delay this until we know whether an explicitly-defaulted (or deleted) 4477 // destructor for the class is trivial. 4478 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4479 !Record->isLiteral() && !Record->getNumVBases()) { 4480 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4481 MEnd = Record->method_end(); 4482 M != MEnd; ++M) { 4483 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4484 switch (Record->getTemplateSpecializationKind()) { 4485 case TSK_ImplicitInstantiation: 4486 case TSK_ExplicitInstantiationDeclaration: 4487 case TSK_ExplicitInstantiationDefinition: 4488 // If a template instantiates to a non-literal type, but its members 4489 // instantiate to constexpr functions, the template is technically 4490 // ill-formed, but we allow it for sanity. 4491 continue; 4492 4493 case TSK_Undeclared: 4494 case TSK_ExplicitSpecialization: 4495 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4496 diag::err_constexpr_method_non_literal); 4497 break; 4498 } 4499 4500 // Only produce one error per class. 4501 break; 4502 } 4503 } 4504 } 4505 4506 // ms_struct is a request to use the same ABI rules as MSVC. Check 4507 // whether this class uses any C++ features that are implemented 4508 // completely differently in MSVC, and if so, emit a diagnostic. 4509 // That diagnostic defaults to an error, but we allow projects to 4510 // map it down to a warning (or ignore it). It's a fairly common 4511 // practice among users of the ms_struct pragma to mass-annotate 4512 // headers, sweeping up a bunch of types that the project doesn't 4513 // really rely on MSVC-compatible layout for. We must therefore 4514 // support "ms_struct except for C++ stuff" as a secondary ABI. 4515 if (Record->isMsStruct(Context) && 4516 (Record->isPolymorphic() || Record->getNumBases())) { 4517 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4518 } 4519 4520 // Declare inheriting constructors. We do this eagerly here because: 4521 // - The standard requires an eager diagnostic for conflicting inheriting 4522 // constructors from different classes. 4523 // - The lazy declaration of the other implicit constructors is so as to not 4524 // waste space and performance on classes that are not meant to be 4525 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4526 // have inheriting constructors. 4527 DeclareInheritingConstructors(Record); 4528 } 4529 4530 /// Look up the special member function that would be called by a special 4531 /// member function for a subobject of class type. 4532 /// 4533 /// \param Class The class type of the subobject. 4534 /// \param CSM The kind of special member function. 4535 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4536 /// \param ConstRHS True if this is a copy operation with a const object 4537 /// on its RHS, that is, if the argument to the outer special member 4538 /// function is 'const' and this is not a field marked 'mutable'. 4539 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4540 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4541 unsigned FieldQuals, bool ConstRHS) { 4542 unsigned LHSQuals = 0; 4543 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4544 LHSQuals = FieldQuals; 4545 4546 unsigned RHSQuals = FieldQuals; 4547 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4548 RHSQuals = 0; 4549 else if (ConstRHS) 4550 RHSQuals |= Qualifiers::Const; 4551 4552 return S.LookupSpecialMember(Class, CSM, 4553 RHSQuals & Qualifiers::Const, 4554 RHSQuals & Qualifiers::Volatile, 4555 false, 4556 LHSQuals & Qualifiers::Const, 4557 LHSQuals & Qualifiers::Volatile); 4558 } 4559 4560 /// Is the special member function which would be selected to perform the 4561 /// specified operation on the specified class type a constexpr constructor? 4562 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4563 Sema::CXXSpecialMember CSM, 4564 unsigned Quals, bool ConstRHS) { 4565 Sema::SpecialMemberOverloadResult *SMOR = 4566 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4567 if (!SMOR || !SMOR->getMethod()) 4568 // A constructor we wouldn't select can't be "involved in initializing" 4569 // anything. 4570 return true; 4571 return SMOR->getMethod()->isConstexpr(); 4572 } 4573 4574 /// Determine whether the specified special member function would be constexpr 4575 /// if it were implicitly defined. 4576 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4577 Sema::CXXSpecialMember CSM, 4578 bool ConstArg) { 4579 if (!S.getLangOpts().CPlusPlus11) 4580 return false; 4581 4582 // C++11 [dcl.constexpr]p4: 4583 // In the definition of a constexpr constructor [...] 4584 bool Ctor = true; 4585 switch (CSM) { 4586 case Sema::CXXDefaultConstructor: 4587 // Since default constructor lookup is essentially trivial (and cannot 4588 // involve, for instance, template instantiation), we compute whether a 4589 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4590 // 4591 // This is important for performance; we need to know whether the default 4592 // constructor is constexpr to determine whether the type is a literal type. 4593 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4594 4595 case Sema::CXXCopyConstructor: 4596 case Sema::CXXMoveConstructor: 4597 // For copy or move constructors, we need to perform overload resolution. 4598 break; 4599 4600 case Sema::CXXCopyAssignment: 4601 case Sema::CXXMoveAssignment: 4602 if (!S.getLangOpts().CPlusPlus1y) 4603 return false; 4604 // In C++1y, we need to perform overload resolution. 4605 Ctor = false; 4606 break; 4607 4608 case Sema::CXXDestructor: 4609 case Sema::CXXInvalid: 4610 return false; 4611 } 4612 4613 // -- if the class is a non-empty union, or for each non-empty anonymous 4614 // union member of a non-union class, exactly one non-static data member 4615 // shall be initialized; [DR1359] 4616 // 4617 // If we squint, this is guaranteed, since exactly one non-static data member 4618 // will be initialized (if the constructor isn't deleted), we just don't know 4619 // which one. 4620 if (Ctor && ClassDecl->isUnion()) 4621 return true; 4622 4623 // -- the class shall not have any virtual base classes; 4624 if (Ctor && ClassDecl->getNumVBases()) 4625 return false; 4626 4627 // C++1y [class.copy]p26: 4628 // -- [the class] is a literal type, and 4629 if (!Ctor && !ClassDecl->isLiteral()) 4630 return false; 4631 4632 // -- every constructor involved in initializing [...] base class 4633 // sub-objects shall be a constexpr constructor; 4634 // -- the assignment operator selected to copy/move each direct base 4635 // class is a constexpr function, and 4636 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4637 BEnd = ClassDecl->bases_end(); 4638 B != BEnd; ++B) { 4639 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4640 if (!BaseType) continue; 4641 4642 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4643 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4644 return false; 4645 } 4646 4647 // -- every constructor involved in initializing non-static data members 4648 // [...] shall be a constexpr constructor; 4649 // -- every non-static data member and base class sub-object shall be 4650 // initialized 4651 // -- for each non-static data member of X that is of class type (or array 4652 // thereof), the assignment operator selected to copy/move that member is 4653 // a constexpr function 4654 for (const auto *F : ClassDecl->fields()) { 4655 if (F->isInvalidDecl()) 4656 continue; 4657 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4658 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4659 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4660 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4661 BaseType.getCVRQualifiers(), 4662 ConstArg && !F->isMutable())) 4663 return false; 4664 } 4665 } 4666 4667 // All OK, it's constexpr! 4668 return true; 4669 } 4670 4671 static Sema::ImplicitExceptionSpecification 4672 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4673 switch (S.getSpecialMember(MD)) { 4674 case Sema::CXXDefaultConstructor: 4675 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4676 case Sema::CXXCopyConstructor: 4677 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4678 case Sema::CXXCopyAssignment: 4679 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4680 case Sema::CXXMoveConstructor: 4681 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4682 case Sema::CXXMoveAssignment: 4683 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4684 case Sema::CXXDestructor: 4685 return S.ComputeDefaultedDtorExceptionSpec(MD); 4686 case Sema::CXXInvalid: 4687 break; 4688 } 4689 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4690 "only special members have implicit exception specs"); 4691 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4692 } 4693 4694 static void 4695 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4696 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4697 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4698 ExceptSpec.getEPI(EPI); 4699 FD->setType(S.Context.getFunctionType(FPT->getReturnType(), 4700 FPT->getParamTypes(), EPI)); 4701 } 4702 4703 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4704 CXXMethodDecl *MD) { 4705 FunctionProtoType::ExtProtoInfo EPI; 4706 4707 // Build an exception specification pointing back at this member. 4708 EPI.ExceptionSpecType = EST_Unevaluated; 4709 EPI.ExceptionSpecDecl = MD; 4710 4711 // Set the calling convention to the default for C++ instance methods. 4712 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4713 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4714 /*IsCXXMethod=*/true)); 4715 return EPI; 4716 } 4717 4718 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4719 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4720 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4721 return; 4722 4723 // Evaluate the exception specification. 4724 ImplicitExceptionSpecification ExceptSpec = 4725 computeImplicitExceptionSpec(*this, Loc, MD); 4726 4727 // Update the type of the special member to use it. 4728 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4729 4730 // A user-provided destructor can be defined outside the class. When that 4731 // happens, be sure to update the exception specification on both 4732 // declarations. 4733 const FunctionProtoType *CanonicalFPT = 4734 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4735 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4736 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4737 CanonicalFPT, ExceptSpec); 4738 } 4739 4740 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4741 CXXRecordDecl *RD = MD->getParent(); 4742 CXXSpecialMember CSM = getSpecialMember(MD); 4743 4744 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4745 "not an explicitly-defaulted special member"); 4746 4747 // Whether this was the first-declared instance of the constructor. 4748 // This affects whether we implicitly add an exception spec and constexpr. 4749 bool First = MD == MD->getCanonicalDecl(); 4750 4751 bool HadError = false; 4752 4753 // C++11 [dcl.fct.def.default]p1: 4754 // A function that is explicitly defaulted shall 4755 // -- be a special member function (checked elsewhere), 4756 // -- have the same type (except for ref-qualifiers, and except that a 4757 // copy operation can take a non-const reference) as an implicit 4758 // declaration, and 4759 // -- not have default arguments. 4760 unsigned ExpectedParams = 1; 4761 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4762 ExpectedParams = 0; 4763 if (MD->getNumParams() != ExpectedParams) { 4764 // This also checks for default arguments: a copy or move constructor with a 4765 // default argument is classified as a default constructor, and assignment 4766 // operations and destructors can't have default arguments. 4767 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4768 << CSM << MD->getSourceRange(); 4769 HadError = true; 4770 } else if (MD->isVariadic()) { 4771 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4772 << CSM << MD->getSourceRange(); 4773 HadError = true; 4774 } 4775 4776 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4777 4778 bool CanHaveConstParam = false; 4779 if (CSM == CXXCopyConstructor) 4780 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4781 else if (CSM == CXXCopyAssignment) 4782 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4783 4784 QualType ReturnType = Context.VoidTy; 4785 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4786 // Check for return type matching. 4787 ReturnType = Type->getReturnType(); 4788 QualType ExpectedReturnType = 4789 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4790 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4791 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4792 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4793 HadError = true; 4794 } 4795 4796 // A defaulted special member cannot have cv-qualifiers. 4797 if (Type->getTypeQuals()) { 4798 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4799 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4800 HadError = true; 4801 } 4802 } 4803 4804 // Check for parameter type matching. 4805 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4806 bool HasConstParam = false; 4807 if (ExpectedParams && ArgType->isReferenceType()) { 4808 // Argument must be reference to possibly-const T. 4809 QualType ReferentType = ArgType->getPointeeType(); 4810 HasConstParam = ReferentType.isConstQualified(); 4811 4812 if (ReferentType.isVolatileQualified()) { 4813 Diag(MD->getLocation(), 4814 diag::err_defaulted_special_member_volatile_param) << CSM; 4815 HadError = true; 4816 } 4817 4818 if (HasConstParam && !CanHaveConstParam) { 4819 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4820 Diag(MD->getLocation(), 4821 diag::err_defaulted_special_member_copy_const_param) 4822 << (CSM == CXXCopyAssignment); 4823 // FIXME: Explain why this special member can't be const. 4824 } else { 4825 Diag(MD->getLocation(), 4826 diag::err_defaulted_special_member_move_const_param) 4827 << (CSM == CXXMoveAssignment); 4828 } 4829 HadError = true; 4830 } 4831 } else if (ExpectedParams) { 4832 // A copy assignment operator can take its argument by value, but a 4833 // defaulted one cannot. 4834 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4835 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4836 HadError = true; 4837 } 4838 4839 // C++11 [dcl.fct.def.default]p2: 4840 // An explicitly-defaulted function may be declared constexpr only if it 4841 // would have been implicitly declared as constexpr, 4842 // Do not apply this rule to members of class templates, since core issue 1358 4843 // makes such functions always instantiate to constexpr functions. For 4844 // functions which cannot be constexpr (for non-constructors in C++11 and for 4845 // destructors in C++1y), this is checked elsewhere. 4846 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4847 HasConstParam); 4848 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4849 : isa<CXXConstructorDecl>(MD)) && 4850 MD->isConstexpr() && !Constexpr && 4851 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4852 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4853 // FIXME: Explain why the special member can't be constexpr. 4854 HadError = true; 4855 } 4856 4857 // and may have an explicit exception-specification only if it is compatible 4858 // with the exception-specification on the implicit declaration. 4859 if (Type->hasExceptionSpec()) { 4860 // Delay the check if this is the first declaration of the special member, 4861 // since we may not have parsed some necessary in-class initializers yet. 4862 if (First) { 4863 // If the exception specification needs to be instantiated, do so now, 4864 // before we clobber it with an EST_Unevaluated specification below. 4865 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4866 InstantiateExceptionSpec(MD->getLocStart(), MD); 4867 Type = MD->getType()->getAs<FunctionProtoType>(); 4868 } 4869 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4870 } else 4871 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4872 } 4873 4874 // If a function is explicitly defaulted on its first declaration, 4875 if (First) { 4876 // -- it is implicitly considered to be constexpr if the implicit 4877 // definition would be, 4878 MD->setConstexpr(Constexpr); 4879 4880 // -- it is implicitly considered to have the same exception-specification 4881 // as if it had been implicitly declared, 4882 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4883 EPI.ExceptionSpecType = EST_Unevaluated; 4884 EPI.ExceptionSpecDecl = MD; 4885 MD->setType(Context.getFunctionType(ReturnType, 4886 ArrayRef<QualType>(&ArgType, 4887 ExpectedParams), 4888 EPI)); 4889 } 4890 4891 if (ShouldDeleteSpecialMember(MD, CSM)) { 4892 if (First) { 4893 SetDeclDeleted(MD, MD->getLocation()); 4894 } else { 4895 // C++11 [dcl.fct.def.default]p4: 4896 // [For a] user-provided explicitly-defaulted function [...] if such a 4897 // function is implicitly defined as deleted, the program is ill-formed. 4898 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4899 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 4900 HadError = true; 4901 } 4902 } 4903 4904 if (HadError) 4905 MD->setInvalidDecl(); 4906 } 4907 4908 /// Check whether the exception specification provided for an 4909 /// explicitly-defaulted special member matches the exception specification 4910 /// that would have been generated for an implicit special member, per 4911 /// C++11 [dcl.fct.def.default]p2. 4912 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4913 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4914 // Compute the implicit exception specification. 4915 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4916 /*IsCXXMethod=*/true); 4917 FunctionProtoType::ExtProtoInfo EPI(CC); 4918 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4919 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4920 Context.getFunctionType(Context.VoidTy, None, EPI)); 4921 4922 // Ensure that it matches. 4923 CheckEquivalentExceptionSpec( 4924 PDiag(diag::err_incorrect_defaulted_exception_spec) 4925 << getSpecialMember(MD), PDiag(), 4926 ImplicitType, SourceLocation(), 4927 SpecifiedType, MD->getLocation()); 4928 } 4929 4930 void Sema::CheckDelayedMemberExceptionSpecs() { 4931 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 4932 2> Checks; 4933 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 4934 4935 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 4936 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 4937 4938 // Perform any deferred checking of exception specifications for virtual 4939 // destructors. 4940 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 4941 const CXXDestructorDecl *Dtor = Checks[i].first; 4942 assert(!Dtor->getParent()->isDependentType() && 4943 "Should not ever add destructors of templates into the list."); 4944 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 4945 } 4946 4947 // Check that any explicitly-defaulted methods have exception specifications 4948 // compatible with their implicit exception specifications. 4949 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 4950 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 4951 Specs[I].second); 4952 } 4953 4954 namespace { 4955 struct SpecialMemberDeletionInfo { 4956 Sema &S; 4957 CXXMethodDecl *MD; 4958 Sema::CXXSpecialMember CSM; 4959 bool Diagnose; 4960 4961 // Properties of the special member, computed for convenience. 4962 bool IsConstructor, IsAssignment, IsMove, ConstArg; 4963 SourceLocation Loc; 4964 4965 bool AllFieldsAreConst; 4966 4967 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4968 Sema::CXXSpecialMember CSM, bool Diagnose) 4969 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4970 IsConstructor(false), IsAssignment(false), IsMove(false), 4971 ConstArg(false), Loc(MD->getLocation()), 4972 AllFieldsAreConst(true) { 4973 switch (CSM) { 4974 case Sema::CXXDefaultConstructor: 4975 case Sema::CXXCopyConstructor: 4976 IsConstructor = true; 4977 break; 4978 case Sema::CXXMoveConstructor: 4979 IsConstructor = true; 4980 IsMove = true; 4981 break; 4982 case Sema::CXXCopyAssignment: 4983 IsAssignment = true; 4984 break; 4985 case Sema::CXXMoveAssignment: 4986 IsAssignment = true; 4987 IsMove = true; 4988 break; 4989 case Sema::CXXDestructor: 4990 break; 4991 case Sema::CXXInvalid: 4992 llvm_unreachable("invalid special member kind"); 4993 } 4994 4995 if (MD->getNumParams()) { 4996 if (const ReferenceType *RT = 4997 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 4998 ConstArg = RT->getPointeeType().isConstQualified(); 4999 } 5000 } 5001 5002 bool inUnion() const { return MD->getParent()->isUnion(); } 5003 5004 /// Look up the corresponding special member in the given class. 5005 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5006 unsigned Quals, bool IsMutable) { 5007 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5008 ConstArg && !IsMutable); 5009 } 5010 5011 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5012 5013 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5014 bool shouldDeleteForField(FieldDecl *FD); 5015 bool shouldDeleteForAllConstMembers(); 5016 5017 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5018 unsigned Quals); 5019 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5020 Sema::SpecialMemberOverloadResult *SMOR, 5021 bool IsDtorCallInCtor); 5022 5023 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5024 }; 5025 } 5026 5027 /// Is the given special member inaccessible when used on the given 5028 /// sub-object. 5029 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5030 CXXMethodDecl *target) { 5031 /// If we're operating on a base class, the object type is the 5032 /// type of this special member. 5033 QualType objectTy; 5034 AccessSpecifier access = target->getAccess(); 5035 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5036 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5037 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5038 5039 // If we're operating on a field, the object type is the type of the field. 5040 } else { 5041 objectTy = S.Context.getTypeDeclType(target->getParent()); 5042 } 5043 5044 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5045 } 5046 5047 /// Check whether we should delete a special member due to the implicit 5048 /// definition containing a call to a special member of a subobject. 5049 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5050 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5051 bool IsDtorCallInCtor) { 5052 CXXMethodDecl *Decl = SMOR->getMethod(); 5053 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5054 5055 int DiagKind = -1; 5056 5057 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5058 DiagKind = !Decl ? 0 : 1; 5059 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5060 DiagKind = 2; 5061 else if (!isAccessible(Subobj, Decl)) 5062 DiagKind = 3; 5063 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5064 !Decl->isTrivial()) { 5065 // A member of a union must have a trivial corresponding special member. 5066 // As a weird special case, a destructor call from a union's constructor 5067 // must be accessible and non-deleted, but need not be trivial. Such a 5068 // destructor is never actually called, but is semantically checked as 5069 // if it were. 5070 DiagKind = 4; 5071 } 5072 5073 if (DiagKind == -1) 5074 return false; 5075 5076 if (Diagnose) { 5077 if (Field) { 5078 S.Diag(Field->getLocation(), 5079 diag::note_deleted_special_member_class_subobject) 5080 << CSM << MD->getParent() << /*IsField*/true 5081 << Field << DiagKind << IsDtorCallInCtor; 5082 } else { 5083 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5084 S.Diag(Base->getLocStart(), 5085 diag::note_deleted_special_member_class_subobject) 5086 << CSM << MD->getParent() << /*IsField*/false 5087 << Base->getType() << DiagKind << IsDtorCallInCtor; 5088 } 5089 5090 if (DiagKind == 1) 5091 S.NoteDeletedFunction(Decl); 5092 // FIXME: Explain inaccessibility if DiagKind == 3. 5093 } 5094 5095 return true; 5096 } 5097 5098 /// Check whether we should delete a special member function due to having a 5099 /// direct or virtual base class or non-static data member of class type M. 5100 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5101 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5102 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5103 bool IsMutable = Field && Field->isMutable(); 5104 5105 // C++11 [class.ctor]p5: 5106 // -- any direct or virtual base class, or non-static data member with no 5107 // brace-or-equal-initializer, has class type M (or array thereof) and 5108 // either M has no default constructor or overload resolution as applied 5109 // to M's default constructor results in an ambiguity or in a function 5110 // that is deleted or inaccessible 5111 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5112 // -- a direct or virtual base class B that cannot be copied/moved because 5113 // overload resolution, as applied to B's corresponding special member, 5114 // results in an ambiguity or a function that is deleted or inaccessible 5115 // from the defaulted special member 5116 // C++11 [class.dtor]p5: 5117 // -- any direct or virtual base class [...] has a type with a destructor 5118 // that is deleted or inaccessible 5119 if (!(CSM == Sema::CXXDefaultConstructor && 5120 Field && Field->hasInClassInitializer()) && 5121 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5122 false)) 5123 return true; 5124 5125 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5126 // -- any direct or virtual base class or non-static data member has a 5127 // type with a destructor that is deleted or inaccessible 5128 if (IsConstructor) { 5129 Sema::SpecialMemberOverloadResult *SMOR = 5130 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5131 false, false, false, false, false); 5132 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5133 return true; 5134 } 5135 5136 return false; 5137 } 5138 5139 /// Check whether we should delete a special member function due to the class 5140 /// having a particular direct or virtual base class. 5141 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5142 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5143 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5144 } 5145 5146 /// Check whether we should delete a special member function due to the class 5147 /// having a particular non-static data member. 5148 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5149 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5150 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5151 5152 if (CSM == Sema::CXXDefaultConstructor) { 5153 // For a default constructor, all references must be initialized in-class 5154 // and, if a union, it must have a non-const member. 5155 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5156 if (Diagnose) 5157 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5158 << MD->getParent() << FD << FieldType << /*Reference*/0; 5159 return true; 5160 } 5161 // C++11 [class.ctor]p5: any non-variant non-static data member of 5162 // const-qualified type (or array thereof) with no 5163 // brace-or-equal-initializer does not have a user-provided default 5164 // constructor. 5165 if (!inUnion() && FieldType.isConstQualified() && 5166 !FD->hasInClassInitializer() && 5167 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5168 if (Diagnose) 5169 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5170 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5171 return true; 5172 } 5173 5174 if (inUnion() && !FieldType.isConstQualified()) 5175 AllFieldsAreConst = false; 5176 } else if (CSM == Sema::CXXCopyConstructor) { 5177 // For a copy constructor, data members must not be of rvalue reference 5178 // type. 5179 if (FieldType->isRValueReferenceType()) { 5180 if (Diagnose) 5181 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5182 << MD->getParent() << FD << FieldType; 5183 return true; 5184 } 5185 } else if (IsAssignment) { 5186 // For an assignment operator, data members must not be of reference type. 5187 if (FieldType->isReferenceType()) { 5188 if (Diagnose) 5189 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5190 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5191 return true; 5192 } 5193 if (!FieldRecord && FieldType.isConstQualified()) { 5194 // C++11 [class.copy]p23: 5195 // -- a non-static data member of const non-class type (or array thereof) 5196 if (Diagnose) 5197 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5198 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5199 return true; 5200 } 5201 } 5202 5203 if (FieldRecord) { 5204 // Some additional restrictions exist on the variant members. 5205 if (!inUnion() && FieldRecord->isUnion() && 5206 FieldRecord->isAnonymousStructOrUnion()) { 5207 bool AllVariantFieldsAreConst = true; 5208 5209 // FIXME: Handle anonymous unions declared within anonymous unions. 5210 for (auto *UI : FieldRecord->fields()) { 5211 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5212 5213 if (!UnionFieldType.isConstQualified()) 5214 AllVariantFieldsAreConst = false; 5215 5216 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5217 if (UnionFieldRecord && 5218 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5219 UnionFieldType.getCVRQualifiers())) 5220 return true; 5221 } 5222 5223 // At least one member in each anonymous union must be non-const 5224 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5225 !FieldRecord->field_empty()) { 5226 if (Diagnose) 5227 S.Diag(FieldRecord->getLocation(), 5228 diag::note_deleted_default_ctor_all_const) 5229 << MD->getParent() << /*anonymous union*/1; 5230 return true; 5231 } 5232 5233 // Don't check the implicit member of the anonymous union type. 5234 // This is technically non-conformant, but sanity demands it. 5235 return false; 5236 } 5237 5238 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5239 FieldType.getCVRQualifiers())) 5240 return true; 5241 } 5242 5243 return false; 5244 } 5245 5246 /// C++11 [class.ctor] p5: 5247 /// A defaulted default constructor for a class X is defined as deleted if 5248 /// X is a union and all of its variant members are of const-qualified type. 5249 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5250 // This is a silly definition, because it gives an empty union a deleted 5251 // default constructor. Don't do that. 5252 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5253 !MD->getParent()->field_empty()) { 5254 if (Diagnose) 5255 S.Diag(MD->getParent()->getLocation(), 5256 diag::note_deleted_default_ctor_all_const) 5257 << MD->getParent() << /*not anonymous union*/0; 5258 return true; 5259 } 5260 return false; 5261 } 5262 5263 /// Determine whether a defaulted special member function should be defined as 5264 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5265 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5266 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5267 bool Diagnose) { 5268 if (MD->isInvalidDecl()) 5269 return false; 5270 CXXRecordDecl *RD = MD->getParent(); 5271 assert(!RD->isDependentType() && "do deletion after instantiation"); 5272 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5273 return false; 5274 5275 // C++11 [expr.lambda.prim]p19: 5276 // The closure type associated with a lambda-expression has a 5277 // deleted (8.4.3) default constructor and a deleted copy 5278 // assignment operator. 5279 if (RD->isLambda() && 5280 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5281 if (Diagnose) 5282 Diag(RD->getLocation(), diag::note_lambda_decl); 5283 return true; 5284 } 5285 5286 // For an anonymous struct or union, the copy and assignment special members 5287 // will never be used, so skip the check. For an anonymous union declared at 5288 // namespace scope, the constructor and destructor are used. 5289 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5290 RD->isAnonymousStructOrUnion()) 5291 return false; 5292 5293 // C++11 [class.copy]p7, p18: 5294 // If the class definition declares a move constructor or move assignment 5295 // operator, an implicitly declared copy constructor or copy assignment 5296 // operator is defined as deleted. 5297 if (MD->isImplicit() && 5298 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5299 CXXMethodDecl *UserDeclaredMove = 0; 5300 5301 // In Microsoft mode, a user-declared move only causes the deletion of the 5302 // corresponding copy operation, not both copy operations. 5303 if (RD->hasUserDeclaredMoveConstructor() && 5304 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5305 if (!Diagnose) return true; 5306 5307 // Find any user-declared move constructor. 5308 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 5309 E = RD->ctor_end(); I != E; ++I) { 5310 if (I->isMoveConstructor()) { 5311 UserDeclaredMove = *I; 5312 break; 5313 } 5314 } 5315 assert(UserDeclaredMove); 5316 } else if (RD->hasUserDeclaredMoveAssignment() && 5317 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5318 if (!Diagnose) return true; 5319 5320 // Find any user-declared move assignment operator. 5321 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5322 E = RD->method_end(); I != E; ++I) { 5323 if (I->isMoveAssignmentOperator()) { 5324 UserDeclaredMove = *I; 5325 break; 5326 } 5327 } 5328 assert(UserDeclaredMove); 5329 } 5330 5331 if (UserDeclaredMove) { 5332 Diag(UserDeclaredMove->getLocation(), 5333 diag::note_deleted_copy_user_declared_move) 5334 << (CSM == CXXCopyAssignment) << RD 5335 << UserDeclaredMove->isMoveAssignmentOperator(); 5336 return true; 5337 } 5338 } 5339 5340 // Do access control from the special member function 5341 ContextRAII MethodContext(*this, MD); 5342 5343 // C++11 [class.dtor]p5: 5344 // -- for a virtual destructor, lookup of the non-array deallocation function 5345 // results in an ambiguity or in a function that is deleted or inaccessible 5346 if (CSM == CXXDestructor && MD->isVirtual()) { 5347 FunctionDecl *OperatorDelete = 0; 5348 DeclarationName Name = 5349 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5350 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5351 OperatorDelete, false)) { 5352 if (Diagnose) 5353 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5354 return true; 5355 } 5356 } 5357 5358 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5359 5360 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5361 BE = RD->bases_end(); BI != BE; ++BI) 5362 if (!BI->isVirtual() && 5363 SMI.shouldDeleteForBase(BI)) 5364 return true; 5365 5366 // Per DR1611, do not consider virtual bases of constructors of abstract 5367 // classes, since we are not going to construct them. 5368 if (!RD->isAbstract() || !SMI.IsConstructor) { 5369 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5370 BE = RD->vbases_end(); 5371 BI != BE; ++BI) 5372 if (SMI.shouldDeleteForBase(BI)) 5373 return true; 5374 } 5375 5376 for (auto *FI : RD->fields()) 5377 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5378 SMI.shouldDeleteForField(FI)) 5379 return true; 5380 5381 if (SMI.shouldDeleteForAllConstMembers()) 5382 return true; 5383 5384 return false; 5385 } 5386 5387 /// Perform lookup for a special member of the specified kind, and determine 5388 /// whether it is trivial. If the triviality can be determined without the 5389 /// lookup, skip it. This is intended for use when determining whether a 5390 /// special member of a containing object is trivial, and thus does not ever 5391 /// perform overload resolution for default constructors. 5392 /// 5393 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5394 /// member that was most likely to be intended to be trivial, if any. 5395 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5396 Sema::CXXSpecialMember CSM, unsigned Quals, 5397 bool ConstRHS, CXXMethodDecl **Selected) { 5398 if (Selected) 5399 *Selected = 0; 5400 5401 switch (CSM) { 5402 case Sema::CXXInvalid: 5403 llvm_unreachable("not a special member"); 5404 5405 case Sema::CXXDefaultConstructor: 5406 // C++11 [class.ctor]p5: 5407 // A default constructor is trivial if: 5408 // - all the [direct subobjects] have trivial default constructors 5409 // 5410 // Note, no overload resolution is performed in this case. 5411 if (RD->hasTrivialDefaultConstructor()) 5412 return true; 5413 5414 if (Selected) { 5415 // If there's a default constructor which could have been trivial, dig it 5416 // out. Otherwise, if there's any user-provided default constructor, point 5417 // to that as an example of why there's not a trivial one. 5418 CXXConstructorDecl *DefCtor = 0; 5419 if (RD->needsImplicitDefaultConstructor()) 5420 S.DeclareImplicitDefaultConstructor(RD); 5421 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5422 CE = RD->ctor_end(); CI != CE; ++CI) { 5423 if (!CI->isDefaultConstructor()) 5424 continue; 5425 DefCtor = *CI; 5426 if (!DefCtor->isUserProvided()) 5427 break; 5428 } 5429 5430 *Selected = DefCtor; 5431 } 5432 5433 return false; 5434 5435 case Sema::CXXDestructor: 5436 // C++11 [class.dtor]p5: 5437 // A destructor is trivial if: 5438 // - all the direct [subobjects] have trivial destructors 5439 if (RD->hasTrivialDestructor()) 5440 return true; 5441 5442 if (Selected) { 5443 if (RD->needsImplicitDestructor()) 5444 S.DeclareImplicitDestructor(RD); 5445 *Selected = RD->getDestructor(); 5446 } 5447 5448 return false; 5449 5450 case Sema::CXXCopyConstructor: 5451 // C++11 [class.copy]p12: 5452 // A copy constructor is trivial if: 5453 // - the constructor selected to copy each direct [subobject] is trivial 5454 if (RD->hasTrivialCopyConstructor()) { 5455 if (Quals == Qualifiers::Const) 5456 // We must either select the trivial copy constructor or reach an 5457 // ambiguity; no need to actually perform overload resolution. 5458 return true; 5459 } else if (!Selected) { 5460 return false; 5461 } 5462 // In C++98, we are not supposed to perform overload resolution here, but we 5463 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5464 // cases like B as having a non-trivial copy constructor: 5465 // struct A { template<typename T> A(T&); }; 5466 // struct B { mutable A a; }; 5467 goto NeedOverloadResolution; 5468 5469 case Sema::CXXCopyAssignment: 5470 // C++11 [class.copy]p25: 5471 // A copy assignment operator is trivial if: 5472 // - the assignment operator selected to copy each direct [subobject] is 5473 // trivial 5474 if (RD->hasTrivialCopyAssignment()) { 5475 if (Quals == Qualifiers::Const) 5476 return true; 5477 } else if (!Selected) { 5478 return false; 5479 } 5480 // In C++98, we are not supposed to perform overload resolution here, but we 5481 // treat that as a language defect. 5482 goto NeedOverloadResolution; 5483 5484 case Sema::CXXMoveConstructor: 5485 case Sema::CXXMoveAssignment: 5486 NeedOverloadResolution: 5487 Sema::SpecialMemberOverloadResult *SMOR = 5488 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5489 5490 // The standard doesn't describe how to behave if the lookup is ambiguous. 5491 // We treat it as not making the member non-trivial, just like the standard 5492 // mandates for the default constructor. This should rarely matter, because 5493 // the member will also be deleted. 5494 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5495 return true; 5496 5497 if (!SMOR->getMethod()) { 5498 assert(SMOR->getKind() == 5499 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5500 return false; 5501 } 5502 5503 // We deliberately don't check if we found a deleted special member. We're 5504 // not supposed to! 5505 if (Selected) 5506 *Selected = SMOR->getMethod(); 5507 return SMOR->getMethod()->isTrivial(); 5508 } 5509 5510 llvm_unreachable("unknown special method kind"); 5511 } 5512 5513 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5514 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5515 CI != CE; ++CI) 5516 if (!CI->isImplicit()) 5517 return *CI; 5518 5519 // Look for constructor templates. 5520 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5521 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5522 if (CXXConstructorDecl *CD = 5523 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5524 return CD; 5525 } 5526 5527 return 0; 5528 } 5529 5530 /// The kind of subobject we are checking for triviality. The values of this 5531 /// enumeration are used in diagnostics. 5532 enum TrivialSubobjectKind { 5533 /// The subobject is a base class. 5534 TSK_BaseClass, 5535 /// The subobject is a non-static data member. 5536 TSK_Field, 5537 /// The object is actually the complete object. 5538 TSK_CompleteObject 5539 }; 5540 5541 /// Check whether the special member selected for a given type would be trivial. 5542 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5543 QualType SubType, bool ConstRHS, 5544 Sema::CXXSpecialMember CSM, 5545 TrivialSubobjectKind Kind, 5546 bool Diagnose) { 5547 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5548 if (!SubRD) 5549 return true; 5550 5551 CXXMethodDecl *Selected; 5552 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5553 ConstRHS, Diagnose ? &Selected : 0)) 5554 return true; 5555 5556 if (Diagnose) { 5557 if (ConstRHS) 5558 SubType.addConst(); 5559 5560 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5561 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5562 << Kind << SubType.getUnqualifiedType(); 5563 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5564 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5565 } else if (!Selected) 5566 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5567 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5568 else if (Selected->isUserProvided()) { 5569 if (Kind == TSK_CompleteObject) 5570 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5571 << Kind << SubType.getUnqualifiedType() << CSM; 5572 else { 5573 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5574 << Kind << SubType.getUnqualifiedType() << CSM; 5575 S.Diag(Selected->getLocation(), diag::note_declared_at); 5576 } 5577 } else { 5578 if (Kind != TSK_CompleteObject) 5579 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5580 << Kind << SubType.getUnqualifiedType() << CSM; 5581 5582 // Explain why the defaulted or deleted special member isn't trivial. 5583 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5584 } 5585 } 5586 5587 return false; 5588 } 5589 5590 /// Check whether the members of a class type allow a special member to be 5591 /// trivial. 5592 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5593 Sema::CXXSpecialMember CSM, 5594 bool ConstArg, bool Diagnose) { 5595 for (const auto *FI : RD->fields()) { 5596 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5597 continue; 5598 5599 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5600 5601 // Pretend anonymous struct or union members are members of this class. 5602 if (FI->isAnonymousStructOrUnion()) { 5603 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5604 CSM, ConstArg, Diagnose)) 5605 return false; 5606 continue; 5607 } 5608 5609 // C++11 [class.ctor]p5: 5610 // A default constructor is trivial if [...] 5611 // -- no non-static data member of its class has a 5612 // brace-or-equal-initializer 5613 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5614 if (Diagnose) 5615 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5616 return false; 5617 } 5618 5619 // Objective C ARC 4.3.5: 5620 // [...] nontrivally ownership-qualified types are [...] not trivially 5621 // default constructible, copy constructible, move constructible, copy 5622 // assignable, move assignable, or destructible [...] 5623 if (S.getLangOpts().ObjCAutoRefCount && 5624 FieldType.hasNonTrivialObjCLifetime()) { 5625 if (Diagnose) 5626 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5627 << RD << FieldType.getObjCLifetime(); 5628 return false; 5629 } 5630 5631 bool ConstRHS = ConstArg && !FI->isMutable(); 5632 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5633 CSM, TSK_Field, Diagnose)) 5634 return false; 5635 } 5636 5637 return true; 5638 } 5639 5640 /// Diagnose why the specified class does not have a trivial special member of 5641 /// the given kind. 5642 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5643 QualType Ty = Context.getRecordType(RD); 5644 5645 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5646 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5647 TSK_CompleteObject, /*Diagnose*/true); 5648 } 5649 5650 /// Determine whether a defaulted or deleted special member function is trivial, 5651 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5652 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5653 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5654 bool Diagnose) { 5655 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5656 5657 CXXRecordDecl *RD = MD->getParent(); 5658 5659 bool ConstArg = false; 5660 5661 // C++11 [class.copy]p12, p25: [DR1593] 5662 // A [special member] is trivial if [...] its parameter-type-list is 5663 // equivalent to the parameter-type-list of an implicit declaration [...] 5664 switch (CSM) { 5665 case CXXDefaultConstructor: 5666 case CXXDestructor: 5667 // Trivial default constructors and destructors cannot have parameters. 5668 break; 5669 5670 case CXXCopyConstructor: 5671 case CXXCopyAssignment: { 5672 // Trivial copy operations always have const, non-volatile parameter types. 5673 ConstArg = true; 5674 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5675 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5676 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5677 if (Diagnose) 5678 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5679 << Param0->getSourceRange() << Param0->getType() 5680 << Context.getLValueReferenceType( 5681 Context.getRecordType(RD).withConst()); 5682 return false; 5683 } 5684 break; 5685 } 5686 5687 case CXXMoveConstructor: 5688 case CXXMoveAssignment: { 5689 // Trivial move operations always have non-cv-qualified parameters. 5690 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5691 const RValueReferenceType *RT = 5692 Param0->getType()->getAs<RValueReferenceType>(); 5693 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5694 if (Diagnose) 5695 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5696 << Param0->getSourceRange() << Param0->getType() 5697 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5698 return false; 5699 } 5700 break; 5701 } 5702 5703 case CXXInvalid: 5704 llvm_unreachable("not a special member"); 5705 } 5706 5707 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5708 if (Diagnose) 5709 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5710 diag::note_nontrivial_default_arg) 5711 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5712 return false; 5713 } 5714 if (MD->isVariadic()) { 5715 if (Diagnose) 5716 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5717 return false; 5718 } 5719 5720 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5721 // A copy/move [constructor or assignment operator] is trivial if 5722 // -- the [member] selected to copy/move each direct base class subobject 5723 // is trivial 5724 // 5725 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5726 // A [default constructor or destructor] is trivial if 5727 // -- all the direct base classes have trivial [default constructors or 5728 // destructors] 5729 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5730 BE = RD->bases_end(); BI != BE; ++BI) 5731 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), BI->getType(), 5732 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5733 return false; 5734 5735 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5736 // A copy/move [constructor or assignment operator] for a class X is 5737 // trivial if 5738 // -- for each non-static data member of X that is of class type (or array 5739 // thereof), the constructor selected to copy/move that member is 5740 // trivial 5741 // 5742 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5743 // A [default constructor or destructor] is trivial if 5744 // -- for all of the non-static data members of its class that are of class 5745 // type (or array thereof), each such class has a trivial [default 5746 // constructor or destructor] 5747 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5748 return false; 5749 5750 // C++11 [class.dtor]p5: 5751 // A destructor is trivial if [...] 5752 // -- the destructor is not virtual 5753 if (CSM == CXXDestructor && MD->isVirtual()) { 5754 if (Diagnose) 5755 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5756 return false; 5757 } 5758 5759 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5760 // A [special member] for class X is trivial if [...] 5761 // -- class X has no virtual functions and no virtual base classes 5762 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5763 if (!Diagnose) 5764 return false; 5765 5766 if (RD->getNumVBases()) { 5767 // Check for virtual bases. We already know that the corresponding 5768 // member in all bases is trivial, so vbases must all be direct. 5769 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5770 assert(BS.isVirtual()); 5771 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5772 return false; 5773 } 5774 5775 // Must have a virtual method. 5776 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5777 ME = RD->method_end(); MI != ME; ++MI) { 5778 if (MI->isVirtual()) { 5779 SourceLocation MLoc = MI->getLocStart(); 5780 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5781 return false; 5782 } 5783 } 5784 5785 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5786 } 5787 5788 // Looks like it's trivial! 5789 return true; 5790 } 5791 5792 /// \brief Data used with FindHiddenVirtualMethod 5793 namespace { 5794 struct FindHiddenVirtualMethodData { 5795 Sema *S; 5796 CXXMethodDecl *Method; 5797 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5798 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5799 }; 5800 } 5801 5802 /// \brief Check whether any most overriden method from MD in Methods 5803 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5804 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5805 if (MD->size_overridden_methods() == 0) 5806 return Methods.count(MD->getCanonicalDecl()); 5807 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5808 E = MD->end_overridden_methods(); 5809 I != E; ++I) 5810 if (CheckMostOverridenMethods(*I, Methods)) 5811 return true; 5812 return false; 5813 } 5814 5815 /// \brief Member lookup function that determines whether a given C++ 5816 /// method overloads virtual methods in a base class without overriding any, 5817 /// to be used with CXXRecordDecl::lookupInBases(). 5818 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5819 CXXBasePath &Path, 5820 void *UserData) { 5821 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5822 5823 FindHiddenVirtualMethodData &Data 5824 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5825 5826 DeclarationName Name = Data.Method->getDeclName(); 5827 assert(Name.getNameKind() == DeclarationName::Identifier); 5828 5829 bool foundSameNameMethod = false; 5830 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5831 for (Path.Decls = BaseRecord->lookup(Name); 5832 !Path.Decls.empty(); 5833 Path.Decls = Path.Decls.slice(1)) { 5834 NamedDecl *D = Path.Decls.front(); 5835 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5836 MD = MD->getCanonicalDecl(); 5837 foundSameNameMethod = true; 5838 // Interested only in hidden virtual methods. 5839 if (!MD->isVirtual()) 5840 continue; 5841 // If the method we are checking overrides a method from its base 5842 // don't warn about the other overloaded methods. 5843 if (!Data.S->IsOverload(Data.Method, MD, false)) 5844 return true; 5845 // Collect the overload only if its hidden. 5846 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5847 overloadedMethods.push_back(MD); 5848 } 5849 } 5850 5851 if (foundSameNameMethod) 5852 Data.OverloadedMethods.append(overloadedMethods.begin(), 5853 overloadedMethods.end()); 5854 return foundSameNameMethod; 5855 } 5856 5857 /// \brief Add the most overriden methods from MD to Methods 5858 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5859 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5860 if (MD->size_overridden_methods() == 0) 5861 Methods.insert(MD->getCanonicalDecl()); 5862 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5863 E = MD->end_overridden_methods(); 5864 I != E; ++I) 5865 AddMostOverridenMethods(*I, Methods); 5866 } 5867 5868 /// \brief Check if a method overloads virtual methods in a base class without 5869 /// overriding any. 5870 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5871 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5872 if (!MD->getDeclName().isIdentifier()) 5873 return; 5874 5875 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5876 /*bool RecordPaths=*/false, 5877 /*bool DetectVirtual=*/false); 5878 FindHiddenVirtualMethodData Data; 5879 Data.Method = MD; 5880 Data.S = this; 5881 5882 // Keep the base methods that were overriden or introduced in the subclass 5883 // by 'using' in a set. A base method not in this set is hidden. 5884 CXXRecordDecl *DC = MD->getParent(); 5885 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5886 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5887 NamedDecl *ND = *I; 5888 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5889 ND = shad->getTargetDecl(); 5890 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5891 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5892 } 5893 5894 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5895 OverloadedMethods = Data.OverloadedMethods; 5896 } 5897 5898 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5899 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5900 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5901 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5902 PartialDiagnostic PD = PDiag( 5903 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5904 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5905 Diag(overloadedMD->getLocation(), PD); 5906 } 5907 } 5908 5909 /// \brief Diagnose methods which overload virtual methods in a base class 5910 /// without overriding any. 5911 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5912 if (MD->isInvalidDecl()) 5913 return; 5914 5915 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5916 MD->getLocation()) == DiagnosticsEngine::Ignored) 5917 return; 5918 5919 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5920 FindHiddenVirtualMethods(MD, OverloadedMethods); 5921 if (!OverloadedMethods.empty()) { 5922 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5923 << MD << (OverloadedMethods.size() > 1); 5924 5925 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5926 } 5927 } 5928 5929 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5930 Decl *TagDecl, 5931 SourceLocation LBrac, 5932 SourceLocation RBrac, 5933 AttributeList *AttrList) { 5934 if (!TagDecl) 5935 return; 5936 5937 AdjustDeclIfTemplate(TagDecl); 5938 5939 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5940 if (l->getKind() != AttributeList::AT_Visibility) 5941 continue; 5942 l->setInvalid(); 5943 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5944 l->getName(); 5945 } 5946 5947 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5948 // strict aliasing violation! 5949 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5950 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5951 5952 CheckCompletedCXXClass( 5953 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5954 } 5955 5956 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5957 /// special functions, such as the default constructor, copy 5958 /// constructor, or destructor, to the given C++ class (C++ 5959 /// [special]p1). This routine can only be executed just before the 5960 /// definition of the class is complete. 5961 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5962 if (!ClassDecl->hasUserDeclaredConstructor()) 5963 ++ASTContext::NumImplicitDefaultConstructors; 5964 5965 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5966 ++ASTContext::NumImplicitCopyConstructors; 5967 5968 // If the properties or semantics of the copy constructor couldn't be 5969 // determined while the class was being declared, force a declaration 5970 // of it now. 5971 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5972 DeclareImplicitCopyConstructor(ClassDecl); 5973 } 5974 5975 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5976 ++ASTContext::NumImplicitMoveConstructors; 5977 5978 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5979 DeclareImplicitMoveConstructor(ClassDecl); 5980 } 5981 5982 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5983 ++ASTContext::NumImplicitCopyAssignmentOperators; 5984 5985 // If we have a dynamic class, then the copy assignment operator may be 5986 // virtual, so we have to declare it immediately. This ensures that, e.g., 5987 // it shows up in the right place in the vtable and that we diagnose 5988 // problems with the implicit exception specification. 5989 if (ClassDecl->isDynamicClass() || 5990 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5991 DeclareImplicitCopyAssignment(ClassDecl); 5992 } 5993 5994 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5995 ++ASTContext::NumImplicitMoveAssignmentOperators; 5996 5997 // Likewise for the move assignment operator. 5998 if (ClassDecl->isDynamicClass() || 5999 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6000 DeclareImplicitMoveAssignment(ClassDecl); 6001 } 6002 6003 if (!ClassDecl->hasUserDeclaredDestructor()) { 6004 ++ASTContext::NumImplicitDestructors; 6005 6006 // If we have a dynamic class, then the destructor may be virtual, so we 6007 // have to declare the destructor immediately. This ensures that, e.g., it 6008 // shows up in the right place in the vtable and that we diagnose problems 6009 // with the implicit exception specification. 6010 if (ClassDecl->isDynamicClass() || 6011 ClassDecl->needsOverloadResolutionForDestructor()) 6012 DeclareImplicitDestructor(ClassDecl); 6013 } 6014 } 6015 6016 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 6017 if (!D) 6018 return; 6019 6020 int NumParamList = D->getNumTemplateParameterLists(); 6021 for (int i = 0; i < NumParamList; i++) { 6022 TemplateParameterList* Params = D->getTemplateParameterList(i); 6023 for (TemplateParameterList::iterator Param = Params->begin(), 6024 ParamEnd = Params->end(); 6025 Param != ParamEnd; ++Param) { 6026 NamedDecl *Named = cast<NamedDecl>(*Param); 6027 if (Named->getDeclName()) { 6028 S->AddDecl(Named); 6029 IdResolver.AddDecl(Named); 6030 } 6031 } 6032 } 6033 } 6034 6035 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6036 if (!D) 6037 return; 6038 6039 TemplateParameterList *Params = 0; 6040 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 6041 Params = Template->getTemplateParameters(); 6042 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6043 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6044 Params = PartialSpec->getTemplateParameters(); 6045 else 6046 return; 6047 6048 for (TemplateParameterList::iterator Param = Params->begin(), 6049 ParamEnd = Params->end(); 6050 Param != ParamEnd; ++Param) { 6051 NamedDecl *Named = cast<NamedDecl>(*Param); 6052 if (Named->getDeclName()) { 6053 S->AddDecl(Named); 6054 IdResolver.AddDecl(Named); 6055 } 6056 } 6057 } 6058 6059 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6060 if (!RecordD) return; 6061 AdjustDeclIfTemplate(RecordD); 6062 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6063 PushDeclContext(S, Record); 6064 } 6065 6066 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6067 if (!RecordD) return; 6068 PopDeclContext(); 6069 } 6070 6071 /// This is used to implement the constant expression evaluation part of the 6072 /// attribute enable_if extension. There is nothing in standard C++ which would 6073 /// require reentering parameters. 6074 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6075 if (!Param) 6076 return; 6077 6078 S->AddDecl(Param); 6079 if (Param->getDeclName()) 6080 IdResolver.AddDecl(Param); 6081 } 6082 6083 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6084 /// parsing a top-level (non-nested) C++ class, and we are now 6085 /// parsing those parts of the given Method declaration that could 6086 /// not be parsed earlier (C++ [class.mem]p2), such as default 6087 /// arguments. This action should enter the scope of the given 6088 /// Method declaration as if we had just parsed the qualified method 6089 /// name. However, it should not bring the parameters into scope; 6090 /// that will be performed by ActOnDelayedCXXMethodParameter. 6091 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6092 } 6093 6094 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6095 /// C++ method declaration. We're (re-)introducing the given 6096 /// function parameter into scope for use in parsing later parts of 6097 /// the method declaration. For example, we could see an 6098 /// ActOnParamDefaultArgument event for this parameter. 6099 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6100 if (!ParamD) 6101 return; 6102 6103 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6104 6105 // If this parameter has an unparsed default argument, clear it out 6106 // to make way for the parsed default argument. 6107 if (Param->hasUnparsedDefaultArg()) 6108 Param->setDefaultArg(0); 6109 6110 S->AddDecl(Param); 6111 if (Param->getDeclName()) 6112 IdResolver.AddDecl(Param); 6113 } 6114 6115 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6116 /// processing the delayed method declaration for Method. The method 6117 /// declaration is now considered finished. There may be a separate 6118 /// ActOnStartOfFunctionDef action later (not necessarily 6119 /// immediately!) for this method, if it was also defined inside the 6120 /// class body. 6121 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6122 if (!MethodD) 6123 return; 6124 6125 AdjustDeclIfTemplate(MethodD); 6126 6127 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6128 6129 // Now that we have our default arguments, check the constructor 6130 // again. It could produce additional diagnostics or affect whether 6131 // the class has implicitly-declared destructors, among other 6132 // things. 6133 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6134 CheckConstructor(Constructor); 6135 6136 // Check the default arguments, which we may have added. 6137 if (!Method->isInvalidDecl()) 6138 CheckCXXDefaultArguments(Method); 6139 } 6140 6141 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6142 /// the well-formedness of the constructor declarator @p D with type @p 6143 /// R. If there are any errors in the declarator, this routine will 6144 /// emit diagnostics and set the invalid bit to true. In any case, the type 6145 /// will be updated to reflect a well-formed type for the constructor and 6146 /// returned. 6147 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6148 StorageClass &SC) { 6149 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6150 6151 // C++ [class.ctor]p3: 6152 // A constructor shall not be virtual (10.3) or static (9.4). A 6153 // constructor can be invoked for a const, volatile or const 6154 // volatile object. A constructor shall not be declared const, 6155 // volatile, or const volatile (9.3.2). 6156 if (isVirtual) { 6157 if (!D.isInvalidType()) 6158 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6159 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6160 << SourceRange(D.getIdentifierLoc()); 6161 D.setInvalidType(); 6162 } 6163 if (SC == SC_Static) { 6164 if (!D.isInvalidType()) 6165 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6166 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6167 << SourceRange(D.getIdentifierLoc()); 6168 D.setInvalidType(); 6169 SC = SC_None; 6170 } 6171 6172 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6173 if (FTI.TypeQuals != 0) { 6174 if (FTI.TypeQuals & Qualifiers::Const) 6175 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6176 << "const" << SourceRange(D.getIdentifierLoc()); 6177 if (FTI.TypeQuals & Qualifiers::Volatile) 6178 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6179 << "volatile" << SourceRange(D.getIdentifierLoc()); 6180 if (FTI.TypeQuals & Qualifiers::Restrict) 6181 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6182 << "restrict" << SourceRange(D.getIdentifierLoc()); 6183 D.setInvalidType(); 6184 } 6185 6186 // C++0x [class.ctor]p4: 6187 // A constructor shall not be declared with a ref-qualifier. 6188 if (FTI.hasRefQualifier()) { 6189 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6190 << FTI.RefQualifierIsLValueRef 6191 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6192 D.setInvalidType(); 6193 } 6194 6195 // Rebuild the function type "R" without any type qualifiers (in 6196 // case any of the errors above fired) and with "void" as the 6197 // return type, since constructors don't have return types. 6198 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6199 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6200 return R; 6201 6202 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6203 EPI.TypeQuals = 0; 6204 EPI.RefQualifier = RQ_None; 6205 6206 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6207 } 6208 6209 /// CheckConstructor - Checks a fully-formed constructor for 6210 /// well-formedness, issuing any diagnostics required. Returns true if 6211 /// the constructor declarator is invalid. 6212 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6213 CXXRecordDecl *ClassDecl 6214 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6215 if (!ClassDecl) 6216 return Constructor->setInvalidDecl(); 6217 6218 // C++ [class.copy]p3: 6219 // A declaration of a constructor for a class X is ill-formed if 6220 // its first parameter is of type (optionally cv-qualified) X and 6221 // either there are no other parameters or else all other 6222 // parameters have default arguments. 6223 if (!Constructor->isInvalidDecl() && 6224 ((Constructor->getNumParams() == 1) || 6225 (Constructor->getNumParams() > 1 && 6226 Constructor->getParamDecl(1)->hasDefaultArg())) && 6227 Constructor->getTemplateSpecializationKind() 6228 != TSK_ImplicitInstantiation) { 6229 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6230 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6231 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6232 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6233 const char *ConstRef 6234 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6235 : " const &"; 6236 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6237 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6238 6239 // FIXME: Rather that making the constructor invalid, we should endeavor 6240 // to fix the type. 6241 Constructor->setInvalidDecl(); 6242 } 6243 } 6244 } 6245 6246 /// CheckDestructor - Checks a fully-formed destructor definition for 6247 /// well-formedness, issuing any diagnostics required. Returns true 6248 /// on error. 6249 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6250 CXXRecordDecl *RD = Destructor->getParent(); 6251 6252 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6253 SourceLocation Loc; 6254 6255 if (!Destructor->isImplicit()) 6256 Loc = Destructor->getLocation(); 6257 else 6258 Loc = RD->getLocation(); 6259 6260 // If we have a virtual destructor, look up the deallocation function 6261 FunctionDecl *OperatorDelete = 0; 6262 DeclarationName Name = 6263 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6264 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6265 return true; 6266 // If there's no class-specific operator delete, look up the global 6267 // non-array delete. 6268 if (!OperatorDelete) 6269 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6270 6271 MarkFunctionReferenced(Loc, OperatorDelete); 6272 6273 Destructor->setOperatorDelete(OperatorDelete); 6274 } 6275 6276 return false; 6277 } 6278 6279 static inline bool 6280 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6281 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6282 FTI.Params[0].Param && 6283 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()); 6284 } 6285 6286 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6287 /// the well-formednes of the destructor declarator @p D with type @p 6288 /// R. If there are any errors in the declarator, this routine will 6289 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6290 /// will be updated to reflect a well-formed type for the destructor and 6291 /// returned. 6292 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6293 StorageClass& SC) { 6294 // C++ [class.dtor]p1: 6295 // [...] A typedef-name that names a class is a class-name 6296 // (7.1.3); however, a typedef-name that names a class shall not 6297 // be used as the identifier in the declarator for a destructor 6298 // declaration. 6299 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6300 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6301 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6302 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6303 else if (const TemplateSpecializationType *TST = 6304 DeclaratorType->getAs<TemplateSpecializationType>()) 6305 if (TST->isTypeAlias()) 6306 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6307 << DeclaratorType << 1; 6308 6309 // C++ [class.dtor]p2: 6310 // A destructor is used to destroy objects of its class type. A 6311 // destructor takes no parameters, and no return type can be 6312 // specified for it (not even void). The address of a destructor 6313 // shall not be taken. A destructor shall not be static. A 6314 // destructor can be invoked for a const, volatile or const 6315 // volatile object. A destructor shall not be declared const, 6316 // volatile or const volatile (9.3.2). 6317 if (SC == SC_Static) { 6318 if (!D.isInvalidType()) 6319 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6320 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6321 << SourceRange(D.getIdentifierLoc()) 6322 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6323 6324 SC = SC_None; 6325 } 6326 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6327 // Destructors don't have return types, but the parser will 6328 // happily parse something like: 6329 // 6330 // class X { 6331 // float ~X(); 6332 // }; 6333 // 6334 // The return type will be eliminated later. 6335 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6336 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6337 << SourceRange(D.getIdentifierLoc()); 6338 } 6339 6340 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6341 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6342 if (FTI.TypeQuals & Qualifiers::Const) 6343 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6344 << "const" << SourceRange(D.getIdentifierLoc()); 6345 if (FTI.TypeQuals & Qualifiers::Volatile) 6346 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6347 << "volatile" << SourceRange(D.getIdentifierLoc()); 6348 if (FTI.TypeQuals & Qualifiers::Restrict) 6349 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6350 << "restrict" << SourceRange(D.getIdentifierLoc()); 6351 D.setInvalidType(); 6352 } 6353 6354 // C++0x [class.dtor]p2: 6355 // A destructor shall not be declared with a ref-qualifier. 6356 if (FTI.hasRefQualifier()) { 6357 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6358 << FTI.RefQualifierIsLValueRef 6359 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6360 D.setInvalidType(); 6361 } 6362 6363 // Make sure we don't have any parameters. 6364 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) { 6365 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6366 6367 // Delete the parameters. 6368 FTI.freeParams(); 6369 D.setInvalidType(); 6370 } 6371 6372 // Make sure the destructor isn't variadic. 6373 if (FTI.isVariadic) { 6374 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6375 D.setInvalidType(); 6376 } 6377 6378 // Rebuild the function type "R" without any type qualifiers or 6379 // parameters (in case any of the errors above fired) and with 6380 // "void" as the return type, since destructors don't have return 6381 // types. 6382 if (!D.isInvalidType()) 6383 return R; 6384 6385 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6386 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6387 EPI.Variadic = false; 6388 EPI.TypeQuals = 0; 6389 EPI.RefQualifier = RQ_None; 6390 return Context.getFunctionType(Context.VoidTy, None, EPI); 6391 } 6392 6393 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6394 /// well-formednes of the conversion function declarator @p D with 6395 /// type @p R. If there are any errors in the declarator, this routine 6396 /// will emit diagnostics and return true. Otherwise, it will return 6397 /// false. Either way, the type @p R will be updated to reflect a 6398 /// well-formed type for the conversion operator. 6399 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6400 StorageClass& SC) { 6401 // C++ [class.conv.fct]p1: 6402 // Neither parameter types nor return type can be specified. The 6403 // type of a conversion function (8.3.5) is "function taking no 6404 // parameter returning conversion-type-id." 6405 if (SC == SC_Static) { 6406 if (!D.isInvalidType()) 6407 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6408 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6409 << D.getName().getSourceRange(); 6410 D.setInvalidType(); 6411 SC = SC_None; 6412 } 6413 6414 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6415 6416 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6417 // Conversion functions don't have return types, but the parser will 6418 // happily parse something like: 6419 // 6420 // class X { 6421 // float operator bool(); 6422 // }; 6423 // 6424 // The return type will be changed later anyway. 6425 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6426 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6427 << SourceRange(D.getIdentifierLoc()); 6428 D.setInvalidType(); 6429 } 6430 6431 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6432 6433 // Make sure we don't have any parameters. 6434 if (Proto->getNumParams() > 0) { 6435 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6436 6437 // Delete the parameters. 6438 D.getFunctionTypeInfo().freeParams(); 6439 D.setInvalidType(); 6440 } else if (Proto->isVariadic()) { 6441 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6442 D.setInvalidType(); 6443 } 6444 6445 // Diagnose "&operator bool()" and other such nonsense. This 6446 // is actually a gcc extension which we don't support. 6447 if (Proto->getReturnType() != ConvType) { 6448 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6449 << Proto->getReturnType(); 6450 D.setInvalidType(); 6451 ConvType = Proto->getReturnType(); 6452 } 6453 6454 // C++ [class.conv.fct]p4: 6455 // The conversion-type-id shall not represent a function type nor 6456 // an array type. 6457 if (ConvType->isArrayType()) { 6458 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6459 ConvType = Context.getPointerType(ConvType); 6460 D.setInvalidType(); 6461 } else if (ConvType->isFunctionType()) { 6462 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6463 ConvType = Context.getPointerType(ConvType); 6464 D.setInvalidType(); 6465 } 6466 6467 // Rebuild the function type "R" without any parameters (in case any 6468 // of the errors above fired) and with the conversion type as the 6469 // return type. 6470 if (D.isInvalidType()) 6471 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6472 6473 // C++0x explicit conversion operators. 6474 if (D.getDeclSpec().isExplicitSpecified()) 6475 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6476 getLangOpts().CPlusPlus11 ? 6477 diag::warn_cxx98_compat_explicit_conversion_functions : 6478 diag::ext_explicit_conversion_functions) 6479 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6480 } 6481 6482 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6483 /// the declaration of the given C++ conversion function. This routine 6484 /// is responsible for recording the conversion function in the C++ 6485 /// class, if possible. 6486 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6487 assert(Conversion && "Expected to receive a conversion function declaration"); 6488 6489 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6490 6491 // Make sure we aren't redeclaring the conversion function. 6492 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6493 6494 // C++ [class.conv.fct]p1: 6495 // [...] A conversion function is never used to convert a 6496 // (possibly cv-qualified) object to the (possibly cv-qualified) 6497 // same object type (or a reference to it), to a (possibly 6498 // cv-qualified) base class of that type (or a reference to it), 6499 // or to (possibly cv-qualified) void. 6500 // FIXME: Suppress this warning if the conversion function ends up being a 6501 // virtual function that overrides a virtual function in a base class. 6502 QualType ClassType 6503 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6504 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6505 ConvType = ConvTypeRef->getPointeeType(); 6506 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6507 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6508 /* Suppress diagnostics for instantiations. */; 6509 else if (ConvType->isRecordType()) { 6510 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6511 if (ConvType == ClassType) 6512 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6513 << ClassType; 6514 else if (IsDerivedFrom(ClassType, ConvType)) 6515 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6516 << ClassType << ConvType; 6517 } else if (ConvType->isVoidType()) { 6518 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6519 << ClassType << ConvType; 6520 } 6521 6522 if (FunctionTemplateDecl *ConversionTemplate 6523 = Conversion->getDescribedFunctionTemplate()) 6524 return ConversionTemplate; 6525 6526 return Conversion; 6527 } 6528 6529 //===----------------------------------------------------------------------===// 6530 // Namespace Handling 6531 //===----------------------------------------------------------------------===// 6532 6533 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6534 /// reopened. 6535 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6536 SourceLocation Loc, 6537 IdentifierInfo *II, bool *IsInline, 6538 NamespaceDecl *PrevNS) { 6539 assert(*IsInline != PrevNS->isInline()); 6540 6541 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6542 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6543 // inline namespaces, with the intention of bringing names into namespace std. 6544 // 6545 // We support this just well enough to get that case working; this is not 6546 // sufficient to support reopening namespaces as inline in general. 6547 if (*IsInline && II && II->getName().startswith("__atomic") && 6548 S.getSourceManager().isInSystemHeader(Loc)) { 6549 // Mark all prior declarations of the namespace as inline. 6550 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6551 NS = NS->getPreviousDecl()) 6552 NS->setInline(*IsInline); 6553 // Patch up the lookup table for the containing namespace. This isn't really 6554 // correct, but it's good enough for this particular case. 6555 for (auto *I : PrevNS->decls()) 6556 if (auto *ND = dyn_cast<NamedDecl>(I)) 6557 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6558 return; 6559 } 6560 6561 if (PrevNS->isInline()) 6562 // The user probably just forgot the 'inline', so suggest that it 6563 // be added back. 6564 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6565 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6566 else 6567 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6568 << IsInline; 6569 6570 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6571 *IsInline = PrevNS->isInline(); 6572 } 6573 6574 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6575 /// definition. 6576 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6577 SourceLocation InlineLoc, 6578 SourceLocation NamespaceLoc, 6579 SourceLocation IdentLoc, 6580 IdentifierInfo *II, 6581 SourceLocation LBrace, 6582 AttributeList *AttrList) { 6583 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6584 // For anonymous namespace, take the location of the left brace. 6585 SourceLocation Loc = II ? IdentLoc : LBrace; 6586 bool IsInline = InlineLoc.isValid(); 6587 bool IsInvalid = false; 6588 bool IsStd = false; 6589 bool AddToKnown = false; 6590 Scope *DeclRegionScope = NamespcScope->getParent(); 6591 6592 NamespaceDecl *PrevNS = 0; 6593 if (II) { 6594 // C++ [namespace.def]p2: 6595 // The identifier in an original-namespace-definition shall not 6596 // have been previously defined in the declarative region in 6597 // which the original-namespace-definition appears. The 6598 // identifier in an original-namespace-definition is the name of 6599 // the namespace. Subsequently in that declarative region, it is 6600 // treated as an original-namespace-name. 6601 // 6602 // Since namespace names are unique in their scope, and we don't 6603 // look through using directives, just look for any ordinary names. 6604 6605 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6606 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6607 Decl::IDNS_Namespace; 6608 NamedDecl *PrevDecl = 0; 6609 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6610 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6611 ++I) { 6612 if ((*I)->getIdentifierNamespace() & IDNS) { 6613 PrevDecl = *I; 6614 break; 6615 } 6616 } 6617 6618 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6619 6620 if (PrevNS) { 6621 // This is an extended namespace definition. 6622 if (IsInline != PrevNS->isInline()) 6623 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6624 &IsInline, PrevNS); 6625 } else if (PrevDecl) { 6626 // This is an invalid name redefinition. 6627 Diag(Loc, diag::err_redefinition_different_kind) 6628 << II; 6629 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6630 IsInvalid = true; 6631 // Continue on to push Namespc as current DeclContext and return it. 6632 } else if (II->isStr("std") && 6633 CurContext->getRedeclContext()->isTranslationUnit()) { 6634 // This is the first "real" definition of the namespace "std", so update 6635 // our cache of the "std" namespace to point at this definition. 6636 PrevNS = getStdNamespace(); 6637 IsStd = true; 6638 AddToKnown = !IsInline; 6639 } else { 6640 // We've seen this namespace for the first time. 6641 AddToKnown = !IsInline; 6642 } 6643 } else { 6644 // Anonymous namespaces. 6645 6646 // Determine whether the parent already has an anonymous namespace. 6647 DeclContext *Parent = CurContext->getRedeclContext(); 6648 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6649 PrevNS = TU->getAnonymousNamespace(); 6650 } else { 6651 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6652 PrevNS = ND->getAnonymousNamespace(); 6653 } 6654 6655 if (PrevNS && IsInline != PrevNS->isInline()) 6656 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6657 &IsInline, PrevNS); 6658 } 6659 6660 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6661 StartLoc, Loc, II, PrevNS); 6662 if (IsInvalid) 6663 Namespc->setInvalidDecl(); 6664 6665 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6666 6667 // FIXME: Should we be merging attributes? 6668 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6669 PushNamespaceVisibilityAttr(Attr, Loc); 6670 6671 if (IsStd) 6672 StdNamespace = Namespc; 6673 if (AddToKnown) 6674 KnownNamespaces[Namespc] = false; 6675 6676 if (II) { 6677 PushOnScopeChains(Namespc, DeclRegionScope); 6678 } else { 6679 // Link the anonymous namespace into its parent. 6680 DeclContext *Parent = CurContext->getRedeclContext(); 6681 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6682 TU->setAnonymousNamespace(Namespc); 6683 } else { 6684 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6685 } 6686 6687 CurContext->addDecl(Namespc); 6688 6689 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6690 // behaves as if it were replaced by 6691 // namespace unique { /* empty body */ } 6692 // using namespace unique; 6693 // namespace unique { namespace-body } 6694 // where all occurrences of 'unique' in a translation unit are 6695 // replaced by the same identifier and this identifier differs 6696 // from all other identifiers in the entire program. 6697 6698 // We just create the namespace with an empty name and then add an 6699 // implicit using declaration, just like the standard suggests. 6700 // 6701 // CodeGen enforces the "universally unique" aspect by giving all 6702 // declarations semantically contained within an anonymous 6703 // namespace internal linkage. 6704 6705 if (!PrevNS) { 6706 UsingDirectiveDecl* UD 6707 = UsingDirectiveDecl::Create(Context, Parent, 6708 /* 'using' */ LBrace, 6709 /* 'namespace' */ SourceLocation(), 6710 /* qualifier */ NestedNameSpecifierLoc(), 6711 /* identifier */ SourceLocation(), 6712 Namespc, 6713 /* Ancestor */ Parent); 6714 UD->setImplicit(); 6715 Parent->addDecl(UD); 6716 } 6717 } 6718 6719 ActOnDocumentableDecl(Namespc); 6720 6721 // Although we could have an invalid decl (i.e. the namespace name is a 6722 // redefinition), push it as current DeclContext and try to continue parsing. 6723 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6724 // for the namespace has the declarations that showed up in that particular 6725 // namespace definition. 6726 PushDeclContext(NamespcScope, Namespc); 6727 return Namespc; 6728 } 6729 6730 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6731 /// is a namespace alias, returns the namespace it points to. 6732 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6733 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6734 return AD->getNamespace(); 6735 return dyn_cast_or_null<NamespaceDecl>(D); 6736 } 6737 6738 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6739 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6740 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6741 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6742 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6743 Namespc->setRBraceLoc(RBrace); 6744 PopDeclContext(); 6745 if (Namespc->hasAttr<VisibilityAttr>()) 6746 PopPragmaVisibility(true, RBrace); 6747 } 6748 6749 CXXRecordDecl *Sema::getStdBadAlloc() const { 6750 return cast_or_null<CXXRecordDecl>( 6751 StdBadAlloc.get(Context.getExternalSource())); 6752 } 6753 6754 NamespaceDecl *Sema::getStdNamespace() const { 6755 return cast_or_null<NamespaceDecl>( 6756 StdNamespace.get(Context.getExternalSource())); 6757 } 6758 6759 /// \brief Retrieve the special "std" namespace, which may require us to 6760 /// implicitly define the namespace. 6761 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6762 if (!StdNamespace) { 6763 // The "std" namespace has not yet been defined, so build one implicitly. 6764 StdNamespace = NamespaceDecl::Create(Context, 6765 Context.getTranslationUnitDecl(), 6766 /*Inline=*/false, 6767 SourceLocation(), SourceLocation(), 6768 &PP.getIdentifierTable().get("std"), 6769 /*PrevDecl=*/0); 6770 getStdNamespace()->setImplicit(true); 6771 } 6772 6773 return getStdNamespace(); 6774 } 6775 6776 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6777 assert(getLangOpts().CPlusPlus && 6778 "Looking for std::initializer_list outside of C++."); 6779 6780 // We're looking for implicit instantiations of 6781 // template <typename E> class std::initializer_list. 6782 6783 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6784 return false; 6785 6786 ClassTemplateDecl *Template = 0; 6787 const TemplateArgument *Arguments = 0; 6788 6789 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6790 6791 ClassTemplateSpecializationDecl *Specialization = 6792 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6793 if (!Specialization) 6794 return false; 6795 6796 Template = Specialization->getSpecializedTemplate(); 6797 Arguments = Specialization->getTemplateArgs().data(); 6798 } else if (const TemplateSpecializationType *TST = 6799 Ty->getAs<TemplateSpecializationType>()) { 6800 Template = dyn_cast_or_null<ClassTemplateDecl>( 6801 TST->getTemplateName().getAsTemplateDecl()); 6802 Arguments = TST->getArgs(); 6803 } 6804 if (!Template) 6805 return false; 6806 6807 if (!StdInitializerList) { 6808 // Haven't recognized std::initializer_list yet, maybe this is it. 6809 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6810 if (TemplateClass->getIdentifier() != 6811 &PP.getIdentifierTable().get("initializer_list") || 6812 !getStdNamespace()->InEnclosingNamespaceSetOf( 6813 TemplateClass->getDeclContext())) 6814 return false; 6815 // This is a template called std::initializer_list, but is it the right 6816 // template? 6817 TemplateParameterList *Params = Template->getTemplateParameters(); 6818 if (Params->getMinRequiredArguments() != 1) 6819 return false; 6820 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6821 return false; 6822 6823 // It's the right template. 6824 StdInitializerList = Template; 6825 } 6826 6827 if (Template != StdInitializerList) 6828 return false; 6829 6830 // This is an instance of std::initializer_list. Find the argument type. 6831 if (Element) 6832 *Element = Arguments[0].getAsType(); 6833 return true; 6834 } 6835 6836 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6837 NamespaceDecl *Std = S.getStdNamespace(); 6838 if (!Std) { 6839 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6840 return 0; 6841 } 6842 6843 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6844 Loc, Sema::LookupOrdinaryName); 6845 if (!S.LookupQualifiedName(Result, Std)) { 6846 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6847 return 0; 6848 } 6849 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6850 if (!Template) { 6851 Result.suppressDiagnostics(); 6852 // We found something weird. Complain about the first thing we found. 6853 NamedDecl *Found = *Result.begin(); 6854 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6855 return 0; 6856 } 6857 6858 // We found some template called std::initializer_list. Now verify that it's 6859 // correct. 6860 TemplateParameterList *Params = Template->getTemplateParameters(); 6861 if (Params->getMinRequiredArguments() != 1 || 6862 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6863 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6864 return 0; 6865 } 6866 6867 return Template; 6868 } 6869 6870 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6871 if (!StdInitializerList) { 6872 StdInitializerList = LookupStdInitializerList(*this, Loc); 6873 if (!StdInitializerList) 6874 return QualType(); 6875 } 6876 6877 TemplateArgumentListInfo Args(Loc, Loc); 6878 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6879 Context.getTrivialTypeSourceInfo(Element, 6880 Loc))); 6881 return Context.getCanonicalType( 6882 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6883 } 6884 6885 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6886 // C++ [dcl.init.list]p2: 6887 // A constructor is an initializer-list constructor if its first parameter 6888 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6889 // std::initializer_list<E> for some type E, and either there are no other 6890 // parameters or else all other parameters have default arguments. 6891 if (Ctor->getNumParams() < 1 || 6892 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6893 return false; 6894 6895 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6896 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6897 ArgType = RT->getPointeeType().getUnqualifiedType(); 6898 6899 return isStdInitializerList(ArgType, 0); 6900 } 6901 6902 /// \brief Determine whether a using statement is in a context where it will be 6903 /// apply in all contexts. 6904 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6905 switch (CurContext->getDeclKind()) { 6906 case Decl::TranslationUnit: 6907 return true; 6908 case Decl::LinkageSpec: 6909 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6910 default: 6911 return false; 6912 } 6913 } 6914 6915 namespace { 6916 6917 // Callback to only accept typo corrections that are namespaces. 6918 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6919 public: 6920 bool ValidateCandidate(const TypoCorrection &candidate) override { 6921 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6922 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6923 return false; 6924 } 6925 }; 6926 6927 } 6928 6929 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6930 CXXScopeSpec &SS, 6931 SourceLocation IdentLoc, 6932 IdentifierInfo *Ident) { 6933 NamespaceValidatorCCC Validator; 6934 R.clear(); 6935 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6936 R.getLookupKind(), Sc, &SS, 6937 Validator)) { 6938 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6939 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6940 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6941 Ident->getName().equals(CorrectedStr); 6942 S.diagnoseTypo(Corrected, 6943 S.PDiag(diag::err_using_directive_member_suggest) 6944 << Ident << DC << DroppedSpecifier << SS.getRange(), 6945 S.PDiag(diag::note_namespace_defined_here)); 6946 } else { 6947 S.diagnoseTypo(Corrected, 6948 S.PDiag(diag::err_using_directive_suggest) << Ident, 6949 S.PDiag(diag::note_namespace_defined_here)); 6950 } 6951 R.addDecl(Corrected.getCorrectionDecl()); 6952 return true; 6953 } 6954 return false; 6955 } 6956 6957 Decl *Sema::ActOnUsingDirective(Scope *S, 6958 SourceLocation UsingLoc, 6959 SourceLocation NamespcLoc, 6960 CXXScopeSpec &SS, 6961 SourceLocation IdentLoc, 6962 IdentifierInfo *NamespcName, 6963 AttributeList *AttrList) { 6964 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6965 assert(NamespcName && "Invalid NamespcName."); 6966 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6967 6968 // This can only happen along a recovery path. 6969 while (S->getFlags() & Scope::TemplateParamScope) 6970 S = S->getParent(); 6971 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6972 6973 UsingDirectiveDecl *UDir = 0; 6974 NestedNameSpecifier *Qualifier = 0; 6975 if (SS.isSet()) 6976 Qualifier = SS.getScopeRep(); 6977 6978 // Lookup namespace name. 6979 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6980 LookupParsedName(R, S, &SS); 6981 if (R.isAmbiguous()) 6982 return 0; 6983 6984 if (R.empty()) { 6985 R.clear(); 6986 // Allow "using namespace std;" or "using namespace ::std;" even if 6987 // "std" hasn't been defined yet, for GCC compatibility. 6988 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6989 NamespcName->isStr("std")) { 6990 Diag(IdentLoc, diag::ext_using_undefined_std); 6991 R.addDecl(getOrCreateStdNamespace()); 6992 R.resolveKind(); 6993 } 6994 // Otherwise, attempt typo correction. 6995 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6996 } 6997 6998 if (!R.empty()) { 6999 NamedDecl *Named = R.getFoundDecl(); 7000 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7001 && "expected namespace decl"); 7002 // C++ [namespace.udir]p1: 7003 // A using-directive specifies that the names in the nominated 7004 // namespace can be used in the scope in which the 7005 // using-directive appears after the using-directive. During 7006 // unqualified name lookup (3.4.1), the names appear as if they 7007 // were declared in the nearest enclosing namespace which 7008 // contains both the using-directive and the nominated 7009 // namespace. [Note: in this context, "contains" means "contains 7010 // directly or indirectly". ] 7011 7012 // Find enclosing context containing both using-directive and 7013 // nominated namespace. 7014 NamespaceDecl *NS = getNamespaceDecl(Named); 7015 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7016 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7017 CommonAncestor = CommonAncestor->getParent(); 7018 7019 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7020 SS.getWithLocInContext(Context), 7021 IdentLoc, Named, CommonAncestor); 7022 7023 if (IsUsingDirectiveInToplevelContext(CurContext) && 7024 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7025 Diag(IdentLoc, diag::warn_using_directive_in_header); 7026 } 7027 7028 PushUsingDirective(S, UDir); 7029 } else { 7030 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7031 } 7032 7033 if (UDir) 7034 ProcessDeclAttributeList(S, UDir, AttrList); 7035 7036 return UDir; 7037 } 7038 7039 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7040 // If the scope has an associated entity and the using directive is at 7041 // namespace or translation unit scope, add the UsingDirectiveDecl into 7042 // its lookup structure so qualified name lookup can find it. 7043 DeclContext *Ctx = S->getEntity(); 7044 if (Ctx && !Ctx->isFunctionOrMethod()) 7045 Ctx->addDecl(UDir); 7046 else 7047 // Otherwise, it is at block sope. The using-directives will affect lookup 7048 // only to the end of the scope. 7049 S->PushUsingDirective(UDir); 7050 } 7051 7052 7053 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7054 AccessSpecifier AS, 7055 bool HasUsingKeyword, 7056 SourceLocation UsingLoc, 7057 CXXScopeSpec &SS, 7058 UnqualifiedId &Name, 7059 AttributeList *AttrList, 7060 bool HasTypenameKeyword, 7061 SourceLocation TypenameLoc) { 7062 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7063 7064 switch (Name.getKind()) { 7065 case UnqualifiedId::IK_ImplicitSelfParam: 7066 case UnqualifiedId::IK_Identifier: 7067 case UnqualifiedId::IK_OperatorFunctionId: 7068 case UnqualifiedId::IK_LiteralOperatorId: 7069 case UnqualifiedId::IK_ConversionFunctionId: 7070 break; 7071 7072 case UnqualifiedId::IK_ConstructorName: 7073 case UnqualifiedId::IK_ConstructorTemplateId: 7074 // C++11 inheriting constructors. 7075 Diag(Name.getLocStart(), 7076 getLangOpts().CPlusPlus11 ? 7077 diag::warn_cxx98_compat_using_decl_constructor : 7078 diag::err_using_decl_constructor) 7079 << SS.getRange(); 7080 7081 if (getLangOpts().CPlusPlus11) break; 7082 7083 return 0; 7084 7085 case UnqualifiedId::IK_DestructorName: 7086 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7087 << SS.getRange(); 7088 return 0; 7089 7090 case UnqualifiedId::IK_TemplateId: 7091 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7092 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7093 return 0; 7094 } 7095 7096 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7097 DeclarationName TargetName = TargetNameInfo.getName(); 7098 if (!TargetName) 7099 return 0; 7100 7101 // Warn about access declarations. 7102 if (!HasUsingKeyword) { 7103 Diag(Name.getLocStart(), 7104 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7105 : diag::warn_access_decl_deprecated) 7106 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7107 } 7108 7109 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7110 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7111 return 0; 7112 7113 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7114 TargetNameInfo, AttrList, 7115 /* IsInstantiation */ false, 7116 HasTypenameKeyword, TypenameLoc); 7117 if (UD) 7118 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7119 7120 return UD; 7121 } 7122 7123 /// \brief Determine whether a using declaration considers the given 7124 /// declarations as "equivalent", e.g., if they are redeclarations of 7125 /// the same entity or are both typedefs of the same type. 7126 static bool 7127 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7128 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7129 return true; 7130 7131 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7132 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7133 return Context.hasSameType(TD1->getUnderlyingType(), 7134 TD2->getUnderlyingType()); 7135 7136 return false; 7137 } 7138 7139 7140 /// Determines whether to create a using shadow decl for a particular 7141 /// decl, given the set of decls existing prior to this using lookup. 7142 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7143 const LookupResult &Previous, 7144 UsingShadowDecl *&PrevShadow) { 7145 // Diagnose finding a decl which is not from a base class of the 7146 // current class. We do this now because there are cases where this 7147 // function will silently decide not to build a shadow decl, which 7148 // will pre-empt further diagnostics. 7149 // 7150 // We don't need to do this in C++0x because we do the check once on 7151 // the qualifier. 7152 // 7153 // FIXME: diagnose the following if we care enough: 7154 // struct A { int foo; }; 7155 // struct B : A { using A::foo; }; 7156 // template <class T> struct C : A {}; 7157 // template <class T> struct D : C<T> { using B::foo; } // <--- 7158 // This is invalid (during instantiation) in C++03 because B::foo 7159 // resolves to the using decl in B, which is not a base class of D<T>. 7160 // We can't diagnose it immediately because C<T> is an unknown 7161 // specialization. The UsingShadowDecl in D<T> then points directly 7162 // to A::foo, which will look well-formed when we instantiate. 7163 // The right solution is to not collapse the shadow-decl chain. 7164 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7165 DeclContext *OrigDC = Orig->getDeclContext(); 7166 7167 // Handle enums and anonymous structs. 7168 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7169 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7170 while (OrigRec->isAnonymousStructOrUnion()) 7171 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7172 7173 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7174 if (OrigDC == CurContext) { 7175 Diag(Using->getLocation(), 7176 diag::err_using_decl_nested_name_specifier_is_current_class) 7177 << Using->getQualifierLoc().getSourceRange(); 7178 Diag(Orig->getLocation(), diag::note_using_decl_target); 7179 return true; 7180 } 7181 7182 Diag(Using->getQualifierLoc().getBeginLoc(), 7183 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7184 << Using->getQualifier() 7185 << cast<CXXRecordDecl>(CurContext) 7186 << Using->getQualifierLoc().getSourceRange(); 7187 Diag(Orig->getLocation(), diag::note_using_decl_target); 7188 return true; 7189 } 7190 } 7191 7192 if (Previous.empty()) return false; 7193 7194 NamedDecl *Target = Orig; 7195 if (isa<UsingShadowDecl>(Target)) 7196 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7197 7198 // If the target happens to be one of the previous declarations, we 7199 // don't have a conflict. 7200 // 7201 // FIXME: but we might be increasing its access, in which case we 7202 // should redeclare it. 7203 NamedDecl *NonTag = 0, *Tag = 0; 7204 bool FoundEquivalentDecl = false; 7205 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7206 I != E; ++I) { 7207 NamedDecl *D = (*I)->getUnderlyingDecl(); 7208 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7209 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7210 PrevShadow = Shadow; 7211 FoundEquivalentDecl = true; 7212 } 7213 7214 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7215 } 7216 7217 if (FoundEquivalentDecl) 7218 return false; 7219 7220 if (FunctionDecl *FD = Target->getAsFunction()) { 7221 NamedDecl *OldDecl = 0; 7222 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7223 case Ovl_Overload: 7224 return false; 7225 7226 case Ovl_NonFunction: 7227 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7228 break; 7229 7230 // We found a decl with the exact signature. 7231 case Ovl_Match: 7232 // If we're in a record, we want to hide the target, so we 7233 // return true (without a diagnostic) to tell the caller not to 7234 // build a shadow decl. 7235 if (CurContext->isRecord()) 7236 return true; 7237 7238 // If we're not in a record, this is an error. 7239 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7240 break; 7241 } 7242 7243 Diag(Target->getLocation(), diag::note_using_decl_target); 7244 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7245 return true; 7246 } 7247 7248 // Target is not a function. 7249 7250 if (isa<TagDecl>(Target)) { 7251 // No conflict between a tag and a non-tag. 7252 if (!Tag) return false; 7253 7254 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7255 Diag(Target->getLocation(), diag::note_using_decl_target); 7256 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7257 return true; 7258 } 7259 7260 // No conflict between a tag and a non-tag. 7261 if (!NonTag) return false; 7262 7263 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7264 Diag(Target->getLocation(), diag::note_using_decl_target); 7265 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7266 return true; 7267 } 7268 7269 /// Builds a shadow declaration corresponding to a 'using' declaration. 7270 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7271 UsingDecl *UD, 7272 NamedDecl *Orig, 7273 UsingShadowDecl *PrevDecl) { 7274 7275 // If we resolved to another shadow declaration, just coalesce them. 7276 NamedDecl *Target = Orig; 7277 if (isa<UsingShadowDecl>(Target)) { 7278 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7279 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7280 } 7281 7282 UsingShadowDecl *Shadow 7283 = UsingShadowDecl::Create(Context, CurContext, 7284 UD->getLocation(), UD, Target); 7285 UD->addShadowDecl(Shadow); 7286 7287 Shadow->setAccess(UD->getAccess()); 7288 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7289 Shadow->setInvalidDecl(); 7290 7291 Shadow->setPreviousDecl(PrevDecl); 7292 7293 if (S) 7294 PushOnScopeChains(Shadow, S); 7295 else 7296 CurContext->addDecl(Shadow); 7297 7298 7299 return Shadow; 7300 } 7301 7302 /// Hides a using shadow declaration. This is required by the current 7303 /// using-decl implementation when a resolvable using declaration in a 7304 /// class is followed by a declaration which would hide or override 7305 /// one or more of the using decl's targets; for example: 7306 /// 7307 /// struct Base { void foo(int); }; 7308 /// struct Derived : Base { 7309 /// using Base::foo; 7310 /// void foo(int); 7311 /// }; 7312 /// 7313 /// The governing language is C++03 [namespace.udecl]p12: 7314 /// 7315 /// When a using-declaration brings names from a base class into a 7316 /// derived class scope, member functions in the derived class 7317 /// override and/or hide member functions with the same name and 7318 /// parameter types in a base class (rather than conflicting). 7319 /// 7320 /// There are two ways to implement this: 7321 /// (1) optimistically create shadow decls when they're not hidden 7322 /// by existing declarations, or 7323 /// (2) don't create any shadow decls (or at least don't make them 7324 /// visible) until we've fully parsed/instantiated the class. 7325 /// The problem with (1) is that we might have to retroactively remove 7326 /// a shadow decl, which requires several O(n) operations because the 7327 /// decl structures are (very reasonably) not designed for removal. 7328 /// (2) avoids this but is very fiddly and phase-dependent. 7329 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7330 if (Shadow->getDeclName().getNameKind() == 7331 DeclarationName::CXXConversionFunctionName) 7332 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7333 7334 // Remove it from the DeclContext... 7335 Shadow->getDeclContext()->removeDecl(Shadow); 7336 7337 // ...and the scope, if applicable... 7338 if (S) { 7339 S->RemoveDecl(Shadow); 7340 IdResolver.RemoveDecl(Shadow); 7341 } 7342 7343 // ...and the using decl. 7344 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7345 7346 // TODO: complain somehow if Shadow was used. It shouldn't 7347 // be possible for this to happen, because...? 7348 } 7349 7350 namespace { 7351 class UsingValidatorCCC : public CorrectionCandidateCallback { 7352 public: 7353 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7354 bool RequireMember) 7355 : HasTypenameKeyword(HasTypenameKeyword), 7356 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {} 7357 7358 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7359 NamedDecl *ND = Candidate.getCorrectionDecl(); 7360 7361 // Keywords are not valid here. 7362 if (!ND || isa<NamespaceDecl>(ND)) 7363 return false; 7364 7365 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) && 7366 !isa<TypeDecl>(ND)) 7367 return false; 7368 7369 // Completely unqualified names are invalid for a 'using' declaration. 7370 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7371 return false; 7372 7373 if (isa<TypeDecl>(ND)) 7374 return HasTypenameKeyword || !IsInstantiation; 7375 7376 return !HasTypenameKeyword; 7377 } 7378 7379 private: 7380 bool HasTypenameKeyword; 7381 bool IsInstantiation; 7382 bool RequireMember; 7383 }; 7384 } // end anonymous namespace 7385 7386 /// Builds a using declaration. 7387 /// 7388 /// \param IsInstantiation - Whether this call arises from an 7389 /// instantiation of an unresolved using declaration. We treat 7390 /// the lookup differently for these declarations. 7391 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7392 SourceLocation UsingLoc, 7393 CXXScopeSpec &SS, 7394 const DeclarationNameInfo &NameInfo, 7395 AttributeList *AttrList, 7396 bool IsInstantiation, 7397 bool HasTypenameKeyword, 7398 SourceLocation TypenameLoc) { 7399 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7400 SourceLocation IdentLoc = NameInfo.getLoc(); 7401 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7402 7403 // FIXME: We ignore attributes for now. 7404 7405 if (SS.isEmpty()) { 7406 Diag(IdentLoc, diag::err_using_requires_qualname); 7407 return 0; 7408 } 7409 7410 // Do the redeclaration lookup in the current scope. 7411 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7412 ForRedeclaration); 7413 Previous.setHideTags(false); 7414 if (S) { 7415 LookupName(Previous, S); 7416 7417 // It is really dumb that we have to do this. 7418 LookupResult::Filter F = Previous.makeFilter(); 7419 while (F.hasNext()) { 7420 NamedDecl *D = F.next(); 7421 if (!isDeclInScope(D, CurContext, S)) 7422 F.erase(); 7423 } 7424 F.done(); 7425 } else { 7426 assert(IsInstantiation && "no scope in non-instantiation"); 7427 assert(CurContext->isRecord() && "scope not record in instantiation"); 7428 LookupQualifiedName(Previous, CurContext); 7429 } 7430 7431 // Check for invalid redeclarations. 7432 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7433 SS, IdentLoc, Previous)) 7434 return 0; 7435 7436 // Check for bad qualifiers. 7437 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7438 return 0; 7439 7440 DeclContext *LookupContext = computeDeclContext(SS); 7441 NamedDecl *D; 7442 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7443 if (!LookupContext) { 7444 if (HasTypenameKeyword) { 7445 // FIXME: not all declaration name kinds are legal here 7446 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7447 UsingLoc, TypenameLoc, 7448 QualifierLoc, 7449 IdentLoc, NameInfo.getName()); 7450 } else { 7451 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7452 QualifierLoc, NameInfo); 7453 } 7454 } else { 7455 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7456 NameInfo, HasTypenameKeyword); 7457 } 7458 D->setAccess(AS); 7459 CurContext->addDecl(D); 7460 7461 if (!LookupContext) return D; 7462 UsingDecl *UD = cast<UsingDecl>(D); 7463 7464 if (RequireCompleteDeclContext(SS, LookupContext)) { 7465 UD->setInvalidDecl(); 7466 return UD; 7467 } 7468 7469 // The normal rules do not apply to inheriting constructor declarations. 7470 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7471 if (CheckInheritingConstructorUsingDecl(UD)) 7472 UD->setInvalidDecl(); 7473 return UD; 7474 } 7475 7476 // Otherwise, look up the target name. 7477 7478 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7479 7480 // Unlike most lookups, we don't always want to hide tag 7481 // declarations: tag names are visible through the using declaration 7482 // even if hidden by ordinary names, *except* in a dependent context 7483 // where it's important for the sanity of two-phase lookup. 7484 if (!IsInstantiation) 7485 R.setHideTags(false); 7486 7487 // For the purposes of this lookup, we have a base object type 7488 // equal to that of the current context. 7489 if (CurContext->isRecord()) { 7490 R.setBaseObjectType( 7491 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7492 } 7493 7494 LookupQualifiedName(R, LookupContext); 7495 7496 // Try to correct typos if possible. 7497 if (R.empty()) { 7498 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, 7499 CurContext->isRecord()); 7500 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7501 R.getLookupKind(), S, &SS, CCC)){ 7502 // We reject any correction for which ND would be NULL. 7503 NamedDecl *ND = Corrected.getCorrectionDecl(); 7504 R.setLookupName(Corrected.getCorrection()); 7505 R.addDecl(ND); 7506 // We reject candidates where DroppedSpecifier == true, hence the 7507 // literal '0' below. 7508 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7509 << NameInfo.getName() << LookupContext << 0 7510 << SS.getRange()); 7511 } else { 7512 Diag(IdentLoc, diag::err_no_member) 7513 << NameInfo.getName() << LookupContext << SS.getRange(); 7514 UD->setInvalidDecl(); 7515 return UD; 7516 } 7517 } 7518 7519 if (R.isAmbiguous()) { 7520 UD->setInvalidDecl(); 7521 return UD; 7522 } 7523 7524 if (HasTypenameKeyword) { 7525 // If we asked for a typename and got a non-type decl, error out. 7526 if (!R.getAsSingle<TypeDecl>()) { 7527 Diag(IdentLoc, diag::err_using_typename_non_type); 7528 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7529 Diag((*I)->getUnderlyingDecl()->getLocation(), 7530 diag::note_using_decl_target); 7531 UD->setInvalidDecl(); 7532 return UD; 7533 } 7534 } else { 7535 // If we asked for a non-typename and we got a type, error out, 7536 // but only if this is an instantiation of an unresolved using 7537 // decl. Otherwise just silently find the type name. 7538 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7539 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7540 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7541 UD->setInvalidDecl(); 7542 return UD; 7543 } 7544 } 7545 7546 // C++0x N2914 [namespace.udecl]p6: 7547 // A using-declaration shall not name a namespace. 7548 if (R.getAsSingle<NamespaceDecl>()) { 7549 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7550 << SS.getRange(); 7551 UD->setInvalidDecl(); 7552 return UD; 7553 } 7554 7555 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7556 UsingShadowDecl *PrevDecl = 0; 7557 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7558 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7559 } 7560 7561 return UD; 7562 } 7563 7564 /// Additional checks for a using declaration referring to a constructor name. 7565 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7566 assert(!UD->hasTypename() && "expecting a constructor name"); 7567 7568 const Type *SourceType = UD->getQualifier()->getAsType(); 7569 assert(SourceType && 7570 "Using decl naming constructor doesn't have type in scope spec."); 7571 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7572 7573 // Check whether the named type is a direct base class. 7574 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7575 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7576 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7577 BaseIt != BaseE; ++BaseIt) { 7578 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7579 if (CanonicalSourceType == BaseType) 7580 break; 7581 if (BaseIt->getType()->isDependentType()) 7582 break; 7583 } 7584 7585 if (BaseIt == BaseE) { 7586 // Did not find SourceType in the bases. 7587 Diag(UD->getUsingLoc(), 7588 diag::err_using_decl_constructor_not_in_direct_base) 7589 << UD->getNameInfo().getSourceRange() 7590 << QualType(SourceType, 0) << TargetClass; 7591 return true; 7592 } 7593 7594 if (!CurContext->isDependentContext()) 7595 BaseIt->setInheritConstructors(); 7596 7597 return false; 7598 } 7599 7600 /// Checks that the given using declaration is not an invalid 7601 /// redeclaration. Note that this is checking only for the using decl 7602 /// itself, not for any ill-formedness among the UsingShadowDecls. 7603 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7604 bool HasTypenameKeyword, 7605 const CXXScopeSpec &SS, 7606 SourceLocation NameLoc, 7607 const LookupResult &Prev) { 7608 // C++03 [namespace.udecl]p8: 7609 // C++0x [namespace.udecl]p10: 7610 // A using-declaration is a declaration and can therefore be used 7611 // repeatedly where (and only where) multiple declarations are 7612 // allowed. 7613 // 7614 // That's in non-member contexts. 7615 if (!CurContext->getRedeclContext()->isRecord()) 7616 return false; 7617 7618 NestedNameSpecifier *Qual = SS.getScopeRep(); 7619 7620 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7621 NamedDecl *D = *I; 7622 7623 bool DTypename; 7624 NestedNameSpecifier *DQual; 7625 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7626 DTypename = UD->hasTypename(); 7627 DQual = UD->getQualifier(); 7628 } else if (UnresolvedUsingValueDecl *UD 7629 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7630 DTypename = false; 7631 DQual = UD->getQualifier(); 7632 } else if (UnresolvedUsingTypenameDecl *UD 7633 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7634 DTypename = true; 7635 DQual = UD->getQualifier(); 7636 } else continue; 7637 7638 // using decls differ if one says 'typename' and the other doesn't. 7639 // FIXME: non-dependent using decls? 7640 if (HasTypenameKeyword != DTypename) continue; 7641 7642 // using decls differ if they name different scopes (but note that 7643 // template instantiation can cause this check to trigger when it 7644 // didn't before instantiation). 7645 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7646 Context.getCanonicalNestedNameSpecifier(DQual)) 7647 continue; 7648 7649 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7650 Diag(D->getLocation(), diag::note_using_decl) << 1; 7651 return true; 7652 } 7653 7654 return false; 7655 } 7656 7657 7658 /// Checks that the given nested-name qualifier used in a using decl 7659 /// in the current context is appropriately related to the current 7660 /// scope. If an error is found, diagnoses it and returns true. 7661 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7662 const CXXScopeSpec &SS, 7663 SourceLocation NameLoc) { 7664 DeclContext *NamedContext = computeDeclContext(SS); 7665 7666 if (!CurContext->isRecord()) { 7667 // C++03 [namespace.udecl]p3: 7668 // C++0x [namespace.udecl]p8: 7669 // A using-declaration for a class member shall be a member-declaration. 7670 7671 // If we weren't able to compute a valid scope, it must be a 7672 // dependent class scope. 7673 if (!NamedContext || NamedContext->isRecord()) { 7674 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7675 << SS.getRange(); 7676 return true; 7677 } 7678 7679 // Otherwise, everything is known to be fine. 7680 return false; 7681 } 7682 7683 // The current scope is a record. 7684 7685 // If the named context is dependent, we can't decide much. 7686 if (!NamedContext) { 7687 // FIXME: in C++0x, we can diagnose if we can prove that the 7688 // nested-name-specifier does not refer to a base class, which is 7689 // still possible in some cases. 7690 7691 // Otherwise we have to conservatively report that things might be 7692 // okay. 7693 return false; 7694 } 7695 7696 if (!NamedContext->isRecord()) { 7697 // Ideally this would point at the last name in the specifier, 7698 // but we don't have that level of source info. 7699 Diag(SS.getRange().getBegin(), 7700 diag::err_using_decl_nested_name_specifier_is_not_class) 7701 << SS.getScopeRep() << SS.getRange(); 7702 return true; 7703 } 7704 7705 if (!NamedContext->isDependentContext() && 7706 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7707 return true; 7708 7709 if (getLangOpts().CPlusPlus11) { 7710 // C++0x [namespace.udecl]p3: 7711 // In a using-declaration used as a member-declaration, the 7712 // nested-name-specifier shall name a base class of the class 7713 // being defined. 7714 7715 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7716 cast<CXXRecordDecl>(NamedContext))) { 7717 if (CurContext == NamedContext) { 7718 Diag(NameLoc, 7719 diag::err_using_decl_nested_name_specifier_is_current_class) 7720 << SS.getRange(); 7721 return true; 7722 } 7723 7724 Diag(SS.getRange().getBegin(), 7725 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7726 << SS.getScopeRep() 7727 << cast<CXXRecordDecl>(CurContext) 7728 << SS.getRange(); 7729 return true; 7730 } 7731 7732 return false; 7733 } 7734 7735 // C++03 [namespace.udecl]p4: 7736 // A using-declaration used as a member-declaration shall refer 7737 // to a member of a base class of the class being defined [etc.]. 7738 7739 // Salient point: SS doesn't have to name a base class as long as 7740 // lookup only finds members from base classes. Therefore we can 7741 // diagnose here only if we can prove that that can't happen, 7742 // i.e. if the class hierarchies provably don't intersect. 7743 7744 // TODO: it would be nice if "definitely valid" results were cached 7745 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7746 // need to be repeated. 7747 7748 struct UserData { 7749 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7750 7751 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7752 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7753 Data->Bases.insert(Base); 7754 return true; 7755 } 7756 7757 bool hasDependentBases(const CXXRecordDecl *Class) { 7758 return !Class->forallBases(collect, this); 7759 } 7760 7761 /// Returns true if the base is dependent or is one of the 7762 /// accumulated base classes. 7763 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7764 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7765 return !Data->Bases.count(Base); 7766 } 7767 7768 bool mightShareBases(const CXXRecordDecl *Class) { 7769 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7770 } 7771 }; 7772 7773 UserData Data; 7774 7775 // Returns false if we find a dependent base. 7776 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7777 return false; 7778 7779 // Returns false if the class has a dependent base or if it or one 7780 // of its bases is present in the base set of the current context. 7781 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7782 return false; 7783 7784 Diag(SS.getRange().getBegin(), 7785 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7786 << SS.getScopeRep() 7787 << cast<CXXRecordDecl>(CurContext) 7788 << SS.getRange(); 7789 7790 return true; 7791 } 7792 7793 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7794 AccessSpecifier AS, 7795 MultiTemplateParamsArg TemplateParamLists, 7796 SourceLocation UsingLoc, 7797 UnqualifiedId &Name, 7798 AttributeList *AttrList, 7799 TypeResult Type) { 7800 // Skip up to the relevant declaration scope. 7801 while (S->getFlags() & Scope::TemplateParamScope) 7802 S = S->getParent(); 7803 assert((S->getFlags() & Scope::DeclScope) && 7804 "got alias-declaration outside of declaration scope"); 7805 7806 if (Type.isInvalid()) 7807 return 0; 7808 7809 bool Invalid = false; 7810 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7811 TypeSourceInfo *TInfo = 0; 7812 GetTypeFromParser(Type.get(), &TInfo); 7813 7814 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7815 return 0; 7816 7817 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7818 UPPC_DeclarationType)) { 7819 Invalid = true; 7820 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7821 TInfo->getTypeLoc().getBeginLoc()); 7822 } 7823 7824 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7825 LookupName(Previous, S); 7826 7827 // Warn about shadowing the name of a template parameter. 7828 if (Previous.isSingleResult() && 7829 Previous.getFoundDecl()->isTemplateParameter()) { 7830 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7831 Previous.clear(); 7832 } 7833 7834 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7835 "name in alias declaration must be an identifier"); 7836 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7837 Name.StartLocation, 7838 Name.Identifier, TInfo); 7839 7840 NewTD->setAccess(AS); 7841 7842 if (Invalid) 7843 NewTD->setInvalidDecl(); 7844 7845 ProcessDeclAttributeList(S, NewTD, AttrList); 7846 7847 CheckTypedefForVariablyModifiedType(S, NewTD); 7848 Invalid |= NewTD->isInvalidDecl(); 7849 7850 bool Redeclaration = false; 7851 7852 NamedDecl *NewND; 7853 if (TemplateParamLists.size()) { 7854 TypeAliasTemplateDecl *OldDecl = 0; 7855 TemplateParameterList *OldTemplateParams = 0; 7856 7857 if (TemplateParamLists.size() != 1) { 7858 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7859 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7860 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7861 } 7862 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7863 7864 // Only consider previous declarations in the same scope. 7865 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7866 /*ExplicitInstantiationOrSpecialization*/false); 7867 if (!Previous.empty()) { 7868 Redeclaration = true; 7869 7870 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7871 if (!OldDecl && !Invalid) { 7872 Diag(UsingLoc, diag::err_redefinition_different_kind) 7873 << Name.Identifier; 7874 7875 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7876 if (OldD->getLocation().isValid()) 7877 Diag(OldD->getLocation(), diag::note_previous_definition); 7878 7879 Invalid = true; 7880 } 7881 7882 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7883 if (TemplateParameterListsAreEqual(TemplateParams, 7884 OldDecl->getTemplateParameters(), 7885 /*Complain=*/true, 7886 TPL_TemplateMatch)) 7887 OldTemplateParams = OldDecl->getTemplateParameters(); 7888 else 7889 Invalid = true; 7890 7891 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7892 if (!Invalid && 7893 !Context.hasSameType(OldTD->getUnderlyingType(), 7894 NewTD->getUnderlyingType())) { 7895 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7896 // but we can't reasonably accept it. 7897 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7898 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7899 if (OldTD->getLocation().isValid()) 7900 Diag(OldTD->getLocation(), diag::note_previous_definition); 7901 Invalid = true; 7902 } 7903 } 7904 } 7905 7906 // Merge any previous default template arguments into our parameters, 7907 // and check the parameter list. 7908 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7909 TPC_TypeAliasTemplate)) 7910 return 0; 7911 7912 TypeAliasTemplateDecl *NewDecl = 7913 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7914 Name.Identifier, TemplateParams, 7915 NewTD); 7916 7917 NewDecl->setAccess(AS); 7918 7919 if (Invalid) 7920 NewDecl->setInvalidDecl(); 7921 else if (OldDecl) 7922 NewDecl->setPreviousDecl(OldDecl); 7923 7924 NewND = NewDecl; 7925 } else { 7926 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7927 NewND = NewTD; 7928 } 7929 7930 if (!Redeclaration) 7931 PushOnScopeChains(NewND, S); 7932 7933 ActOnDocumentableDecl(NewND); 7934 return NewND; 7935 } 7936 7937 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7938 SourceLocation NamespaceLoc, 7939 SourceLocation AliasLoc, 7940 IdentifierInfo *Alias, 7941 CXXScopeSpec &SS, 7942 SourceLocation IdentLoc, 7943 IdentifierInfo *Ident) { 7944 7945 // Lookup the namespace name. 7946 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7947 LookupParsedName(R, S, &SS); 7948 7949 // Check if we have a previous declaration with the same name. 7950 NamedDecl *PrevDecl 7951 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7952 ForRedeclaration); 7953 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7954 PrevDecl = 0; 7955 7956 if (PrevDecl) { 7957 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7958 // We already have an alias with the same name that points to the same 7959 // namespace, so don't create a new one. 7960 // FIXME: At some point, we'll want to create the (redundant) 7961 // declaration to maintain better source information. 7962 if (!R.isAmbiguous() && !R.empty() && 7963 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7964 return 0; 7965 } 7966 7967 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7968 diag::err_redefinition_different_kind; 7969 Diag(AliasLoc, DiagID) << Alias; 7970 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7971 return 0; 7972 } 7973 7974 if (R.isAmbiguous()) 7975 return 0; 7976 7977 if (R.empty()) { 7978 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7979 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7980 return 0; 7981 } 7982 } 7983 7984 NamespaceAliasDecl *AliasDecl = 7985 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7986 Alias, SS.getWithLocInContext(Context), 7987 IdentLoc, R.getFoundDecl()); 7988 7989 PushOnScopeChains(AliasDecl, S); 7990 return AliasDecl; 7991 } 7992 7993 Sema::ImplicitExceptionSpecification 7994 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7995 CXXMethodDecl *MD) { 7996 CXXRecordDecl *ClassDecl = MD->getParent(); 7997 7998 // C++ [except.spec]p14: 7999 // An implicitly declared special member function (Clause 12) shall have an 8000 // exception-specification. [...] 8001 ImplicitExceptionSpecification ExceptSpec(*this); 8002 if (ClassDecl->isInvalidDecl()) 8003 return ExceptSpec; 8004 8005 // Direct base-class constructors. 8006 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8007 BEnd = ClassDecl->bases_end(); 8008 B != BEnd; ++B) { 8009 if (B->isVirtual()) // Handled below. 8010 continue; 8011 8012 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8013 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8014 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8015 // If this is a deleted function, add it anyway. This might be conformant 8016 // with the standard. This might not. I'm not sure. It might not matter. 8017 if (Constructor) 8018 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8019 } 8020 } 8021 8022 // Virtual base-class constructors. 8023 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8024 BEnd = ClassDecl->vbases_end(); 8025 B != BEnd; ++B) { 8026 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8027 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8028 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8029 // If this is a deleted function, add it anyway. This might be conformant 8030 // with the standard. This might not. I'm not sure. It might not matter. 8031 if (Constructor) 8032 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8033 } 8034 } 8035 8036 // Field constructors. 8037 for (const auto *F : ClassDecl->fields()) { 8038 if (F->hasInClassInitializer()) { 8039 if (Expr *E = F->getInClassInitializer()) 8040 ExceptSpec.CalledExpr(E); 8041 else if (!F->isInvalidDecl()) 8042 // DR1351: 8043 // If the brace-or-equal-initializer of a non-static data member 8044 // invokes a defaulted default constructor of its class or of an 8045 // enclosing class in a potentially evaluated subexpression, the 8046 // program is ill-formed. 8047 // 8048 // This resolution is unworkable: the exception specification of the 8049 // default constructor can be needed in an unevaluated context, in 8050 // particular, in the operand of a noexcept-expression, and we can be 8051 // unable to compute an exception specification for an enclosed class. 8052 // 8053 // We do not allow an in-class initializer to require the evaluation 8054 // of the exception specification for any in-class initializer whose 8055 // definition is not lexically complete. 8056 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8057 } else if (const RecordType *RecordTy 8058 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8059 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8060 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8061 // If this is a deleted function, add it anyway. This might be conformant 8062 // with the standard. This might not. I'm not sure. It might not matter. 8063 // In particular, the problem is that this function never gets called. It 8064 // might just be ill-formed because this function attempts to refer to 8065 // a deleted function here. 8066 if (Constructor) 8067 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8068 } 8069 } 8070 8071 return ExceptSpec; 8072 } 8073 8074 Sema::ImplicitExceptionSpecification 8075 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8076 CXXRecordDecl *ClassDecl = CD->getParent(); 8077 8078 // C++ [except.spec]p14: 8079 // An inheriting constructor [...] shall have an exception-specification. [...] 8080 ImplicitExceptionSpecification ExceptSpec(*this); 8081 if (ClassDecl->isInvalidDecl()) 8082 return ExceptSpec; 8083 8084 // Inherited constructor. 8085 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8086 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8087 // FIXME: Copying or moving the parameters could add extra exceptions to the 8088 // set, as could the default arguments for the inherited constructor. This 8089 // will be addressed when we implement the resolution of core issue 1351. 8090 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8091 8092 // Direct base-class constructors. 8093 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8094 BEnd = ClassDecl->bases_end(); 8095 B != BEnd; ++B) { 8096 if (B->isVirtual()) // Handled below. 8097 continue; 8098 8099 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8100 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8101 if (BaseClassDecl == InheritedDecl) 8102 continue; 8103 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8104 if (Constructor) 8105 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8106 } 8107 } 8108 8109 // Virtual base-class constructors. 8110 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8111 BEnd = ClassDecl->vbases_end(); 8112 B != BEnd; ++B) { 8113 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8114 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8115 if (BaseClassDecl == InheritedDecl) 8116 continue; 8117 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8118 if (Constructor) 8119 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8120 } 8121 } 8122 8123 // Field constructors. 8124 for (const auto *F : ClassDecl->fields()) { 8125 if (F->hasInClassInitializer()) { 8126 if (Expr *E = F->getInClassInitializer()) 8127 ExceptSpec.CalledExpr(E); 8128 else if (!F->isInvalidDecl()) 8129 Diag(CD->getLocation(), 8130 diag::err_in_class_initializer_references_def_ctor) << CD; 8131 } else if (const RecordType *RecordTy 8132 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8133 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8134 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8135 if (Constructor) 8136 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8137 } 8138 } 8139 8140 return ExceptSpec; 8141 } 8142 8143 namespace { 8144 /// RAII object to register a special member as being currently declared. 8145 struct DeclaringSpecialMember { 8146 Sema &S; 8147 Sema::SpecialMemberDecl D; 8148 bool WasAlreadyBeingDeclared; 8149 8150 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8151 : S(S), D(RD, CSM) { 8152 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8153 if (WasAlreadyBeingDeclared) 8154 // This almost never happens, but if it does, ensure that our cache 8155 // doesn't contain a stale result. 8156 S.SpecialMemberCache.clear(); 8157 8158 // FIXME: Register a note to be produced if we encounter an error while 8159 // declaring the special member. 8160 } 8161 ~DeclaringSpecialMember() { 8162 if (!WasAlreadyBeingDeclared) 8163 S.SpecialMembersBeingDeclared.erase(D); 8164 } 8165 8166 /// \brief Are we already trying to declare this special member? 8167 bool isAlreadyBeingDeclared() const { 8168 return WasAlreadyBeingDeclared; 8169 } 8170 }; 8171 } 8172 8173 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8174 CXXRecordDecl *ClassDecl) { 8175 // C++ [class.ctor]p5: 8176 // A default constructor for a class X is a constructor of class X 8177 // that can be called without an argument. If there is no 8178 // user-declared constructor for class X, a default constructor is 8179 // implicitly declared. An implicitly-declared default constructor 8180 // is an inline public member of its class. 8181 assert(ClassDecl->needsImplicitDefaultConstructor() && 8182 "Should not build implicit default constructor!"); 8183 8184 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8185 if (DSM.isAlreadyBeingDeclared()) 8186 return 0; 8187 8188 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8189 CXXDefaultConstructor, 8190 false); 8191 8192 // Create the actual constructor declaration. 8193 CanQualType ClassType 8194 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8195 SourceLocation ClassLoc = ClassDecl->getLocation(); 8196 DeclarationName Name 8197 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8198 DeclarationNameInfo NameInfo(Name, ClassLoc); 8199 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8200 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8201 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8202 Constexpr); 8203 DefaultCon->setAccess(AS_public); 8204 DefaultCon->setDefaulted(); 8205 DefaultCon->setImplicit(); 8206 8207 // Build an exception specification pointing back at this constructor. 8208 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8209 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8210 8211 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8212 // constructors is easy to compute. 8213 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8214 8215 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8216 SetDeclDeleted(DefaultCon, ClassLoc); 8217 8218 // Note that we have declared this constructor. 8219 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8220 8221 if (Scope *S = getScopeForContext(ClassDecl)) 8222 PushOnScopeChains(DefaultCon, S, false); 8223 ClassDecl->addDecl(DefaultCon); 8224 8225 return DefaultCon; 8226 } 8227 8228 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8229 CXXConstructorDecl *Constructor) { 8230 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8231 !Constructor->doesThisDeclarationHaveABody() && 8232 !Constructor->isDeleted()) && 8233 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8234 8235 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8236 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8237 8238 SynthesizedFunctionScope Scope(*this, Constructor); 8239 DiagnosticErrorTrap Trap(Diags); 8240 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8241 Trap.hasErrorOccurred()) { 8242 Diag(CurrentLocation, diag::note_member_synthesized_at) 8243 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8244 Constructor->setInvalidDecl(); 8245 return; 8246 } 8247 8248 SourceLocation Loc = Constructor->getLocation(); 8249 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8250 8251 Constructor->markUsed(Context); 8252 MarkVTableUsed(CurrentLocation, ClassDecl); 8253 8254 if (ASTMutationListener *L = getASTMutationListener()) { 8255 L->CompletedImplicitDefinition(Constructor); 8256 } 8257 8258 DiagnoseUninitializedFields(*this, Constructor); 8259 } 8260 8261 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8262 // Perform any delayed checks on exception specifications. 8263 CheckDelayedMemberExceptionSpecs(); 8264 } 8265 8266 namespace { 8267 /// Information on inheriting constructors to declare. 8268 class InheritingConstructorInfo { 8269 public: 8270 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8271 : SemaRef(SemaRef), Derived(Derived) { 8272 // Mark the constructors that we already have in the derived class. 8273 // 8274 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8275 // unless there is a user-declared constructor with the same signature in 8276 // the class where the using-declaration appears. 8277 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8278 } 8279 8280 void inheritAll(CXXRecordDecl *RD) { 8281 visitAll(RD, &InheritingConstructorInfo::inherit); 8282 } 8283 8284 private: 8285 /// Information about an inheriting constructor. 8286 struct InheritingConstructor { 8287 InheritingConstructor() 8288 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8289 8290 /// If \c true, a constructor with this signature is already declared 8291 /// in the derived class. 8292 bool DeclaredInDerived; 8293 8294 /// The constructor which is inherited. 8295 const CXXConstructorDecl *BaseCtor; 8296 8297 /// The derived constructor we declared. 8298 CXXConstructorDecl *DerivedCtor; 8299 }; 8300 8301 /// Inheriting constructors with a given canonical type. There can be at 8302 /// most one such non-template constructor, and any number of templated 8303 /// constructors. 8304 struct InheritingConstructorsForType { 8305 InheritingConstructor NonTemplate; 8306 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8307 Templates; 8308 8309 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8310 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8311 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8312 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8313 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8314 false, S.TPL_TemplateMatch)) 8315 return Templates[I].second; 8316 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8317 return Templates.back().second; 8318 } 8319 8320 return NonTemplate; 8321 } 8322 }; 8323 8324 /// Get or create the inheriting constructor record for a constructor. 8325 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8326 QualType CtorType) { 8327 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8328 .getEntry(SemaRef, Ctor); 8329 } 8330 8331 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8332 8333 /// Process all constructors for a class. 8334 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8335 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 8336 CtorE = RD->ctor_end(); 8337 CtorIt != CtorE; ++CtorIt) 8338 (this->*Callback)(*CtorIt); 8339 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8340 I(RD->decls_begin()), E(RD->decls_end()); 8341 I != E; ++I) { 8342 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8343 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8344 (this->*Callback)(CD); 8345 } 8346 } 8347 8348 /// Note that a constructor (or constructor template) was declared in Derived. 8349 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8350 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8351 } 8352 8353 /// Inherit a single constructor. 8354 void inherit(const CXXConstructorDecl *Ctor) { 8355 const FunctionProtoType *CtorType = 8356 Ctor->getType()->castAs<FunctionProtoType>(); 8357 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8358 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8359 8360 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8361 8362 // Core issue (no number yet): the ellipsis is always discarded. 8363 if (EPI.Variadic) { 8364 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8365 SemaRef.Diag(Ctor->getLocation(), 8366 diag::note_using_decl_constructor_ellipsis); 8367 EPI.Variadic = false; 8368 } 8369 8370 // Declare a constructor for each number of parameters. 8371 // 8372 // C++11 [class.inhctor]p1: 8373 // The candidate set of inherited constructors from the class X named in 8374 // the using-declaration consists of [... modulo defects ...] for each 8375 // constructor or constructor template of X, the set of constructors or 8376 // constructor templates that results from omitting any ellipsis parameter 8377 // specification and successively omitting parameters with a default 8378 // argument from the end of the parameter-type-list 8379 unsigned MinParams = minParamsToInherit(Ctor); 8380 unsigned Params = Ctor->getNumParams(); 8381 if (Params >= MinParams) { 8382 do 8383 declareCtor(UsingLoc, Ctor, 8384 SemaRef.Context.getFunctionType( 8385 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8386 while (Params > MinParams && 8387 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8388 } 8389 } 8390 8391 /// Find the using-declaration which specified that we should inherit the 8392 /// constructors of \p Base. 8393 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8394 // No fancy lookup required; just look for the base constructor name 8395 // directly within the derived class. 8396 ASTContext &Context = SemaRef.Context; 8397 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8398 Context.getCanonicalType(Context.getRecordType(Base))); 8399 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8400 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8401 } 8402 8403 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8404 // C++11 [class.inhctor]p3: 8405 // [F]or each constructor template in the candidate set of inherited 8406 // constructors, a constructor template is implicitly declared 8407 if (Ctor->getDescribedFunctionTemplate()) 8408 return 0; 8409 8410 // For each non-template constructor in the candidate set of inherited 8411 // constructors other than a constructor having no parameters or a 8412 // copy/move constructor having a single parameter, a constructor is 8413 // implicitly declared [...] 8414 if (Ctor->getNumParams() == 0) 8415 return 1; 8416 if (Ctor->isCopyOrMoveConstructor()) 8417 return 2; 8418 8419 // Per discussion on core reflector, never inherit a constructor which 8420 // would become a default, copy, or move constructor of Derived either. 8421 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8422 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8423 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8424 } 8425 8426 /// Declare a single inheriting constructor, inheriting the specified 8427 /// constructor, with the given type. 8428 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8429 QualType DerivedType) { 8430 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8431 8432 // C++11 [class.inhctor]p3: 8433 // ... a constructor is implicitly declared with the same constructor 8434 // characteristics unless there is a user-declared constructor with 8435 // the same signature in the class where the using-declaration appears 8436 if (Entry.DeclaredInDerived) 8437 return; 8438 8439 // C++11 [class.inhctor]p7: 8440 // If two using-declarations declare inheriting constructors with the 8441 // same signature, the program is ill-formed 8442 if (Entry.DerivedCtor) { 8443 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8444 // Only diagnose this once per constructor. 8445 if (Entry.DerivedCtor->isInvalidDecl()) 8446 return; 8447 Entry.DerivedCtor->setInvalidDecl(); 8448 8449 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8450 SemaRef.Diag(BaseCtor->getLocation(), 8451 diag::note_using_decl_constructor_conflict_current_ctor); 8452 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8453 diag::note_using_decl_constructor_conflict_previous_ctor); 8454 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8455 diag::note_using_decl_constructor_conflict_previous_using); 8456 } else { 8457 // Core issue (no number): if the same inheriting constructor is 8458 // produced by multiple base class constructors from the same base 8459 // class, the inheriting constructor is defined as deleted. 8460 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8461 } 8462 8463 return; 8464 } 8465 8466 ASTContext &Context = SemaRef.Context; 8467 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8468 Context.getCanonicalType(Context.getRecordType(Derived))); 8469 DeclarationNameInfo NameInfo(Name, UsingLoc); 8470 8471 TemplateParameterList *TemplateParams = 0; 8472 if (const FunctionTemplateDecl *FTD = 8473 BaseCtor->getDescribedFunctionTemplate()) { 8474 TemplateParams = FTD->getTemplateParameters(); 8475 // We're reusing template parameters from a different DeclContext. This 8476 // is questionable at best, but works out because the template depth in 8477 // both places is guaranteed to be 0. 8478 // FIXME: Rebuild the template parameters in the new context, and 8479 // transform the function type to refer to them. 8480 } 8481 8482 // Build type source info pointing at the using-declaration. This is 8483 // required by template instantiation. 8484 TypeSourceInfo *TInfo = 8485 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8486 FunctionProtoTypeLoc ProtoLoc = 8487 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8488 8489 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8490 Context, Derived, UsingLoc, NameInfo, DerivedType, 8491 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8492 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8493 8494 // Build an unevaluated exception specification for this constructor. 8495 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8496 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8497 EPI.ExceptionSpecType = EST_Unevaluated; 8498 EPI.ExceptionSpecDecl = DerivedCtor; 8499 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8500 FPT->getParamTypes(), EPI)); 8501 8502 // Build the parameter declarations. 8503 SmallVector<ParmVarDecl *, 16> ParamDecls; 8504 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8505 TypeSourceInfo *TInfo = 8506 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8507 ParmVarDecl *PD = ParmVarDecl::Create( 8508 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8509 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0); 8510 PD->setScopeInfo(0, I); 8511 PD->setImplicit(); 8512 ParamDecls.push_back(PD); 8513 ProtoLoc.setParam(I, PD); 8514 } 8515 8516 // Set up the new constructor. 8517 DerivedCtor->setAccess(BaseCtor->getAccess()); 8518 DerivedCtor->setParams(ParamDecls); 8519 DerivedCtor->setInheritedConstructor(BaseCtor); 8520 if (BaseCtor->isDeleted()) 8521 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8522 8523 // If this is a constructor template, build the template declaration. 8524 if (TemplateParams) { 8525 FunctionTemplateDecl *DerivedTemplate = 8526 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8527 TemplateParams, DerivedCtor); 8528 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8529 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8530 Derived->addDecl(DerivedTemplate); 8531 } else { 8532 Derived->addDecl(DerivedCtor); 8533 } 8534 8535 Entry.BaseCtor = BaseCtor; 8536 Entry.DerivedCtor = DerivedCtor; 8537 } 8538 8539 Sema &SemaRef; 8540 CXXRecordDecl *Derived; 8541 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8542 MapType Map; 8543 }; 8544 } 8545 8546 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8547 // Defer declaring the inheriting constructors until the class is 8548 // instantiated. 8549 if (ClassDecl->isDependentContext()) 8550 return; 8551 8552 // Find base classes from which we might inherit constructors. 8553 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8554 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8555 BaseE = ClassDecl->bases_end(); 8556 BaseIt != BaseE; ++BaseIt) 8557 if (BaseIt->getInheritConstructors()) 8558 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8559 8560 // Go no further if we're not inheriting any constructors. 8561 if (InheritedBases.empty()) 8562 return; 8563 8564 // Declare the inherited constructors. 8565 InheritingConstructorInfo ICI(*this, ClassDecl); 8566 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8567 ICI.inheritAll(InheritedBases[I]); 8568 } 8569 8570 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8571 CXXConstructorDecl *Constructor) { 8572 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8573 assert(Constructor->getInheritedConstructor() && 8574 !Constructor->doesThisDeclarationHaveABody() && 8575 !Constructor->isDeleted()); 8576 8577 SynthesizedFunctionScope Scope(*this, Constructor); 8578 DiagnosticErrorTrap Trap(Diags); 8579 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8580 Trap.hasErrorOccurred()) { 8581 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8582 << Context.getTagDeclType(ClassDecl); 8583 Constructor->setInvalidDecl(); 8584 return; 8585 } 8586 8587 SourceLocation Loc = Constructor->getLocation(); 8588 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8589 8590 Constructor->markUsed(Context); 8591 MarkVTableUsed(CurrentLocation, ClassDecl); 8592 8593 if (ASTMutationListener *L = getASTMutationListener()) { 8594 L->CompletedImplicitDefinition(Constructor); 8595 } 8596 } 8597 8598 8599 Sema::ImplicitExceptionSpecification 8600 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8601 CXXRecordDecl *ClassDecl = MD->getParent(); 8602 8603 // C++ [except.spec]p14: 8604 // An implicitly declared special member function (Clause 12) shall have 8605 // an exception-specification. 8606 ImplicitExceptionSpecification ExceptSpec(*this); 8607 if (ClassDecl->isInvalidDecl()) 8608 return ExceptSpec; 8609 8610 // Direct base-class destructors. 8611 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8612 BEnd = ClassDecl->bases_end(); 8613 B != BEnd; ++B) { 8614 if (B->isVirtual()) // Handled below. 8615 continue; 8616 8617 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8618 ExceptSpec.CalledDecl(B->getLocStart(), 8619 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8620 } 8621 8622 // Virtual base-class destructors. 8623 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8624 BEnd = ClassDecl->vbases_end(); 8625 B != BEnd; ++B) { 8626 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8627 ExceptSpec.CalledDecl(B->getLocStart(), 8628 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8629 } 8630 8631 // Field destructors. 8632 for (const auto *F : ClassDecl->fields()) { 8633 if (const RecordType *RecordTy 8634 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8635 ExceptSpec.CalledDecl(F->getLocation(), 8636 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8637 } 8638 8639 return ExceptSpec; 8640 } 8641 8642 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8643 // C++ [class.dtor]p2: 8644 // If a class has no user-declared destructor, a destructor is 8645 // declared implicitly. An implicitly-declared destructor is an 8646 // inline public member of its class. 8647 assert(ClassDecl->needsImplicitDestructor()); 8648 8649 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8650 if (DSM.isAlreadyBeingDeclared()) 8651 return 0; 8652 8653 // Create the actual destructor declaration. 8654 CanQualType ClassType 8655 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8656 SourceLocation ClassLoc = ClassDecl->getLocation(); 8657 DeclarationName Name 8658 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8659 DeclarationNameInfo NameInfo(Name, ClassLoc); 8660 CXXDestructorDecl *Destructor 8661 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8662 QualType(), 0, /*isInline=*/true, 8663 /*isImplicitlyDeclared=*/true); 8664 Destructor->setAccess(AS_public); 8665 Destructor->setDefaulted(); 8666 Destructor->setImplicit(); 8667 8668 // Build an exception specification pointing back at this destructor. 8669 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8670 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8671 8672 AddOverriddenMethods(ClassDecl, Destructor); 8673 8674 // We don't need to use SpecialMemberIsTrivial here; triviality for 8675 // destructors is easy to compute. 8676 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8677 8678 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8679 SetDeclDeleted(Destructor, ClassLoc); 8680 8681 // Note that we have declared this destructor. 8682 ++ASTContext::NumImplicitDestructorsDeclared; 8683 8684 // Introduce this destructor into its scope. 8685 if (Scope *S = getScopeForContext(ClassDecl)) 8686 PushOnScopeChains(Destructor, S, false); 8687 ClassDecl->addDecl(Destructor); 8688 8689 return Destructor; 8690 } 8691 8692 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8693 CXXDestructorDecl *Destructor) { 8694 assert((Destructor->isDefaulted() && 8695 !Destructor->doesThisDeclarationHaveABody() && 8696 !Destructor->isDeleted()) && 8697 "DefineImplicitDestructor - call it for implicit default dtor"); 8698 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8699 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8700 8701 if (Destructor->isInvalidDecl()) 8702 return; 8703 8704 SynthesizedFunctionScope Scope(*this, Destructor); 8705 8706 DiagnosticErrorTrap Trap(Diags); 8707 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8708 Destructor->getParent()); 8709 8710 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8711 Diag(CurrentLocation, diag::note_member_synthesized_at) 8712 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8713 8714 Destructor->setInvalidDecl(); 8715 return; 8716 } 8717 8718 SourceLocation Loc = Destructor->getLocation(); 8719 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8720 Destructor->markUsed(Context); 8721 MarkVTableUsed(CurrentLocation, ClassDecl); 8722 8723 if (ASTMutationListener *L = getASTMutationListener()) { 8724 L->CompletedImplicitDefinition(Destructor); 8725 } 8726 } 8727 8728 /// \brief Perform any semantic analysis which needs to be delayed until all 8729 /// pending class member declarations have been parsed. 8730 void Sema::ActOnFinishCXXMemberDecls() { 8731 // If the context is an invalid C++ class, just suppress these checks. 8732 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8733 if (Record->isInvalidDecl()) { 8734 DelayedDefaultedMemberExceptionSpecs.clear(); 8735 DelayedDestructorExceptionSpecChecks.clear(); 8736 return; 8737 } 8738 } 8739 } 8740 8741 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8742 CXXDestructorDecl *Destructor) { 8743 assert(getLangOpts().CPlusPlus11 && 8744 "adjusting dtor exception specs was introduced in c++11"); 8745 8746 // C++11 [class.dtor]p3: 8747 // A declaration of a destructor that does not have an exception- 8748 // specification is implicitly considered to have the same exception- 8749 // specification as an implicit declaration. 8750 const FunctionProtoType *DtorType = Destructor->getType()-> 8751 getAs<FunctionProtoType>(); 8752 if (DtorType->hasExceptionSpec()) 8753 return; 8754 8755 // Replace the destructor's type, building off the existing one. Fortunately, 8756 // the only thing of interest in the destructor type is its extended info. 8757 // The return and arguments are fixed. 8758 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8759 EPI.ExceptionSpecType = EST_Unevaluated; 8760 EPI.ExceptionSpecDecl = Destructor; 8761 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8762 8763 // FIXME: If the destructor has a body that could throw, and the newly created 8764 // spec doesn't allow exceptions, we should emit a warning, because this 8765 // change in behavior can break conforming C++03 programs at runtime. 8766 // However, we don't have a body or an exception specification yet, so it 8767 // needs to be done somewhere else. 8768 } 8769 8770 namespace { 8771 /// \brief An abstract base class for all helper classes used in building the 8772 // copy/move operators. These classes serve as factory functions and help us 8773 // avoid using the same Expr* in the AST twice. 8774 class ExprBuilder { 8775 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8776 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8777 8778 protected: 8779 static Expr *assertNotNull(Expr *E) { 8780 assert(E && "Expression construction must not fail."); 8781 return E; 8782 } 8783 8784 public: 8785 ExprBuilder() {} 8786 virtual ~ExprBuilder() {} 8787 8788 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8789 }; 8790 8791 class RefBuilder: public ExprBuilder { 8792 VarDecl *Var; 8793 QualType VarType; 8794 8795 public: 8796 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8797 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8798 } 8799 8800 RefBuilder(VarDecl *Var, QualType VarType) 8801 : Var(Var), VarType(VarType) {} 8802 }; 8803 8804 class ThisBuilder: public ExprBuilder { 8805 public: 8806 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8807 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8808 } 8809 }; 8810 8811 class CastBuilder: public ExprBuilder { 8812 const ExprBuilder &Builder; 8813 QualType Type; 8814 ExprValueKind Kind; 8815 const CXXCastPath &Path; 8816 8817 public: 8818 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8819 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8820 CK_UncheckedDerivedToBase, Kind, 8821 &Path).take()); 8822 } 8823 8824 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8825 const CXXCastPath &Path) 8826 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8827 }; 8828 8829 class DerefBuilder: public ExprBuilder { 8830 const ExprBuilder &Builder; 8831 8832 public: 8833 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8834 return assertNotNull( 8835 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8836 } 8837 8838 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8839 }; 8840 8841 class MemberBuilder: public ExprBuilder { 8842 const ExprBuilder &Builder; 8843 QualType Type; 8844 CXXScopeSpec SS; 8845 bool IsArrow; 8846 LookupResult &MemberLookup; 8847 8848 public: 8849 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8850 return assertNotNull(S.BuildMemberReferenceExpr( 8851 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8852 MemberLookup, 0).take()); 8853 } 8854 8855 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8856 LookupResult &MemberLookup) 8857 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8858 MemberLookup(MemberLookup) {} 8859 }; 8860 8861 class MoveCastBuilder: public ExprBuilder { 8862 const ExprBuilder &Builder; 8863 8864 public: 8865 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8866 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8867 } 8868 8869 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8870 }; 8871 8872 class LvalueConvBuilder: public ExprBuilder { 8873 const ExprBuilder &Builder; 8874 8875 public: 8876 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8877 return assertNotNull( 8878 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8879 } 8880 8881 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8882 }; 8883 8884 class SubscriptBuilder: public ExprBuilder { 8885 const ExprBuilder &Base; 8886 const ExprBuilder &Index; 8887 8888 public: 8889 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8890 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8891 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8892 } 8893 8894 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8895 : Base(Base), Index(Index) {} 8896 }; 8897 8898 } // end anonymous namespace 8899 8900 /// When generating a defaulted copy or move assignment operator, if a field 8901 /// should be copied with __builtin_memcpy rather than via explicit assignments, 8902 /// do so. This optimization only applies for arrays of scalars, and for arrays 8903 /// of class type where the selected copy/move-assignment operator is trivial. 8904 static StmtResult 8905 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8906 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8907 // Compute the size of the memory buffer to be copied. 8908 QualType SizeType = S.Context.getSizeType(); 8909 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8910 S.Context.getTypeSizeInChars(T).getQuantity()); 8911 8912 // Take the address of the field references for "from" and "to". We 8913 // directly construct UnaryOperators here because semantic analysis 8914 // does not permit us to take the address of an xvalue. 8915 Expr *From = FromB.build(S, Loc); 8916 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8917 S.Context.getPointerType(From->getType()), 8918 VK_RValue, OK_Ordinary, Loc); 8919 Expr *To = ToB.build(S, Loc); 8920 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8921 S.Context.getPointerType(To->getType()), 8922 VK_RValue, OK_Ordinary, Loc); 8923 8924 const Type *E = T->getBaseElementTypeUnsafe(); 8925 bool NeedsCollectableMemCpy = 8926 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8927 8928 // Create a reference to the __builtin_objc_memmove_collectable function 8929 StringRef MemCpyName = NeedsCollectableMemCpy ? 8930 "__builtin_objc_memmove_collectable" : 8931 "__builtin_memcpy"; 8932 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8933 Sema::LookupOrdinaryName); 8934 S.LookupName(R, S.TUScope, true); 8935 8936 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8937 if (!MemCpy) 8938 // Something went horribly wrong earlier, and we will have complained 8939 // about it. 8940 return StmtError(); 8941 8942 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8943 VK_RValue, Loc, 0); 8944 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8945 8946 Expr *CallArgs[] = { 8947 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8948 }; 8949 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8950 Loc, CallArgs, Loc); 8951 8952 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8953 return S.Owned(Call.takeAs<Stmt>()); 8954 } 8955 8956 /// \brief Builds a statement that copies/moves the given entity from \p From to 8957 /// \c To. 8958 /// 8959 /// This routine is used to copy/move the members of a class with an 8960 /// implicitly-declared copy/move assignment operator. When the entities being 8961 /// copied are arrays, this routine builds for loops to copy them. 8962 /// 8963 /// \param S The Sema object used for type-checking. 8964 /// 8965 /// \param Loc The location where the implicit copy/move is being generated. 8966 /// 8967 /// \param T The type of the expressions being copied/moved. Both expressions 8968 /// must have this type. 8969 /// 8970 /// \param To The expression we are copying/moving to. 8971 /// 8972 /// \param From The expression we are copying/moving from. 8973 /// 8974 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8975 /// Otherwise, it's a non-static member subobject. 8976 /// 8977 /// \param Copying Whether we're copying or moving. 8978 /// 8979 /// \param Depth Internal parameter recording the depth of the recursion. 8980 /// 8981 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8982 /// if a memcpy should be used instead. 8983 static StmtResult 8984 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8985 const ExprBuilder &To, const ExprBuilder &From, 8986 bool CopyingBaseSubobject, bool Copying, 8987 unsigned Depth = 0) { 8988 // C++11 [class.copy]p28: 8989 // Each subobject is assigned in the manner appropriate to its type: 8990 // 8991 // - if the subobject is of class type, as if by a call to operator= with 8992 // the subobject as the object expression and the corresponding 8993 // subobject of x as a single function argument (as if by explicit 8994 // qualification; that is, ignoring any possible virtual overriding 8995 // functions in more derived classes); 8996 // 8997 // C++03 [class.copy]p13: 8998 // - if the subobject is of class type, the copy assignment operator for 8999 // the class is used (as if by explicit qualification; that is, 9000 // ignoring any possible virtual overriding functions in more derived 9001 // classes); 9002 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9003 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9004 9005 // Look for operator=. 9006 DeclarationName Name 9007 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9008 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9009 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9010 9011 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9012 // operator. 9013 if (!S.getLangOpts().CPlusPlus11) { 9014 LookupResult::Filter F = OpLookup.makeFilter(); 9015 while (F.hasNext()) { 9016 NamedDecl *D = F.next(); 9017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9018 if (Method->isCopyAssignmentOperator() || 9019 (!Copying && Method->isMoveAssignmentOperator())) 9020 continue; 9021 9022 F.erase(); 9023 } 9024 F.done(); 9025 } 9026 9027 // Suppress the protected check (C++ [class.protected]) for each of the 9028 // assignment operators we found. This strange dance is required when 9029 // we're assigning via a base classes's copy-assignment operator. To 9030 // ensure that we're getting the right base class subobject (without 9031 // ambiguities), we need to cast "this" to that subobject type; to 9032 // ensure that we don't go through the virtual call mechanism, we need 9033 // to qualify the operator= name with the base class (see below). However, 9034 // this means that if the base class has a protected copy assignment 9035 // operator, the protected member access check will fail. So, we 9036 // rewrite "protected" access to "public" access in this case, since we 9037 // know by construction that we're calling from a derived class. 9038 if (CopyingBaseSubobject) { 9039 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9040 L != LEnd; ++L) { 9041 if (L.getAccess() == AS_protected) 9042 L.setAccess(AS_public); 9043 } 9044 } 9045 9046 // Create the nested-name-specifier that will be used to qualify the 9047 // reference to operator=; this is required to suppress the virtual 9048 // call mechanism. 9049 CXXScopeSpec SS; 9050 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9051 SS.MakeTrivial(S.Context, 9052 NestedNameSpecifier::Create(S.Context, 0, false, 9053 CanonicalT), 9054 Loc); 9055 9056 // Create the reference to operator=. 9057 ExprResult OpEqualRef 9058 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9059 SS, /*TemplateKWLoc=*/SourceLocation(), 9060 /*FirstQualifierInScope=*/0, 9061 OpLookup, 9062 /*TemplateArgs=*/0, 9063 /*SuppressQualifierCheck=*/true); 9064 if (OpEqualRef.isInvalid()) 9065 return StmtError(); 9066 9067 // Build the call to the assignment operator. 9068 9069 Expr *FromInst = From.build(S, Loc); 9070 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9071 OpEqualRef.takeAs<Expr>(), 9072 Loc, FromInst, Loc); 9073 if (Call.isInvalid()) 9074 return StmtError(); 9075 9076 // If we built a call to a trivial 'operator=' while copying an array, 9077 // bail out. We'll replace the whole shebang with a memcpy. 9078 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9079 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9080 return StmtResult((Stmt*)0); 9081 9082 // Convert to an expression-statement, and clean up any produced 9083 // temporaries. 9084 return S.ActOnExprStmt(Call); 9085 } 9086 9087 // - if the subobject is of scalar type, the built-in assignment 9088 // operator is used. 9089 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9090 if (!ArrayTy) { 9091 ExprResult Assignment = S.CreateBuiltinBinOp( 9092 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9093 if (Assignment.isInvalid()) 9094 return StmtError(); 9095 return S.ActOnExprStmt(Assignment); 9096 } 9097 9098 // - if the subobject is an array, each element is assigned, in the 9099 // manner appropriate to the element type; 9100 9101 // Construct a loop over the array bounds, e.g., 9102 // 9103 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9104 // 9105 // that will copy each of the array elements. 9106 QualType SizeType = S.Context.getSizeType(); 9107 9108 // Create the iteration variable. 9109 IdentifierInfo *IterationVarName = 0; 9110 { 9111 SmallString<8> Str; 9112 llvm::raw_svector_ostream OS(Str); 9113 OS << "__i" << Depth; 9114 IterationVarName = &S.Context.Idents.get(OS.str()); 9115 } 9116 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9117 IterationVarName, SizeType, 9118 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9119 SC_None); 9120 9121 // Initialize the iteration variable to zero. 9122 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9123 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9124 9125 // Creates a reference to the iteration variable. 9126 RefBuilder IterationVarRef(IterationVar, SizeType); 9127 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9128 9129 // Create the DeclStmt that holds the iteration variable. 9130 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9131 9132 // Subscript the "from" and "to" expressions with the iteration variable. 9133 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9134 MoveCastBuilder FromIndexMove(FromIndexCopy); 9135 const ExprBuilder *FromIndex; 9136 if (Copying) 9137 FromIndex = &FromIndexCopy; 9138 else 9139 FromIndex = &FromIndexMove; 9140 9141 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9142 9143 // Build the copy/move for an individual element of the array. 9144 StmtResult Copy = 9145 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9146 ToIndex, *FromIndex, CopyingBaseSubobject, 9147 Copying, Depth + 1); 9148 // Bail out if copying fails or if we determined that we should use memcpy. 9149 if (Copy.isInvalid() || !Copy.get()) 9150 return Copy; 9151 9152 // Create the comparison against the array bound. 9153 llvm::APInt Upper 9154 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9155 Expr *Comparison 9156 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9157 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9158 BO_NE, S.Context.BoolTy, 9159 VK_RValue, OK_Ordinary, Loc, false); 9160 9161 // Create the pre-increment of the iteration variable. 9162 Expr *Increment 9163 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9164 SizeType, VK_LValue, OK_Ordinary, Loc); 9165 9166 // Construct the loop that copies all elements of this array. 9167 return S.ActOnForStmt(Loc, Loc, InitStmt, 9168 S.MakeFullExpr(Comparison), 9169 0, S.MakeFullDiscardedValueExpr(Increment), 9170 Loc, Copy.take()); 9171 } 9172 9173 static StmtResult 9174 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9175 const ExprBuilder &To, const ExprBuilder &From, 9176 bool CopyingBaseSubobject, bool Copying) { 9177 // Maybe we should use a memcpy? 9178 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9179 T.isTriviallyCopyableType(S.Context)) 9180 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9181 9182 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9183 CopyingBaseSubobject, 9184 Copying, 0)); 9185 9186 // If we ended up picking a trivial assignment operator for an array of a 9187 // non-trivially-copyable class type, just emit a memcpy. 9188 if (!Result.isInvalid() && !Result.get()) 9189 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9190 9191 return Result; 9192 } 9193 9194 Sema::ImplicitExceptionSpecification 9195 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9196 CXXRecordDecl *ClassDecl = MD->getParent(); 9197 9198 ImplicitExceptionSpecification ExceptSpec(*this); 9199 if (ClassDecl->isInvalidDecl()) 9200 return ExceptSpec; 9201 9202 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9203 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9204 unsigned ArgQuals = 9205 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9206 9207 // C++ [except.spec]p14: 9208 // An implicitly declared special member function (Clause 12) shall have an 9209 // exception-specification. [...] 9210 9211 // It is unspecified whether or not an implicit copy assignment operator 9212 // attempts to deduplicate calls to assignment operators of virtual bases are 9213 // made. As such, this exception specification is effectively unspecified. 9214 // Based on a similar decision made for constness in C++0x, we're erring on 9215 // the side of assuming such calls to be made regardless of whether they 9216 // actually happen. 9217 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9218 BaseEnd = ClassDecl->bases_end(); 9219 Base != BaseEnd; ++Base) { 9220 if (Base->isVirtual()) 9221 continue; 9222 9223 CXXRecordDecl *BaseClassDecl 9224 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9225 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9226 ArgQuals, false, 0)) 9227 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9228 } 9229 9230 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9231 BaseEnd = ClassDecl->vbases_end(); 9232 Base != BaseEnd; ++Base) { 9233 CXXRecordDecl *BaseClassDecl 9234 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9235 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9236 ArgQuals, false, 0)) 9237 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9238 } 9239 9240 for (const auto *Field : ClassDecl->fields()) { 9241 QualType FieldType = Context.getBaseElementType(Field->getType()); 9242 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9243 if (CXXMethodDecl *CopyAssign = 9244 LookupCopyingAssignment(FieldClassDecl, 9245 ArgQuals | FieldType.getCVRQualifiers(), 9246 false, 0)) 9247 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9248 } 9249 } 9250 9251 return ExceptSpec; 9252 } 9253 9254 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9255 // Note: The following rules are largely analoguous to the copy 9256 // constructor rules. Note that virtual bases are not taken into account 9257 // for determining the argument type of the operator. Note also that 9258 // operators taking an object instead of a reference are allowed. 9259 assert(ClassDecl->needsImplicitCopyAssignment()); 9260 9261 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9262 if (DSM.isAlreadyBeingDeclared()) 9263 return 0; 9264 9265 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9266 QualType RetType = Context.getLValueReferenceType(ArgType); 9267 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9268 if (Const) 9269 ArgType = ArgType.withConst(); 9270 ArgType = Context.getLValueReferenceType(ArgType); 9271 9272 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9273 CXXCopyAssignment, 9274 Const); 9275 9276 // An implicitly-declared copy assignment operator is an inline public 9277 // member of its class. 9278 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9279 SourceLocation ClassLoc = ClassDecl->getLocation(); 9280 DeclarationNameInfo NameInfo(Name, ClassLoc); 9281 CXXMethodDecl *CopyAssignment = 9282 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9283 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9284 /*isInline=*/ true, Constexpr, SourceLocation()); 9285 CopyAssignment->setAccess(AS_public); 9286 CopyAssignment->setDefaulted(); 9287 CopyAssignment->setImplicit(); 9288 9289 // Build an exception specification pointing back at this member. 9290 FunctionProtoType::ExtProtoInfo EPI = 9291 getImplicitMethodEPI(*this, CopyAssignment); 9292 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9293 9294 // Add the parameter to the operator. 9295 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9296 ClassLoc, ClassLoc, /*Id=*/0, 9297 ArgType, /*TInfo=*/0, 9298 SC_None, 0); 9299 CopyAssignment->setParams(FromParam); 9300 9301 AddOverriddenMethods(ClassDecl, CopyAssignment); 9302 9303 CopyAssignment->setTrivial( 9304 ClassDecl->needsOverloadResolutionForCopyAssignment() 9305 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9306 : ClassDecl->hasTrivialCopyAssignment()); 9307 9308 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9309 SetDeclDeleted(CopyAssignment, ClassLoc); 9310 9311 // Note that we have added this copy-assignment operator. 9312 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9313 9314 if (Scope *S = getScopeForContext(ClassDecl)) 9315 PushOnScopeChains(CopyAssignment, S, false); 9316 ClassDecl->addDecl(CopyAssignment); 9317 9318 return CopyAssignment; 9319 } 9320 9321 /// Diagnose an implicit copy operation for a class which is odr-used, but 9322 /// which is deprecated because the class has a user-declared copy constructor, 9323 /// copy assignment operator, or destructor. 9324 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9325 SourceLocation UseLoc) { 9326 assert(CopyOp->isImplicit()); 9327 9328 CXXRecordDecl *RD = CopyOp->getParent(); 9329 CXXMethodDecl *UserDeclaredOperation = 0; 9330 9331 // In Microsoft mode, assignment operations don't affect constructors and 9332 // vice versa. 9333 if (RD->hasUserDeclaredDestructor()) { 9334 UserDeclaredOperation = RD->getDestructor(); 9335 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9336 RD->hasUserDeclaredCopyConstructor() && 9337 !S.getLangOpts().MSVCCompat) { 9338 // Find any user-declared copy constructor. 9339 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 9340 E = RD->ctor_end(); I != E; ++I) { 9341 if (I->isCopyConstructor()) { 9342 UserDeclaredOperation = *I; 9343 break; 9344 } 9345 } 9346 assert(UserDeclaredOperation); 9347 } else if (isa<CXXConstructorDecl>(CopyOp) && 9348 RD->hasUserDeclaredCopyAssignment() && 9349 !S.getLangOpts().MSVCCompat) { 9350 // Find any user-declared move assignment operator. 9351 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 9352 E = RD->method_end(); I != E; ++I) { 9353 if (I->isCopyAssignmentOperator()) { 9354 UserDeclaredOperation = *I; 9355 break; 9356 } 9357 } 9358 assert(UserDeclaredOperation); 9359 } 9360 9361 if (UserDeclaredOperation) { 9362 S.Diag(UserDeclaredOperation->getLocation(), 9363 diag::warn_deprecated_copy_operation) 9364 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9365 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9366 S.Diag(UseLoc, diag::note_member_synthesized_at) 9367 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9368 : Sema::CXXCopyAssignment) 9369 << RD; 9370 } 9371 } 9372 9373 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9374 CXXMethodDecl *CopyAssignOperator) { 9375 assert((CopyAssignOperator->isDefaulted() && 9376 CopyAssignOperator->isOverloadedOperator() && 9377 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9378 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9379 !CopyAssignOperator->isDeleted()) && 9380 "DefineImplicitCopyAssignment called for wrong function"); 9381 9382 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9383 9384 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9385 CopyAssignOperator->setInvalidDecl(); 9386 return; 9387 } 9388 9389 // C++11 [class.copy]p18: 9390 // The [definition of an implicitly declared copy assignment operator] is 9391 // deprecated if the class has a user-declared copy constructor or a 9392 // user-declared destructor. 9393 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9394 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9395 9396 CopyAssignOperator->markUsed(Context); 9397 9398 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9399 DiagnosticErrorTrap Trap(Diags); 9400 9401 // C++0x [class.copy]p30: 9402 // The implicitly-defined or explicitly-defaulted copy assignment operator 9403 // for a non-union class X performs memberwise copy assignment of its 9404 // subobjects. The direct base classes of X are assigned first, in the 9405 // order of their declaration in the base-specifier-list, and then the 9406 // immediate non-static data members of X are assigned, in the order in 9407 // which they were declared in the class definition. 9408 9409 // The statements that form the synthesized function body. 9410 SmallVector<Stmt*, 8> Statements; 9411 9412 // The parameter for the "other" object, which we are copying from. 9413 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9414 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9415 QualType OtherRefType = Other->getType(); 9416 if (const LValueReferenceType *OtherRef 9417 = OtherRefType->getAs<LValueReferenceType>()) { 9418 OtherRefType = OtherRef->getPointeeType(); 9419 OtherQuals = OtherRefType.getQualifiers(); 9420 } 9421 9422 // Our location for everything implicitly-generated. 9423 SourceLocation Loc = CopyAssignOperator->getLocation(); 9424 9425 // Builds a DeclRefExpr for the "other" object. 9426 RefBuilder OtherRef(Other, OtherRefType); 9427 9428 // Builds the "this" pointer. 9429 ThisBuilder This; 9430 9431 // Assign base classes. 9432 bool Invalid = false; 9433 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9434 E = ClassDecl->bases_end(); Base != E; ++Base) { 9435 // Form the assignment: 9436 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9437 QualType BaseType = Base->getType().getUnqualifiedType(); 9438 if (!BaseType->isRecordType()) { 9439 Invalid = true; 9440 continue; 9441 } 9442 9443 CXXCastPath BasePath; 9444 BasePath.push_back(Base); 9445 9446 // Construct the "from" expression, which is an implicit cast to the 9447 // appropriately-qualified base type. 9448 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9449 VK_LValue, BasePath); 9450 9451 // Dereference "this". 9452 DerefBuilder DerefThis(This); 9453 CastBuilder To(DerefThis, 9454 Context.getCVRQualifiedType( 9455 BaseType, CopyAssignOperator->getTypeQualifiers()), 9456 VK_LValue, BasePath); 9457 9458 // Build the copy. 9459 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9460 To, From, 9461 /*CopyingBaseSubobject=*/true, 9462 /*Copying=*/true); 9463 if (Copy.isInvalid()) { 9464 Diag(CurrentLocation, diag::note_member_synthesized_at) 9465 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9466 CopyAssignOperator->setInvalidDecl(); 9467 return; 9468 } 9469 9470 // Success! Record the copy. 9471 Statements.push_back(Copy.takeAs<Expr>()); 9472 } 9473 9474 // Assign non-static members. 9475 for (auto *Field : ClassDecl->fields()) { 9476 if (Field->isUnnamedBitfield()) 9477 continue; 9478 9479 if (Field->isInvalidDecl()) { 9480 Invalid = true; 9481 continue; 9482 } 9483 9484 // Check for members of reference type; we can't copy those. 9485 if (Field->getType()->isReferenceType()) { 9486 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9487 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9488 Diag(Field->getLocation(), diag::note_declared_at); 9489 Diag(CurrentLocation, diag::note_member_synthesized_at) 9490 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9491 Invalid = true; 9492 continue; 9493 } 9494 9495 // Check for members of const-qualified, non-class type. 9496 QualType BaseType = Context.getBaseElementType(Field->getType()); 9497 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9498 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9499 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9500 Diag(Field->getLocation(), diag::note_declared_at); 9501 Diag(CurrentLocation, diag::note_member_synthesized_at) 9502 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9503 Invalid = true; 9504 continue; 9505 } 9506 9507 // Suppress assigning zero-width bitfields. 9508 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9509 continue; 9510 9511 QualType FieldType = Field->getType().getNonReferenceType(); 9512 if (FieldType->isIncompleteArrayType()) { 9513 assert(ClassDecl->hasFlexibleArrayMember() && 9514 "Incomplete array type is not valid"); 9515 continue; 9516 } 9517 9518 // Build references to the field in the object we're copying from and to. 9519 CXXScopeSpec SS; // Intentionally empty 9520 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9521 LookupMemberName); 9522 MemberLookup.addDecl(Field); 9523 MemberLookup.resolveKind(); 9524 9525 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9526 9527 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9528 9529 // Build the copy of this field. 9530 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9531 To, From, 9532 /*CopyingBaseSubobject=*/false, 9533 /*Copying=*/true); 9534 if (Copy.isInvalid()) { 9535 Diag(CurrentLocation, diag::note_member_synthesized_at) 9536 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9537 CopyAssignOperator->setInvalidDecl(); 9538 return; 9539 } 9540 9541 // Success! Record the copy. 9542 Statements.push_back(Copy.takeAs<Stmt>()); 9543 } 9544 9545 if (!Invalid) { 9546 // Add a "return *this;" 9547 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9548 9549 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9550 if (Return.isInvalid()) 9551 Invalid = true; 9552 else { 9553 Statements.push_back(Return.takeAs<Stmt>()); 9554 9555 if (Trap.hasErrorOccurred()) { 9556 Diag(CurrentLocation, diag::note_member_synthesized_at) 9557 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9558 Invalid = true; 9559 } 9560 } 9561 } 9562 9563 if (Invalid) { 9564 CopyAssignOperator->setInvalidDecl(); 9565 return; 9566 } 9567 9568 StmtResult Body; 9569 { 9570 CompoundScopeRAII CompoundScope(*this); 9571 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9572 /*isStmtExpr=*/false); 9573 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9574 } 9575 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9576 9577 if (ASTMutationListener *L = getASTMutationListener()) { 9578 L->CompletedImplicitDefinition(CopyAssignOperator); 9579 } 9580 } 9581 9582 Sema::ImplicitExceptionSpecification 9583 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9584 CXXRecordDecl *ClassDecl = MD->getParent(); 9585 9586 ImplicitExceptionSpecification ExceptSpec(*this); 9587 if (ClassDecl->isInvalidDecl()) 9588 return ExceptSpec; 9589 9590 // C++0x [except.spec]p14: 9591 // An implicitly declared special member function (Clause 12) shall have an 9592 // exception-specification. [...] 9593 9594 // It is unspecified whether or not an implicit move assignment operator 9595 // attempts to deduplicate calls to assignment operators of virtual bases are 9596 // made. As such, this exception specification is effectively unspecified. 9597 // Based on a similar decision made for constness in C++0x, we're erring on 9598 // the side of assuming such calls to be made regardless of whether they 9599 // actually happen. 9600 // Note that a move constructor is not implicitly declared when there are 9601 // virtual bases, but it can still be user-declared and explicitly defaulted. 9602 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9603 BaseEnd = ClassDecl->bases_end(); 9604 Base != BaseEnd; ++Base) { 9605 if (Base->isVirtual()) 9606 continue; 9607 9608 CXXRecordDecl *BaseClassDecl 9609 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9610 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9611 0, false, 0)) 9612 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9613 } 9614 9615 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9616 BaseEnd = ClassDecl->vbases_end(); 9617 Base != BaseEnd; ++Base) { 9618 CXXRecordDecl *BaseClassDecl 9619 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9620 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9621 0, false, 0)) 9622 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9623 } 9624 9625 for (const auto *Field : ClassDecl->fields()) { 9626 QualType FieldType = Context.getBaseElementType(Field->getType()); 9627 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9628 if (CXXMethodDecl *MoveAssign = 9629 LookupMovingAssignment(FieldClassDecl, 9630 FieldType.getCVRQualifiers(), 9631 false, 0)) 9632 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9633 } 9634 } 9635 9636 return ExceptSpec; 9637 } 9638 9639 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9640 assert(ClassDecl->needsImplicitMoveAssignment()); 9641 9642 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9643 if (DSM.isAlreadyBeingDeclared()) 9644 return 0; 9645 9646 // Note: The following rules are largely analoguous to the move 9647 // constructor rules. 9648 9649 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9650 QualType RetType = Context.getLValueReferenceType(ArgType); 9651 ArgType = Context.getRValueReferenceType(ArgType); 9652 9653 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9654 CXXMoveAssignment, 9655 false); 9656 9657 // An implicitly-declared move assignment operator is an inline public 9658 // member of its class. 9659 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9660 SourceLocation ClassLoc = ClassDecl->getLocation(); 9661 DeclarationNameInfo NameInfo(Name, ClassLoc); 9662 CXXMethodDecl *MoveAssignment = 9663 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9664 /*TInfo=*/0, /*StorageClass=*/SC_None, 9665 /*isInline=*/true, Constexpr, SourceLocation()); 9666 MoveAssignment->setAccess(AS_public); 9667 MoveAssignment->setDefaulted(); 9668 MoveAssignment->setImplicit(); 9669 9670 // Build an exception specification pointing back at this member. 9671 FunctionProtoType::ExtProtoInfo EPI = 9672 getImplicitMethodEPI(*this, MoveAssignment); 9673 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9674 9675 // Add the parameter to the operator. 9676 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9677 ClassLoc, ClassLoc, /*Id=*/0, 9678 ArgType, /*TInfo=*/0, 9679 SC_None, 0); 9680 MoveAssignment->setParams(FromParam); 9681 9682 AddOverriddenMethods(ClassDecl, MoveAssignment); 9683 9684 MoveAssignment->setTrivial( 9685 ClassDecl->needsOverloadResolutionForMoveAssignment() 9686 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9687 : ClassDecl->hasTrivialMoveAssignment()); 9688 9689 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9690 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9691 SetDeclDeleted(MoveAssignment, ClassLoc); 9692 } 9693 9694 // Note that we have added this copy-assignment operator. 9695 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9696 9697 if (Scope *S = getScopeForContext(ClassDecl)) 9698 PushOnScopeChains(MoveAssignment, S, false); 9699 ClassDecl->addDecl(MoveAssignment); 9700 9701 return MoveAssignment; 9702 } 9703 9704 /// Check if we're implicitly defining a move assignment operator for a class 9705 /// with virtual bases. Such a move assignment might move-assign the virtual 9706 /// base multiple times. 9707 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9708 SourceLocation CurrentLocation) { 9709 assert(!Class->isDependentContext() && "should not define dependent move"); 9710 9711 // Only a virtual base could get implicitly move-assigned multiple times. 9712 // Only a non-trivial move assignment can observe this. We only want to 9713 // diagnose if we implicitly define an assignment operator that assigns 9714 // two base classes, both of which move-assign the same virtual base. 9715 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9716 Class->getNumBases() < 2) 9717 return; 9718 9719 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9720 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9721 VBaseMap VBases; 9722 9723 for (CXXRecordDecl::base_class_iterator BI = Class->bases_begin(), 9724 BE = Class->bases_end(); 9725 BI != BE; ++BI) { 9726 Worklist.push_back(&*BI); 9727 while (!Worklist.empty()) { 9728 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9729 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9730 9731 // If the base has no non-trivial move assignment operators, 9732 // we don't care about moves from it. 9733 if (!Base->hasNonTrivialMoveAssignment()) 9734 continue; 9735 9736 // If there's nothing virtual here, skip it. 9737 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9738 continue; 9739 9740 // If we're not actually going to call a move assignment for this base, 9741 // or the selected move assignment is trivial, skip it. 9742 Sema::SpecialMemberOverloadResult *SMOR = 9743 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9744 /*ConstArg*/false, /*VolatileArg*/false, 9745 /*RValueThis*/true, /*ConstThis*/false, 9746 /*VolatileThis*/false); 9747 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9748 !SMOR->getMethod()->isMoveAssignmentOperator()) 9749 continue; 9750 9751 if (BaseSpec->isVirtual()) { 9752 // We're going to move-assign this virtual base, and its move 9753 // assignment operator is not trivial. If this can happen for 9754 // multiple distinct direct bases of Class, diagnose it. (If it 9755 // only happens in one base, we'll diagnose it when synthesizing 9756 // that base class's move assignment operator.) 9757 CXXBaseSpecifier *&Existing = 9758 VBases.insert(std::make_pair(Base->getCanonicalDecl(), BI)) 9759 .first->second; 9760 if (Existing && Existing != BI) { 9761 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9762 << Class << Base; 9763 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9764 << (Base->getCanonicalDecl() == 9765 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9766 << Base << Existing->getType() << Existing->getSourceRange(); 9767 S.Diag(BI->getLocStart(), diag::note_vbase_moved_here) 9768 << (Base->getCanonicalDecl() == 9769 BI->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9770 << Base << BI->getType() << BaseSpec->getSourceRange(); 9771 9772 // Only diagnose each vbase once. 9773 Existing = 0; 9774 } 9775 } else { 9776 // Only walk over bases that have defaulted move assignment operators. 9777 // We assume that any user-provided move assignment operator handles 9778 // the multiple-moves-of-vbase case itself somehow. 9779 if (!SMOR->getMethod()->isDefaulted()) 9780 continue; 9781 9782 // We're going to move the base classes of Base. Add them to the list. 9783 for (CXXRecordDecl::base_class_iterator BI = Base->bases_begin(), 9784 BE = Base->bases_end(); 9785 BI != BE; ++BI) 9786 Worklist.push_back(&*BI); 9787 } 9788 } 9789 } 9790 } 9791 9792 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9793 CXXMethodDecl *MoveAssignOperator) { 9794 assert((MoveAssignOperator->isDefaulted() && 9795 MoveAssignOperator->isOverloadedOperator() && 9796 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9797 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9798 !MoveAssignOperator->isDeleted()) && 9799 "DefineImplicitMoveAssignment called for wrong function"); 9800 9801 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9802 9803 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9804 MoveAssignOperator->setInvalidDecl(); 9805 return; 9806 } 9807 9808 MoveAssignOperator->markUsed(Context); 9809 9810 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9811 DiagnosticErrorTrap Trap(Diags); 9812 9813 // C++0x [class.copy]p28: 9814 // The implicitly-defined or move assignment operator for a non-union class 9815 // X performs memberwise move assignment of its subobjects. The direct base 9816 // classes of X are assigned first, in the order of their declaration in the 9817 // base-specifier-list, and then the immediate non-static data members of X 9818 // are assigned, in the order in which they were declared in the class 9819 // definition. 9820 9821 // Issue a warning if our implicit move assignment operator will move 9822 // from a virtual base more than once. 9823 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 9824 9825 // The statements that form the synthesized function body. 9826 SmallVector<Stmt*, 8> Statements; 9827 9828 // The parameter for the "other" object, which we are move from. 9829 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9830 QualType OtherRefType = Other->getType()-> 9831 getAs<RValueReferenceType>()->getPointeeType(); 9832 assert(!OtherRefType.getQualifiers() && 9833 "Bad argument type of defaulted move assignment"); 9834 9835 // Our location for everything implicitly-generated. 9836 SourceLocation Loc = MoveAssignOperator->getLocation(); 9837 9838 // Builds a reference to the "other" object. 9839 RefBuilder OtherRef(Other, OtherRefType); 9840 // Cast to rvalue. 9841 MoveCastBuilder MoveOther(OtherRef); 9842 9843 // Builds the "this" pointer. 9844 ThisBuilder This; 9845 9846 // Assign base classes. 9847 bool Invalid = false; 9848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9849 E = ClassDecl->bases_end(); Base != E; ++Base) { 9850 // C++11 [class.copy]p28: 9851 // It is unspecified whether subobjects representing virtual base classes 9852 // are assigned more than once by the implicitly-defined copy assignment 9853 // operator. 9854 // FIXME: Do not assign to a vbase that will be assigned by some other base 9855 // class. For a move-assignment, this can result in the vbase being moved 9856 // multiple times. 9857 9858 // Form the assignment: 9859 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9860 QualType BaseType = Base->getType().getUnqualifiedType(); 9861 if (!BaseType->isRecordType()) { 9862 Invalid = true; 9863 continue; 9864 } 9865 9866 CXXCastPath BasePath; 9867 BasePath.push_back(Base); 9868 9869 // Construct the "from" expression, which is an implicit cast to the 9870 // appropriately-qualified base type. 9871 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9872 9873 // Dereference "this". 9874 DerefBuilder DerefThis(This); 9875 9876 // Implicitly cast "this" to the appropriately-qualified base type. 9877 CastBuilder To(DerefThis, 9878 Context.getCVRQualifiedType( 9879 BaseType, MoveAssignOperator->getTypeQualifiers()), 9880 VK_LValue, BasePath); 9881 9882 // Build the move. 9883 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9884 To, From, 9885 /*CopyingBaseSubobject=*/true, 9886 /*Copying=*/false); 9887 if (Move.isInvalid()) { 9888 Diag(CurrentLocation, diag::note_member_synthesized_at) 9889 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9890 MoveAssignOperator->setInvalidDecl(); 9891 return; 9892 } 9893 9894 // Success! Record the move. 9895 Statements.push_back(Move.takeAs<Expr>()); 9896 } 9897 9898 // Assign non-static members. 9899 for (auto *Field : ClassDecl->fields()) { 9900 if (Field->isUnnamedBitfield()) 9901 continue; 9902 9903 if (Field->isInvalidDecl()) { 9904 Invalid = true; 9905 continue; 9906 } 9907 9908 // Check for members of reference type; we can't move those. 9909 if (Field->getType()->isReferenceType()) { 9910 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9911 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9912 Diag(Field->getLocation(), diag::note_declared_at); 9913 Diag(CurrentLocation, diag::note_member_synthesized_at) 9914 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9915 Invalid = true; 9916 continue; 9917 } 9918 9919 // Check for members of const-qualified, non-class type. 9920 QualType BaseType = Context.getBaseElementType(Field->getType()); 9921 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9922 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9923 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9924 Diag(Field->getLocation(), diag::note_declared_at); 9925 Diag(CurrentLocation, diag::note_member_synthesized_at) 9926 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9927 Invalid = true; 9928 continue; 9929 } 9930 9931 // Suppress assigning zero-width bitfields. 9932 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9933 continue; 9934 9935 QualType FieldType = Field->getType().getNonReferenceType(); 9936 if (FieldType->isIncompleteArrayType()) { 9937 assert(ClassDecl->hasFlexibleArrayMember() && 9938 "Incomplete array type is not valid"); 9939 continue; 9940 } 9941 9942 // Build references to the field in the object we're copying from and to. 9943 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9944 LookupMemberName); 9945 MemberLookup.addDecl(Field); 9946 MemberLookup.resolveKind(); 9947 MemberBuilder From(MoveOther, OtherRefType, 9948 /*IsArrow=*/false, MemberLookup); 9949 MemberBuilder To(This, getCurrentThisType(), 9950 /*IsArrow=*/true, MemberLookup); 9951 9952 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9953 "Member reference with rvalue base must be rvalue except for reference " 9954 "members, which aren't allowed for move assignment."); 9955 9956 // Build the move of this field. 9957 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9958 To, From, 9959 /*CopyingBaseSubobject=*/false, 9960 /*Copying=*/false); 9961 if (Move.isInvalid()) { 9962 Diag(CurrentLocation, diag::note_member_synthesized_at) 9963 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9964 MoveAssignOperator->setInvalidDecl(); 9965 return; 9966 } 9967 9968 // Success! Record the copy. 9969 Statements.push_back(Move.takeAs<Stmt>()); 9970 } 9971 9972 if (!Invalid) { 9973 // Add a "return *this;" 9974 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9975 9976 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9977 if (Return.isInvalid()) 9978 Invalid = true; 9979 else { 9980 Statements.push_back(Return.takeAs<Stmt>()); 9981 9982 if (Trap.hasErrorOccurred()) { 9983 Diag(CurrentLocation, diag::note_member_synthesized_at) 9984 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9985 Invalid = true; 9986 } 9987 } 9988 } 9989 9990 if (Invalid) { 9991 MoveAssignOperator->setInvalidDecl(); 9992 return; 9993 } 9994 9995 StmtResult Body; 9996 { 9997 CompoundScopeRAII CompoundScope(*this); 9998 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9999 /*isStmtExpr=*/false); 10000 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10001 } 10002 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 10003 10004 if (ASTMutationListener *L = getASTMutationListener()) { 10005 L->CompletedImplicitDefinition(MoveAssignOperator); 10006 } 10007 } 10008 10009 Sema::ImplicitExceptionSpecification 10010 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10011 CXXRecordDecl *ClassDecl = MD->getParent(); 10012 10013 ImplicitExceptionSpecification ExceptSpec(*this); 10014 if (ClassDecl->isInvalidDecl()) 10015 return ExceptSpec; 10016 10017 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10018 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10019 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10020 10021 // C++ [except.spec]p14: 10022 // An implicitly declared special member function (Clause 12) shall have an 10023 // exception-specification. [...] 10024 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 10025 BaseEnd = ClassDecl->bases_end(); 10026 Base != BaseEnd; 10027 ++Base) { 10028 // Virtual bases are handled below. 10029 if (Base->isVirtual()) 10030 continue; 10031 10032 CXXRecordDecl *BaseClassDecl 10033 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10034 if (CXXConstructorDecl *CopyConstructor = 10035 LookupCopyingConstructor(BaseClassDecl, Quals)) 10036 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10037 } 10038 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 10039 BaseEnd = ClassDecl->vbases_end(); 10040 Base != BaseEnd; 10041 ++Base) { 10042 CXXRecordDecl *BaseClassDecl 10043 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10044 if (CXXConstructorDecl *CopyConstructor = 10045 LookupCopyingConstructor(BaseClassDecl, Quals)) 10046 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10047 } 10048 for (const auto *Field : ClassDecl->fields()) { 10049 QualType FieldType = Context.getBaseElementType(Field->getType()); 10050 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10051 if (CXXConstructorDecl *CopyConstructor = 10052 LookupCopyingConstructor(FieldClassDecl, 10053 Quals | FieldType.getCVRQualifiers())) 10054 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10055 } 10056 } 10057 10058 return ExceptSpec; 10059 } 10060 10061 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10062 CXXRecordDecl *ClassDecl) { 10063 // C++ [class.copy]p4: 10064 // If the class definition does not explicitly declare a copy 10065 // constructor, one is declared implicitly. 10066 assert(ClassDecl->needsImplicitCopyConstructor()); 10067 10068 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10069 if (DSM.isAlreadyBeingDeclared()) 10070 return 0; 10071 10072 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10073 QualType ArgType = ClassType; 10074 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10075 if (Const) 10076 ArgType = ArgType.withConst(); 10077 ArgType = Context.getLValueReferenceType(ArgType); 10078 10079 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10080 CXXCopyConstructor, 10081 Const); 10082 10083 DeclarationName Name 10084 = Context.DeclarationNames.getCXXConstructorName( 10085 Context.getCanonicalType(ClassType)); 10086 SourceLocation ClassLoc = ClassDecl->getLocation(); 10087 DeclarationNameInfo NameInfo(Name, ClassLoc); 10088 10089 // An implicitly-declared copy constructor is an inline public 10090 // member of its class. 10091 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10092 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10093 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10094 Constexpr); 10095 CopyConstructor->setAccess(AS_public); 10096 CopyConstructor->setDefaulted(); 10097 10098 // Build an exception specification pointing back at this member. 10099 FunctionProtoType::ExtProtoInfo EPI = 10100 getImplicitMethodEPI(*this, CopyConstructor); 10101 CopyConstructor->setType( 10102 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10103 10104 // Add the parameter to the constructor. 10105 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10106 ClassLoc, ClassLoc, 10107 /*IdentifierInfo=*/0, 10108 ArgType, /*TInfo=*/0, 10109 SC_None, 0); 10110 CopyConstructor->setParams(FromParam); 10111 10112 CopyConstructor->setTrivial( 10113 ClassDecl->needsOverloadResolutionForCopyConstructor() 10114 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10115 : ClassDecl->hasTrivialCopyConstructor()); 10116 10117 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10118 SetDeclDeleted(CopyConstructor, ClassLoc); 10119 10120 // Note that we have declared this constructor. 10121 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10122 10123 if (Scope *S = getScopeForContext(ClassDecl)) 10124 PushOnScopeChains(CopyConstructor, S, false); 10125 ClassDecl->addDecl(CopyConstructor); 10126 10127 return CopyConstructor; 10128 } 10129 10130 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10131 CXXConstructorDecl *CopyConstructor) { 10132 assert((CopyConstructor->isDefaulted() && 10133 CopyConstructor->isCopyConstructor() && 10134 !CopyConstructor->doesThisDeclarationHaveABody() && 10135 !CopyConstructor->isDeleted()) && 10136 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10137 10138 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10139 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10140 10141 // C++11 [class.copy]p7: 10142 // The [definition of an implicitly declared copy constructor] is 10143 // deprecated if the class has a user-declared copy assignment operator 10144 // or a user-declared destructor. 10145 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10146 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10147 10148 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10149 DiagnosticErrorTrap Trap(Diags); 10150 10151 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10152 Trap.hasErrorOccurred()) { 10153 Diag(CurrentLocation, diag::note_member_synthesized_at) 10154 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10155 CopyConstructor->setInvalidDecl(); 10156 } else { 10157 Sema::CompoundScopeRAII CompoundScope(*this); 10158 CopyConstructor->setBody(ActOnCompoundStmt( 10159 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10160 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10161 } 10162 10163 CopyConstructor->markUsed(Context); 10164 if (ASTMutationListener *L = getASTMutationListener()) { 10165 L->CompletedImplicitDefinition(CopyConstructor); 10166 } 10167 } 10168 10169 Sema::ImplicitExceptionSpecification 10170 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10171 CXXRecordDecl *ClassDecl = MD->getParent(); 10172 10173 // C++ [except.spec]p14: 10174 // An implicitly declared special member function (Clause 12) shall have an 10175 // exception-specification. [...] 10176 ImplicitExceptionSpecification ExceptSpec(*this); 10177 if (ClassDecl->isInvalidDecl()) 10178 return ExceptSpec; 10179 10180 // Direct base-class constructors. 10181 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 10182 BEnd = ClassDecl->bases_end(); 10183 B != BEnd; ++B) { 10184 if (B->isVirtual()) // Handled below. 10185 continue; 10186 10187 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10188 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10189 CXXConstructorDecl *Constructor = 10190 LookupMovingConstructor(BaseClassDecl, 0); 10191 // If this is a deleted function, add it anyway. This might be conformant 10192 // with the standard. This might not. I'm not sure. It might not matter. 10193 if (Constructor) 10194 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10195 } 10196 } 10197 10198 // Virtual base-class constructors. 10199 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 10200 BEnd = ClassDecl->vbases_end(); 10201 B != BEnd; ++B) { 10202 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10203 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10204 CXXConstructorDecl *Constructor = 10205 LookupMovingConstructor(BaseClassDecl, 0); 10206 // If this is a deleted function, add it anyway. This might be conformant 10207 // with the standard. This might not. I'm not sure. It might not matter. 10208 if (Constructor) 10209 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10210 } 10211 } 10212 10213 // Field constructors. 10214 for (const auto *F : ClassDecl->fields()) { 10215 QualType FieldType = Context.getBaseElementType(F->getType()); 10216 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10217 CXXConstructorDecl *Constructor = 10218 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10219 // If this is a deleted function, add it anyway. This might be conformant 10220 // with the standard. This might not. I'm not sure. It might not matter. 10221 // In particular, the problem is that this function never gets called. It 10222 // might just be ill-formed because this function attempts to refer to 10223 // a deleted function here. 10224 if (Constructor) 10225 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10226 } 10227 } 10228 10229 return ExceptSpec; 10230 } 10231 10232 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10233 CXXRecordDecl *ClassDecl) { 10234 assert(ClassDecl->needsImplicitMoveConstructor()); 10235 10236 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10237 if (DSM.isAlreadyBeingDeclared()) 10238 return 0; 10239 10240 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10241 QualType ArgType = Context.getRValueReferenceType(ClassType); 10242 10243 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10244 CXXMoveConstructor, 10245 false); 10246 10247 DeclarationName Name 10248 = Context.DeclarationNames.getCXXConstructorName( 10249 Context.getCanonicalType(ClassType)); 10250 SourceLocation ClassLoc = ClassDecl->getLocation(); 10251 DeclarationNameInfo NameInfo(Name, ClassLoc); 10252 10253 // C++11 [class.copy]p11: 10254 // An implicitly-declared copy/move constructor is an inline public 10255 // member of its class. 10256 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10257 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10258 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10259 Constexpr); 10260 MoveConstructor->setAccess(AS_public); 10261 MoveConstructor->setDefaulted(); 10262 10263 // Build an exception specification pointing back at this member. 10264 FunctionProtoType::ExtProtoInfo EPI = 10265 getImplicitMethodEPI(*this, MoveConstructor); 10266 MoveConstructor->setType( 10267 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10268 10269 // Add the parameter to the constructor. 10270 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10271 ClassLoc, ClassLoc, 10272 /*IdentifierInfo=*/0, 10273 ArgType, /*TInfo=*/0, 10274 SC_None, 0); 10275 MoveConstructor->setParams(FromParam); 10276 10277 MoveConstructor->setTrivial( 10278 ClassDecl->needsOverloadResolutionForMoveConstructor() 10279 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10280 : ClassDecl->hasTrivialMoveConstructor()); 10281 10282 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10283 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10284 SetDeclDeleted(MoveConstructor, ClassLoc); 10285 } 10286 10287 // Note that we have declared this constructor. 10288 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10289 10290 if (Scope *S = getScopeForContext(ClassDecl)) 10291 PushOnScopeChains(MoveConstructor, S, false); 10292 ClassDecl->addDecl(MoveConstructor); 10293 10294 return MoveConstructor; 10295 } 10296 10297 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10298 CXXConstructorDecl *MoveConstructor) { 10299 assert((MoveConstructor->isDefaulted() && 10300 MoveConstructor->isMoveConstructor() && 10301 !MoveConstructor->doesThisDeclarationHaveABody() && 10302 !MoveConstructor->isDeleted()) && 10303 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10304 10305 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10306 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10307 10308 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10309 DiagnosticErrorTrap Trap(Diags); 10310 10311 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10312 Trap.hasErrorOccurred()) { 10313 Diag(CurrentLocation, diag::note_member_synthesized_at) 10314 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10315 MoveConstructor->setInvalidDecl(); 10316 } else { 10317 Sema::CompoundScopeRAII CompoundScope(*this); 10318 MoveConstructor->setBody(ActOnCompoundStmt( 10319 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10320 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10321 } 10322 10323 MoveConstructor->markUsed(Context); 10324 10325 if (ASTMutationListener *L = getASTMutationListener()) { 10326 L->CompletedImplicitDefinition(MoveConstructor); 10327 } 10328 } 10329 10330 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10331 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10332 } 10333 10334 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10335 SourceLocation CurrentLocation, 10336 CXXConversionDecl *Conv) { 10337 CXXRecordDecl *Lambda = Conv->getParent(); 10338 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10339 // If we are defining a specialization of a conversion to function-ptr 10340 // cache the deduced template arguments for this specialization 10341 // so that we can use them to retrieve the corresponding call-operator 10342 // and static-invoker. 10343 const TemplateArgumentList *DeducedTemplateArgs = 0; 10344 10345 10346 // Retrieve the corresponding call-operator specialization. 10347 if (Lambda->isGenericLambda()) { 10348 assert(Conv->isFunctionTemplateSpecialization()); 10349 FunctionTemplateDecl *CallOpTemplate = 10350 CallOp->getDescribedFunctionTemplate(); 10351 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10352 void *InsertPos = 0; 10353 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10354 DeducedTemplateArgs->data(), 10355 DeducedTemplateArgs->size(), 10356 InsertPos); 10357 assert(CallOpSpec && 10358 "Conversion operator must have a corresponding call operator"); 10359 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10360 } 10361 // Mark the call operator referenced (and add to pending instantiations 10362 // if necessary). 10363 // For both the conversion and static-invoker template specializations 10364 // we construct their body's in this function, so no need to add them 10365 // to the PendingInstantiations. 10366 MarkFunctionReferenced(CurrentLocation, CallOp); 10367 10368 SynthesizedFunctionScope Scope(*this, Conv); 10369 DiagnosticErrorTrap Trap(Diags); 10370 10371 // Retrieve the static invoker... 10372 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10373 // ... and get the corresponding specialization for a generic lambda. 10374 if (Lambda->isGenericLambda()) { 10375 assert(DeducedTemplateArgs && 10376 "Must have deduced template arguments from Conversion Operator"); 10377 FunctionTemplateDecl *InvokeTemplate = 10378 Invoker->getDescribedFunctionTemplate(); 10379 void *InsertPos = 0; 10380 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10381 DeducedTemplateArgs->data(), 10382 DeducedTemplateArgs->size(), 10383 InsertPos); 10384 assert(InvokeSpec && 10385 "Must have a corresponding static invoker specialization"); 10386 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10387 } 10388 // Construct the body of the conversion function { return __invoke; }. 10389 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10390 VK_LValue, Conv->getLocation()).take(); 10391 assert(FunctionRef && "Can't refer to __invoke function?"); 10392 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10393 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10394 Conv->getLocation(), 10395 Conv->getLocation())); 10396 10397 Conv->markUsed(Context); 10398 Conv->setReferenced(); 10399 10400 // Fill in the __invoke function with a dummy implementation. IR generation 10401 // will fill in the actual details. 10402 Invoker->markUsed(Context); 10403 Invoker->setReferenced(); 10404 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10405 10406 if (ASTMutationListener *L = getASTMutationListener()) { 10407 L->CompletedImplicitDefinition(Conv); 10408 L->CompletedImplicitDefinition(Invoker); 10409 } 10410 } 10411 10412 10413 10414 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10415 SourceLocation CurrentLocation, 10416 CXXConversionDecl *Conv) 10417 { 10418 assert(!Conv->getParent()->isGenericLambda()); 10419 10420 Conv->markUsed(Context); 10421 10422 SynthesizedFunctionScope Scope(*this, Conv); 10423 DiagnosticErrorTrap Trap(Diags); 10424 10425 // Copy-initialize the lambda object as needed to capture it. 10426 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10427 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10428 10429 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10430 Conv->getLocation(), 10431 Conv, DerefThis); 10432 10433 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10434 // behavior. Note that only the general conversion function does this 10435 // (since it's unusable otherwise); in the case where we inline the 10436 // block literal, it has block literal lifetime semantics. 10437 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10438 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10439 CK_CopyAndAutoreleaseBlockObject, 10440 BuildBlock.get(), 0, VK_RValue); 10441 10442 if (BuildBlock.isInvalid()) { 10443 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10444 Conv->setInvalidDecl(); 10445 return; 10446 } 10447 10448 // Create the return statement that returns the block from the conversion 10449 // function. 10450 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10451 if (Return.isInvalid()) { 10452 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10453 Conv->setInvalidDecl(); 10454 return; 10455 } 10456 10457 // Set the body of the conversion function. 10458 Stmt *ReturnS = Return.take(); 10459 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10460 Conv->getLocation(), 10461 Conv->getLocation())); 10462 10463 // We're done; notify the mutation listener, if any. 10464 if (ASTMutationListener *L = getASTMutationListener()) { 10465 L->CompletedImplicitDefinition(Conv); 10466 } 10467 } 10468 10469 /// \brief Determine whether the given list arguments contains exactly one 10470 /// "real" (non-default) argument. 10471 static bool hasOneRealArgument(MultiExprArg Args) { 10472 switch (Args.size()) { 10473 case 0: 10474 return false; 10475 10476 default: 10477 if (!Args[1]->isDefaultArgument()) 10478 return false; 10479 10480 // fall through 10481 case 1: 10482 return !Args[0]->isDefaultArgument(); 10483 } 10484 10485 return false; 10486 } 10487 10488 ExprResult 10489 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10490 CXXConstructorDecl *Constructor, 10491 MultiExprArg ExprArgs, 10492 bool HadMultipleCandidates, 10493 bool IsListInitialization, 10494 bool RequiresZeroInit, 10495 unsigned ConstructKind, 10496 SourceRange ParenRange) { 10497 bool Elidable = false; 10498 10499 // C++0x [class.copy]p34: 10500 // When certain criteria are met, an implementation is allowed to 10501 // omit the copy/move construction of a class object, even if the 10502 // copy/move constructor and/or destructor for the object have 10503 // side effects. [...] 10504 // - when a temporary class object that has not been bound to a 10505 // reference (12.2) would be copied/moved to a class object 10506 // with the same cv-unqualified type, the copy/move operation 10507 // can be omitted by constructing the temporary object 10508 // directly into the target of the omitted copy/move 10509 if (ConstructKind == CXXConstructExpr::CK_Complete && 10510 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10511 Expr *SubExpr = ExprArgs[0]; 10512 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10513 } 10514 10515 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10516 Elidable, ExprArgs, HadMultipleCandidates, 10517 IsListInitialization, RequiresZeroInit, 10518 ConstructKind, ParenRange); 10519 } 10520 10521 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10522 /// including handling of its default argument expressions. 10523 ExprResult 10524 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10525 CXXConstructorDecl *Constructor, bool Elidable, 10526 MultiExprArg ExprArgs, 10527 bool HadMultipleCandidates, 10528 bool IsListInitialization, 10529 bool RequiresZeroInit, 10530 unsigned ConstructKind, 10531 SourceRange ParenRange) { 10532 MarkFunctionReferenced(ConstructLoc, Constructor); 10533 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10534 Constructor, Elidable, ExprArgs, 10535 HadMultipleCandidates, 10536 IsListInitialization, RequiresZeroInit, 10537 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10538 ParenRange)); 10539 } 10540 10541 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10542 if (VD->isInvalidDecl()) return; 10543 10544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10545 if (ClassDecl->isInvalidDecl()) return; 10546 if (ClassDecl->hasIrrelevantDestructor()) return; 10547 if (ClassDecl->isDependentContext()) return; 10548 10549 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10550 MarkFunctionReferenced(VD->getLocation(), Destructor); 10551 CheckDestructorAccess(VD->getLocation(), Destructor, 10552 PDiag(diag::err_access_dtor_var) 10553 << VD->getDeclName() 10554 << VD->getType()); 10555 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10556 10557 if (!VD->hasGlobalStorage()) return; 10558 10559 // Emit warning for non-trivial dtor in global scope (a real global, 10560 // class-static, function-static). 10561 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10562 10563 // TODO: this should be re-enabled for static locals by !CXAAtExit 10564 if (!VD->isStaticLocal()) 10565 Diag(VD->getLocation(), diag::warn_global_destructor); 10566 } 10567 10568 /// \brief Given a constructor and the set of arguments provided for the 10569 /// constructor, convert the arguments and add any required default arguments 10570 /// to form a proper call to this constructor. 10571 /// 10572 /// \returns true if an error occurred, false otherwise. 10573 bool 10574 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10575 MultiExprArg ArgsPtr, 10576 SourceLocation Loc, 10577 SmallVectorImpl<Expr*> &ConvertedArgs, 10578 bool AllowExplicit, 10579 bool IsListInitialization) { 10580 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10581 unsigned NumArgs = ArgsPtr.size(); 10582 Expr **Args = ArgsPtr.data(); 10583 10584 const FunctionProtoType *Proto 10585 = Constructor->getType()->getAs<FunctionProtoType>(); 10586 assert(Proto && "Constructor without a prototype?"); 10587 unsigned NumParams = Proto->getNumParams(); 10588 10589 // If too few arguments are available, we'll fill in the rest with defaults. 10590 if (NumArgs < NumParams) 10591 ConvertedArgs.reserve(NumParams); 10592 else 10593 ConvertedArgs.reserve(NumArgs); 10594 10595 VariadicCallType CallType = 10596 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10597 SmallVector<Expr *, 8> AllArgs; 10598 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10599 Proto, 0, 10600 llvm::makeArrayRef(Args, NumArgs), 10601 AllArgs, 10602 CallType, AllowExplicit, 10603 IsListInitialization); 10604 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10605 10606 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10607 10608 CheckConstructorCall(Constructor, 10609 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10610 AllArgs.size()), 10611 Proto, Loc); 10612 10613 return Invalid; 10614 } 10615 10616 static inline bool 10617 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10618 const FunctionDecl *FnDecl) { 10619 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10620 if (isa<NamespaceDecl>(DC)) { 10621 return SemaRef.Diag(FnDecl->getLocation(), 10622 diag::err_operator_new_delete_declared_in_namespace) 10623 << FnDecl->getDeclName(); 10624 } 10625 10626 if (isa<TranslationUnitDecl>(DC) && 10627 FnDecl->getStorageClass() == SC_Static) { 10628 return SemaRef.Diag(FnDecl->getLocation(), 10629 diag::err_operator_new_delete_declared_static) 10630 << FnDecl->getDeclName(); 10631 } 10632 10633 return false; 10634 } 10635 10636 static inline bool 10637 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10638 CanQualType ExpectedResultType, 10639 CanQualType ExpectedFirstParamType, 10640 unsigned DependentParamTypeDiag, 10641 unsigned InvalidParamTypeDiag) { 10642 QualType ResultType = 10643 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10644 10645 // Check that the result type is not dependent. 10646 if (ResultType->isDependentType()) 10647 return SemaRef.Diag(FnDecl->getLocation(), 10648 diag::err_operator_new_delete_dependent_result_type) 10649 << FnDecl->getDeclName() << ExpectedResultType; 10650 10651 // Check that the result type is what we expect. 10652 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10653 return SemaRef.Diag(FnDecl->getLocation(), 10654 diag::err_operator_new_delete_invalid_result_type) 10655 << FnDecl->getDeclName() << ExpectedResultType; 10656 10657 // A function template must have at least 2 parameters. 10658 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10659 return SemaRef.Diag(FnDecl->getLocation(), 10660 diag::err_operator_new_delete_template_too_few_parameters) 10661 << FnDecl->getDeclName(); 10662 10663 // The function decl must have at least 1 parameter. 10664 if (FnDecl->getNumParams() == 0) 10665 return SemaRef.Diag(FnDecl->getLocation(), 10666 diag::err_operator_new_delete_too_few_parameters) 10667 << FnDecl->getDeclName(); 10668 10669 // Check the first parameter type is not dependent. 10670 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10671 if (FirstParamType->isDependentType()) 10672 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10673 << FnDecl->getDeclName() << ExpectedFirstParamType; 10674 10675 // Check that the first parameter type is what we expect. 10676 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10677 ExpectedFirstParamType) 10678 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10679 << FnDecl->getDeclName() << ExpectedFirstParamType; 10680 10681 return false; 10682 } 10683 10684 static bool 10685 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10686 // C++ [basic.stc.dynamic.allocation]p1: 10687 // A program is ill-formed if an allocation function is declared in a 10688 // namespace scope other than global scope or declared static in global 10689 // scope. 10690 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10691 return true; 10692 10693 CanQualType SizeTy = 10694 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10695 10696 // C++ [basic.stc.dynamic.allocation]p1: 10697 // The return type shall be void*. The first parameter shall have type 10698 // std::size_t. 10699 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10700 SizeTy, 10701 diag::err_operator_new_dependent_param_type, 10702 diag::err_operator_new_param_type)) 10703 return true; 10704 10705 // C++ [basic.stc.dynamic.allocation]p1: 10706 // The first parameter shall not have an associated default argument. 10707 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10708 return SemaRef.Diag(FnDecl->getLocation(), 10709 diag::err_operator_new_default_arg) 10710 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10711 10712 return false; 10713 } 10714 10715 static bool 10716 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10717 // C++ [basic.stc.dynamic.deallocation]p1: 10718 // A program is ill-formed if deallocation functions are declared in a 10719 // namespace scope other than global scope or declared static in global 10720 // scope. 10721 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10722 return true; 10723 10724 // C++ [basic.stc.dynamic.deallocation]p2: 10725 // Each deallocation function shall return void and its first parameter 10726 // shall be void*. 10727 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10728 SemaRef.Context.VoidPtrTy, 10729 diag::err_operator_delete_dependent_param_type, 10730 diag::err_operator_delete_param_type)) 10731 return true; 10732 10733 return false; 10734 } 10735 10736 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10737 /// of this overloaded operator is well-formed. If so, returns false; 10738 /// otherwise, emits appropriate diagnostics and returns true. 10739 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10740 assert(FnDecl && FnDecl->isOverloadedOperator() && 10741 "Expected an overloaded operator declaration"); 10742 10743 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10744 10745 // C++ [over.oper]p5: 10746 // The allocation and deallocation functions, operator new, 10747 // operator new[], operator delete and operator delete[], are 10748 // described completely in 3.7.3. The attributes and restrictions 10749 // found in the rest of this subclause do not apply to them unless 10750 // explicitly stated in 3.7.3. 10751 if (Op == OO_Delete || Op == OO_Array_Delete) 10752 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10753 10754 if (Op == OO_New || Op == OO_Array_New) 10755 return CheckOperatorNewDeclaration(*this, FnDecl); 10756 10757 // C++ [over.oper]p6: 10758 // An operator function shall either be a non-static member 10759 // function or be a non-member function and have at least one 10760 // parameter whose type is a class, a reference to a class, an 10761 // enumeration, or a reference to an enumeration. 10762 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10763 if (MethodDecl->isStatic()) 10764 return Diag(FnDecl->getLocation(), 10765 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10766 } else { 10767 bool ClassOrEnumParam = false; 10768 for (auto Param : FnDecl->params()) { 10769 QualType ParamType = Param->getType().getNonReferenceType(); 10770 if (ParamType->isDependentType() || ParamType->isRecordType() || 10771 ParamType->isEnumeralType()) { 10772 ClassOrEnumParam = true; 10773 break; 10774 } 10775 } 10776 10777 if (!ClassOrEnumParam) 10778 return Diag(FnDecl->getLocation(), 10779 diag::err_operator_overload_needs_class_or_enum) 10780 << FnDecl->getDeclName(); 10781 } 10782 10783 // C++ [over.oper]p8: 10784 // An operator function cannot have default arguments (8.3.6), 10785 // except where explicitly stated below. 10786 // 10787 // Only the function-call operator allows default arguments 10788 // (C++ [over.call]p1). 10789 if (Op != OO_Call) { 10790 for (auto Param : FnDecl->params()) { 10791 if (Param->hasDefaultArg()) 10792 return Diag(Param->getLocation(), 10793 diag::err_operator_overload_default_arg) 10794 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 10795 } 10796 } 10797 10798 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10799 { false, false, false } 10800 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10801 , { Unary, Binary, MemberOnly } 10802 #include "clang/Basic/OperatorKinds.def" 10803 }; 10804 10805 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10806 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10807 bool MustBeMemberOperator = OperatorUses[Op][2]; 10808 10809 // C++ [over.oper]p8: 10810 // [...] Operator functions cannot have more or fewer parameters 10811 // than the number required for the corresponding operator, as 10812 // described in the rest of this subclause. 10813 unsigned NumParams = FnDecl->getNumParams() 10814 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10815 if (Op != OO_Call && 10816 ((NumParams == 1 && !CanBeUnaryOperator) || 10817 (NumParams == 2 && !CanBeBinaryOperator) || 10818 (NumParams < 1) || (NumParams > 2))) { 10819 // We have the wrong number of parameters. 10820 unsigned ErrorKind; 10821 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10822 ErrorKind = 2; // 2 -> unary or binary. 10823 } else if (CanBeUnaryOperator) { 10824 ErrorKind = 0; // 0 -> unary 10825 } else { 10826 assert(CanBeBinaryOperator && 10827 "All non-call overloaded operators are unary or binary!"); 10828 ErrorKind = 1; // 1 -> binary 10829 } 10830 10831 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10832 << FnDecl->getDeclName() << NumParams << ErrorKind; 10833 } 10834 10835 // Overloaded operators other than operator() cannot be variadic. 10836 if (Op != OO_Call && 10837 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10838 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10839 << FnDecl->getDeclName(); 10840 } 10841 10842 // Some operators must be non-static member functions. 10843 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10844 return Diag(FnDecl->getLocation(), 10845 diag::err_operator_overload_must_be_member) 10846 << FnDecl->getDeclName(); 10847 } 10848 10849 // C++ [over.inc]p1: 10850 // The user-defined function called operator++ implements the 10851 // prefix and postfix ++ operator. If this function is a member 10852 // function with no parameters, or a non-member function with one 10853 // parameter of class or enumeration type, it defines the prefix 10854 // increment operator ++ for objects of that type. If the function 10855 // is a member function with one parameter (which shall be of type 10856 // int) or a non-member function with two parameters (the second 10857 // of which shall be of type int), it defines the postfix 10858 // increment operator ++ for objects of that type. 10859 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10860 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10861 QualType ParamType = LastParam->getType(); 10862 10863 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 10864 !ParamType->isDependentType()) 10865 return Diag(LastParam->getLocation(), 10866 diag::err_operator_overload_post_incdec_must_be_int) 10867 << LastParam->getType() << (Op == OO_MinusMinus); 10868 } 10869 10870 return false; 10871 } 10872 10873 /// CheckLiteralOperatorDeclaration - Check whether the declaration 10874 /// of this literal operator function is well-formed. If so, returns 10875 /// false; otherwise, emits appropriate diagnostics and returns true. 10876 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10877 if (isa<CXXMethodDecl>(FnDecl)) { 10878 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10879 << FnDecl->getDeclName(); 10880 return true; 10881 } 10882 10883 if (FnDecl->isExternC()) { 10884 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10885 return true; 10886 } 10887 10888 bool Valid = false; 10889 10890 // This might be the definition of a literal operator template. 10891 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10892 // This might be a specialization of a literal operator template. 10893 if (!TpDecl) 10894 TpDecl = FnDecl->getPrimaryTemplate(); 10895 10896 // template <char...> type operator "" name() and 10897 // template <class T, T...> type operator "" name() are the only valid 10898 // template signatures, and the only valid signatures with no parameters. 10899 if (TpDecl) { 10900 if (FnDecl->param_size() == 0) { 10901 // Must have one or two template parameters 10902 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10903 if (Params->size() == 1) { 10904 NonTypeTemplateParmDecl *PmDecl = 10905 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10906 10907 // The template parameter must be a char parameter pack. 10908 if (PmDecl && PmDecl->isTemplateParameterPack() && 10909 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10910 Valid = true; 10911 } else if (Params->size() == 2) { 10912 TemplateTypeParmDecl *PmType = 10913 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10914 NonTypeTemplateParmDecl *PmArgs = 10915 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10916 10917 // The second template parameter must be a parameter pack with the 10918 // first template parameter as its type. 10919 if (PmType && PmArgs && 10920 !PmType->isTemplateParameterPack() && 10921 PmArgs->isTemplateParameterPack()) { 10922 const TemplateTypeParmType *TArgs = 10923 PmArgs->getType()->getAs<TemplateTypeParmType>(); 10924 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 10925 TArgs->getIndex() == PmType->getIndex()) { 10926 Valid = true; 10927 if (ActiveTemplateInstantiations.empty()) 10928 Diag(FnDecl->getLocation(), 10929 diag::ext_string_literal_operator_template); 10930 } 10931 } 10932 } 10933 } 10934 } else if (FnDecl->param_size()) { 10935 // Check the first parameter 10936 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10937 10938 QualType T = (*Param)->getType().getUnqualifiedType(); 10939 10940 // unsigned long long int, long double, and any character type are allowed 10941 // as the only parameters. 10942 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10943 Context.hasSameType(T, Context.LongDoubleTy) || 10944 Context.hasSameType(T, Context.CharTy) || 10945 Context.hasSameType(T, Context.WideCharTy) || 10946 Context.hasSameType(T, Context.Char16Ty) || 10947 Context.hasSameType(T, Context.Char32Ty)) { 10948 if (++Param == FnDecl->param_end()) 10949 Valid = true; 10950 goto FinishedParams; 10951 } 10952 10953 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10954 const PointerType *PT = T->getAs<PointerType>(); 10955 if (!PT) 10956 goto FinishedParams; 10957 T = PT->getPointeeType(); 10958 if (!T.isConstQualified() || T.isVolatileQualified()) 10959 goto FinishedParams; 10960 T = T.getUnqualifiedType(); 10961 10962 // Move on to the second parameter; 10963 ++Param; 10964 10965 // If there is no second parameter, the first must be a const char * 10966 if (Param == FnDecl->param_end()) { 10967 if (Context.hasSameType(T, Context.CharTy)) 10968 Valid = true; 10969 goto FinishedParams; 10970 } 10971 10972 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10973 // are allowed as the first parameter to a two-parameter function 10974 if (!(Context.hasSameType(T, Context.CharTy) || 10975 Context.hasSameType(T, Context.WideCharTy) || 10976 Context.hasSameType(T, Context.Char16Ty) || 10977 Context.hasSameType(T, Context.Char32Ty))) 10978 goto FinishedParams; 10979 10980 // The second and final parameter must be an std::size_t 10981 T = (*Param)->getType().getUnqualifiedType(); 10982 if (Context.hasSameType(T, Context.getSizeType()) && 10983 ++Param == FnDecl->param_end()) 10984 Valid = true; 10985 } 10986 10987 // FIXME: This diagnostic is absolutely terrible. 10988 FinishedParams: 10989 if (!Valid) { 10990 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10991 << FnDecl->getDeclName(); 10992 return true; 10993 } 10994 10995 // A parameter-declaration-clause containing a default argument is not 10996 // equivalent to any of the permitted forms. 10997 for (auto Param : FnDecl->params()) { 10998 if (Param->hasDefaultArg()) { 10999 Diag(Param->getDefaultArgRange().getBegin(), 11000 diag::err_literal_operator_default_argument) 11001 << Param->getDefaultArgRange(); 11002 break; 11003 } 11004 } 11005 11006 StringRef LiteralName 11007 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11008 if (LiteralName[0] != '_') { 11009 // C++11 [usrlit.suffix]p1: 11010 // Literal suffix identifiers that do not start with an underscore 11011 // are reserved for future standardization. 11012 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11013 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11014 } 11015 11016 return false; 11017 } 11018 11019 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11020 /// linkage specification, including the language and (if present) 11021 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11022 /// language string literal. LBraceLoc, if valid, provides the location of 11023 /// the '{' brace. Otherwise, this linkage specification does not 11024 /// have any braces. 11025 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11026 Expr *LangStr, 11027 SourceLocation LBraceLoc) { 11028 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11029 if (!Lit->isAscii()) { 11030 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11031 << LangStr->getSourceRange(); 11032 return 0; 11033 } 11034 11035 StringRef Lang = Lit->getString(); 11036 LinkageSpecDecl::LanguageIDs Language; 11037 if (Lang == "C") 11038 Language = LinkageSpecDecl::lang_c; 11039 else if (Lang == "C++") 11040 Language = LinkageSpecDecl::lang_cxx; 11041 else { 11042 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11043 << LangStr->getSourceRange(); 11044 return 0; 11045 } 11046 11047 // FIXME: Add all the various semantics of linkage specifications 11048 11049 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11050 LangStr->getExprLoc(), Language, 11051 LBraceLoc.isValid()); 11052 CurContext->addDecl(D); 11053 PushDeclContext(S, D); 11054 return D; 11055 } 11056 11057 /// ActOnFinishLinkageSpecification - Complete the definition of 11058 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11059 /// valid, it's the position of the closing '}' brace in a linkage 11060 /// specification that uses braces. 11061 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11062 Decl *LinkageSpec, 11063 SourceLocation RBraceLoc) { 11064 if (RBraceLoc.isValid()) { 11065 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11066 LSDecl->setRBraceLoc(RBraceLoc); 11067 } 11068 PopDeclContext(); 11069 return LinkageSpec; 11070 } 11071 11072 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11073 AttributeList *AttrList, 11074 SourceLocation SemiLoc) { 11075 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11076 // Attribute declarations appertain to empty declaration so we handle 11077 // them here. 11078 if (AttrList) 11079 ProcessDeclAttributeList(S, ED, AttrList); 11080 11081 CurContext->addDecl(ED); 11082 return ED; 11083 } 11084 11085 /// \brief Perform semantic analysis for the variable declaration that 11086 /// occurs within a C++ catch clause, returning the newly-created 11087 /// variable. 11088 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11089 TypeSourceInfo *TInfo, 11090 SourceLocation StartLoc, 11091 SourceLocation Loc, 11092 IdentifierInfo *Name) { 11093 bool Invalid = false; 11094 QualType ExDeclType = TInfo->getType(); 11095 11096 // Arrays and functions decay. 11097 if (ExDeclType->isArrayType()) 11098 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11099 else if (ExDeclType->isFunctionType()) 11100 ExDeclType = Context.getPointerType(ExDeclType); 11101 11102 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11103 // The exception-declaration shall not denote a pointer or reference to an 11104 // incomplete type, other than [cv] void*. 11105 // N2844 forbids rvalue references. 11106 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11107 Diag(Loc, diag::err_catch_rvalue_ref); 11108 Invalid = true; 11109 } 11110 11111 QualType BaseType = ExDeclType; 11112 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11113 unsigned DK = diag::err_catch_incomplete; 11114 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11115 BaseType = Ptr->getPointeeType(); 11116 Mode = 1; 11117 DK = diag::err_catch_incomplete_ptr; 11118 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11119 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11120 BaseType = Ref->getPointeeType(); 11121 Mode = 2; 11122 DK = diag::err_catch_incomplete_ref; 11123 } 11124 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11125 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11126 Invalid = true; 11127 11128 if (!Invalid && !ExDeclType->isDependentType() && 11129 RequireNonAbstractType(Loc, ExDeclType, 11130 diag::err_abstract_type_in_decl, 11131 AbstractVariableType)) 11132 Invalid = true; 11133 11134 // Only the non-fragile NeXT runtime currently supports C++ catches 11135 // of ObjC types, and no runtime supports catching ObjC types by value. 11136 if (!Invalid && getLangOpts().ObjC1) { 11137 QualType T = ExDeclType; 11138 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11139 T = RT->getPointeeType(); 11140 11141 if (T->isObjCObjectType()) { 11142 Diag(Loc, diag::err_objc_object_catch); 11143 Invalid = true; 11144 } else if (T->isObjCObjectPointerType()) { 11145 // FIXME: should this be a test for macosx-fragile specifically? 11146 if (getLangOpts().ObjCRuntime.isFragile()) 11147 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11148 } 11149 } 11150 11151 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11152 ExDeclType, TInfo, SC_None); 11153 ExDecl->setExceptionVariable(true); 11154 11155 // In ARC, infer 'retaining' for variables of retainable type. 11156 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11157 Invalid = true; 11158 11159 if (!Invalid && !ExDeclType->isDependentType()) { 11160 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11161 // Insulate this from anything else we might currently be parsing. 11162 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11163 11164 // C++ [except.handle]p16: 11165 // The object declared in an exception-declaration or, if the 11166 // exception-declaration does not specify a name, a temporary (12.2) is 11167 // copy-initialized (8.5) from the exception object. [...] 11168 // The object is destroyed when the handler exits, after the destruction 11169 // of any automatic objects initialized within the handler. 11170 // 11171 // We just pretend to initialize the object with itself, then make sure 11172 // it can be destroyed later. 11173 QualType initType = ExDeclType; 11174 11175 InitializedEntity entity = 11176 InitializedEntity::InitializeVariable(ExDecl); 11177 InitializationKind initKind = 11178 InitializationKind::CreateCopy(Loc, SourceLocation()); 11179 11180 Expr *opaqueValue = 11181 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11182 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11183 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11184 if (result.isInvalid()) 11185 Invalid = true; 11186 else { 11187 // If the constructor used was non-trivial, set this as the 11188 // "initializer". 11189 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11190 if (!construct->getConstructor()->isTrivial()) { 11191 Expr *init = MaybeCreateExprWithCleanups(construct); 11192 ExDecl->setInit(init); 11193 } 11194 11195 // And make sure it's destructable. 11196 FinalizeVarWithDestructor(ExDecl, recordType); 11197 } 11198 } 11199 } 11200 11201 if (Invalid) 11202 ExDecl->setInvalidDecl(); 11203 11204 return ExDecl; 11205 } 11206 11207 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11208 /// handler. 11209 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11210 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11211 bool Invalid = D.isInvalidType(); 11212 11213 // Check for unexpanded parameter packs. 11214 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11215 UPPC_ExceptionType)) { 11216 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11217 D.getIdentifierLoc()); 11218 Invalid = true; 11219 } 11220 11221 IdentifierInfo *II = D.getIdentifier(); 11222 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11223 LookupOrdinaryName, 11224 ForRedeclaration)) { 11225 // The scope should be freshly made just for us. There is just no way 11226 // it contains any previous declaration. 11227 assert(!S->isDeclScope(PrevDecl)); 11228 if (PrevDecl->isTemplateParameter()) { 11229 // Maybe we will complain about the shadowed template parameter. 11230 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11231 PrevDecl = 0; 11232 } 11233 } 11234 11235 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11236 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11237 << D.getCXXScopeSpec().getRange(); 11238 Invalid = true; 11239 } 11240 11241 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11242 D.getLocStart(), 11243 D.getIdentifierLoc(), 11244 D.getIdentifier()); 11245 if (Invalid) 11246 ExDecl->setInvalidDecl(); 11247 11248 // Add the exception declaration into this scope. 11249 if (II) 11250 PushOnScopeChains(ExDecl, S); 11251 else 11252 CurContext->addDecl(ExDecl); 11253 11254 ProcessDeclAttributes(S, ExDecl, D); 11255 return ExDecl; 11256 } 11257 11258 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11259 Expr *AssertExpr, 11260 Expr *AssertMessageExpr, 11261 SourceLocation RParenLoc) { 11262 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11263 11264 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11265 return 0; 11266 11267 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11268 AssertMessage, RParenLoc, false); 11269 } 11270 11271 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11272 Expr *AssertExpr, 11273 StringLiteral *AssertMessage, 11274 SourceLocation RParenLoc, 11275 bool Failed) { 11276 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11277 !Failed) { 11278 // In a static_assert-declaration, the constant-expression shall be a 11279 // constant expression that can be contextually converted to bool. 11280 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11281 if (Converted.isInvalid()) 11282 Failed = true; 11283 11284 llvm::APSInt Cond; 11285 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11286 diag::err_static_assert_expression_is_not_constant, 11287 /*AllowFold=*/false).isInvalid()) 11288 Failed = true; 11289 11290 if (!Failed && !Cond) { 11291 SmallString<256> MsgBuffer; 11292 llvm::raw_svector_ostream Msg(MsgBuffer); 11293 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11294 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11295 << Msg.str() << AssertExpr->getSourceRange(); 11296 Failed = true; 11297 } 11298 } 11299 11300 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11301 AssertExpr, AssertMessage, RParenLoc, 11302 Failed); 11303 11304 CurContext->addDecl(Decl); 11305 return Decl; 11306 } 11307 11308 /// \brief Perform semantic analysis of the given friend type declaration. 11309 /// 11310 /// \returns A friend declaration that. 11311 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11312 SourceLocation FriendLoc, 11313 TypeSourceInfo *TSInfo) { 11314 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11315 11316 QualType T = TSInfo->getType(); 11317 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11318 11319 // C++03 [class.friend]p2: 11320 // An elaborated-type-specifier shall be used in a friend declaration 11321 // for a class.* 11322 // 11323 // * The class-key of the elaborated-type-specifier is required. 11324 if (!ActiveTemplateInstantiations.empty()) { 11325 // Do not complain about the form of friend template types during 11326 // template instantiation; we will already have complained when the 11327 // template was declared. 11328 } else { 11329 if (!T->isElaboratedTypeSpecifier()) { 11330 // If we evaluated the type to a record type, suggest putting 11331 // a tag in front. 11332 if (const RecordType *RT = T->getAs<RecordType>()) { 11333 RecordDecl *RD = RT->getDecl(); 11334 11335 std::string InsertionText = std::string(" ") + RD->getKindName(); 11336 11337 Diag(TypeRange.getBegin(), 11338 getLangOpts().CPlusPlus11 ? 11339 diag::warn_cxx98_compat_unelaborated_friend_type : 11340 diag::ext_unelaborated_friend_type) 11341 << (unsigned) RD->getTagKind() 11342 << T 11343 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11344 InsertionText); 11345 } else { 11346 Diag(FriendLoc, 11347 getLangOpts().CPlusPlus11 ? 11348 diag::warn_cxx98_compat_nonclass_type_friend : 11349 diag::ext_nonclass_type_friend) 11350 << T 11351 << TypeRange; 11352 } 11353 } else if (T->getAs<EnumType>()) { 11354 Diag(FriendLoc, 11355 getLangOpts().CPlusPlus11 ? 11356 diag::warn_cxx98_compat_enum_friend : 11357 diag::ext_enum_friend) 11358 << T 11359 << TypeRange; 11360 } 11361 11362 // C++11 [class.friend]p3: 11363 // A friend declaration that does not declare a function shall have one 11364 // of the following forms: 11365 // friend elaborated-type-specifier ; 11366 // friend simple-type-specifier ; 11367 // friend typename-specifier ; 11368 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11369 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11370 } 11371 11372 // If the type specifier in a friend declaration designates a (possibly 11373 // cv-qualified) class type, that class is declared as a friend; otherwise, 11374 // the friend declaration is ignored. 11375 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11376 } 11377 11378 /// Handle a friend tag declaration where the scope specifier was 11379 /// templated. 11380 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11381 unsigned TagSpec, SourceLocation TagLoc, 11382 CXXScopeSpec &SS, 11383 IdentifierInfo *Name, 11384 SourceLocation NameLoc, 11385 AttributeList *Attr, 11386 MultiTemplateParamsArg TempParamLists) { 11387 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11388 11389 bool isExplicitSpecialization = false; 11390 bool Invalid = false; 11391 11392 if (TemplateParameterList *TemplateParams = 11393 MatchTemplateParametersToScopeSpecifier( 11394 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11395 isExplicitSpecialization, Invalid)) { 11396 if (TemplateParams->size() > 0) { 11397 // This is a declaration of a class template. 11398 if (Invalid) 11399 return 0; 11400 11401 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11402 SS, Name, NameLoc, Attr, 11403 TemplateParams, AS_public, 11404 /*ModulePrivateLoc=*/SourceLocation(), 11405 TempParamLists.size() - 1, 11406 TempParamLists.data()).take(); 11407 } else { 11408 // The "template<>" header is extraneous. 11409 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11410 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11411 isExplicitSpecialization = true; 11412 } 11413 } 11414 11415 if (Invalid) return 0; 11416 11417 bool isAllExplicitSpecializations = true; 11418 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11419 if (TempParamLists[I]->size()) { 11420 isAllExplicitSpecializations = false; 11421 break; 11422 } 11423 } 11424 11425 // FIXME: don't ignore attributes. 11426 11427 // If it's explicit specializations all the way down, just forget 11428 // about the template header and build an appropriate non-templated 11429 // friend. TODO: for source fidelity, remember the headers. 11430 if (isAllExplicitSpecializations) { 11431 if (SS.isEmpty()) { 11432 bool Owned = false; 11433 bool IsDependent = false; 11434 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11435 Attr, AS_public, 11436 /*ModulePrivateLoc=*/SourceLocation(), 11437 MultiTemplateParamsArg(), Owned, IsDependent, 11438 /*ScopedEnumKWLoc=*/SourceLocation(), 11439 /*ScopedEnumUsesClassTag=*/false, 11440 /*UnderlyingType=*/TypeResult(), 11441 /*IsTypeSpecifier=*/false); 11442 } 11443 11444 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11445 ElaboratedTypeKeyword Keyword 11446 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11447 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11448 *Name, NameLoc); 11449 if (T.isNull()) 11450 return 0; 11451 11452 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11453 if (isa<DependentNameType>(T)) { 11454 DependentNameTypeLoc TL = 11455 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11456 TL.setElaboratedKeywordLoc(TagLoc); 11457 TL.setQualifierLoc(QualifierLoc); 11458 TL.setNameLoc(NameLoc); 11459 } else { 11460 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11461 TL.setElaboratedKeywordLoc(TagLoc); 11462 TL.setQualifierLoc(QualifierLoc); 11463 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11464 } 11465 11466 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11467 TSI, FriendLoc, TempParamLists); 11468 Friend->setAccess(AS_public); 11469 CurContext->addDecl(Friend); 11470 return Friend; 11471 } 11472 11473 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11474 11475 11476 11477 // Handle the case of a templated-scope friend class. e.g. 11478 // template <class T> class A<T>::B; 11479 // FIXME: we don't support these right now. 11480 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11481 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11482 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11483 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11484 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11485 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11486 TL.setElaboratedKeywordLoc(TagLoc); 11487 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11488 TL.setNameLoc(NameLoc); 11489 11490 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11491 TSI, FriendLoc, TempParamLists); 11492 Friend->setAccess(AS_public); 11493 Friend->setUnsupportedFriend(true); 11494 CurContext->addDecl(Friend); 11495 return Friend; 11496 } 11497 11498 11499 /// Handle a friend type declaration. This works in tandem with 11500 /// ActOnTag. 11501 /// 11502 /// Notes on friend class templates: 11503 /// 11504 /// We generally treat friend class declarations as if they were 11505 /// declaring a class. So, for example, the elaborated type specifier 11506 /// in a friend declaration is required to obey the restrictions of a 11507 /// class-head (i.e. no typedefs in the scope chain), template 11508 /// parameters are required to match up with simple template-ids, &c. 11509 /// However, unlike when declaring a template specialization, it's 11510 /// okay to refer to a template specialization without an empty 11511 /// template parameter declaration, e.g. 11512 /// friend class A<T>::B<unsigned>; 11513 /// We permit this as a special case; if there are any template 11514 /// parameters present at all, require proper matching, i.e. 11515 /// template <> template \<class T> friend class A<int>::B; 11516 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11517 MultiTemplateParamsArg TempParams) { 11518 SourceLocation Loc = DS.getLocStart(); 11519 11520 assert(DS.isFriendSpecified()); 11521 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11522 11523 // Try to convert the decl specifier to a type. This works for 11524 // friend templates because ActOnTag never produces a ClassTemplateDecl 11525 // for a TUK_Friend. 11526 Declarator TheDeclarator(DS, Declarator::MemberContext); 11527 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11528 QualType T = TSI->getType(); 11529 if (TheDeclarator.isInvalidType()) 11530 return 0; 11531 11532 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11533 return 0; 11534 11535 // This is definitely an error in C++98. It's probably meant to 11536 // be forbidden in C++0x, too, but the specification is just 11537 // poorly written. 11538 // 11539 // The problem is with declarations like the following: 11540 // template <T> friend A<T>::foo; 11541 // where deciding whether a class C is a friend or not now hinges 11542 // on whether there exists an instantiation of A that causes 11543 // 'foo' to equal C. There are restrictions on class-heads 11544 // (which we declare (by fiat) elaborated friend declarations to 11545 // be) that makes this tractable. 11546 // 11547 // FIXME: handle "template <> friend class A<T>;", which 11548 // is possibly well-formed? Who even knows? 11549 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11550 Diag(Loc, diag::err_tagless_friend_type_template) 11551 << DS.getSourceRange(); 11552 return 0; 11553 } 11554 11555 // C++98 [class.friend]p1: A friend of a class is a function 11556 // or class that is not a member of the class . . . 11557 // This is fixed in DR77, which just barely didn't make the C++03 11558 // deadline. It's also a very silly restriction that seriously 11559 // affects inner classes and which nobody else seems to implement; 11560 // thus we never diagnose it, not even in -pedantic. 11561 // 11562 // But note that we could warn about it: it's always useless to 11563 // friend one of your own members (it's not, however, worthless to 11564 // friend a member of an arbitrary specialization of your template). 11565 11566 Decl *D; 11567 if (unsigned NumTempParamLists = TempParams.size()) 11568 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11569 NumTempParamLists, 11570 TempParams.data(), 11571 TSI, 11572 DS.getFriendSpecLoc()); 11573 else 11574 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11575 11576 if (!D) 11577 return 0; 11578 11579 D->setAccess(AS_public); 11580 CurContext->addDecl(D); 11581 11582 return D; 11583 } 11584 11585 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11586 MultiTemplateParamsArg TemplateParams) { 11587 const DeclSpec &DS = D.getDeclSpec(); 11588 11589 assert(DS.isFriendSpecified()); 11590 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11591 11592 SourceLocation Loc = D.getIdentifierLoc(); 11593 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11594 11595 // C++ [class.friend]p1 11596 // A friend of a class is a function or class.... 11597 // Note that this sees through typedefs, which is intended. 11598 // It *doesn't* see through dependent types, which is correct 11599 // according to [temp.arg.type]p3: 11600 // If a declaration acquires a function type through a 11601 // type dependent on a template-parameter and this causes 11602 // a declaration that does not use the syntactic form of a 11603 // function declarator to have a function type, the program 11604 // is ill-formed. 11605 if (!TInfo->getType()->isFunctionType()) { 11606 Diag(Loc, diag::err_unexpected_friend); 11607 11608 // It might be worthwhile to try to recover by creating an 11609 // appropriate declaration. 11610 return 0; 11611 } 11612 11613 // C++ [namespace.memdef]p3 11614 // - If a friend declaration in a non-local class first declares a 11615 // class or function, the friend class or function is a member 11616 // of the innermost enclosing namespace. 11617 // - The name of the friend is not found by simple name lookup 11618 // until a matching declaration is provided in that namespace 11619 // scope (either before or after the class declaration granting 11620 // friendship). 11621 // - If a friend function is called, its name may be found by the 11622 // name lookup that considers functions from namespaces and 11623 // classes associated with the types of the function arguments. 11624 // - When looking for a prior declaration of a class or a function 11625 // declared as a friend, scopes outside the innermost enclosing 11626 // namespace scope are not considered. 11627 11628 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11629 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11630 DeclarationName Name = NameInfo.getName(); 11631 assert(Name); 11632 11633 // Check for unexpanded parameter packs. 11634 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11635 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11636 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11637 return 0; 11638 11639 // The context we found the declaration in, or in which we should 11640 // create the declaration. 11641 DeclContext *DC; 11642 Scope *DCScope = S; 11643 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11644 ForRedeclaration); 11645 11646 // There are five cases here. 11647 // - There's no scope specifier and we're in a local class. Only look 11648 // for functions declared in the immediately-enclosing block scope. 11649 // We recover from invalid scope qualifiers as if they just weren't there. 11650 FunctionDecl *FunctionContainingLocalClass = 0; 11651 if ((SS.isInvalid() || !SS.isSet()) && 11652 (FunctionContainingLocalClass = 11653 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11654 // C++11 [class.friend]p11: 11655 // If a friend declaration appears in a local class and the name 11656 // specified is an unqualified name, a prior declaration is 11657 // looked up without considering scopes that are outside the 11658 // innermost enclosing non-class scope. For a friend function 11659 // declaration, if there is no prior declaration, the program is 11660 // ill-formed. 11661 11662 // Find the innermost enclosing non-class scope. This is the block 11663 // scope containing the local class definition (or for a nested class, 11664 // the outer local class). 11665 DCScope = S->getFnParent(); 11666 11667 // Look up the function name in the scope. 11668 Previous.clear(LookupLocalFriendName); 11669 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11670 11671 if (!Previous.empty()) { 11672 // All possible previous declarations must have the same context: 11673 // either they were declared at block scope or they are members of 11674 // one of the enclosing local classes. 11675 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11676 } else { 11677 // This is ill-formed, but provide the context that we would have 11678 // declared the function in, if we were permitted to, for error recovery. 11679 DC = FunctionContainingLocalClass; 11680 } 11681 adjustContextForLocalExternDecl(DC); 11682 11683 // C++ [class.friend]p6: 11684 // A function can be defined in a friend declaration of a class if and 11685 // only if the class is a non-local class (9.8), the function name is 11686 // unqualified, and the function has namespace scope. 11687 if (D.isFunctionDefinition()) { 11688 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11689 } 11690 11691 // - There's no scope specifier, in which case we just go to the 11692 // appropriate scope and look for a function or function template 11693 // there as appropriate. 11694 } else if (SS.isInvalid() || !SS.isSet()) { 11695 // C++11 [namespace.memdef]p3: 11696 // If the name in a friend declaration is neither qualified nor 11697 // a template-id and the declaration is a function or an 11698 // elaborated-type-specifier, the lookup to determine whether 11699 // the entity has been previously declared shall not consider 11700 // any scopes outside the innermost enclosing namespace. 11701 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11702 11703 // Find the appropriate context according to the above. 11704 DC = CurContext; 11705 11706 // Skip class contexts. If someone can cite chapter and verse 11707 // for this behavior, that would be nice --- it's what GCC and 11708 // EDG do, and it seems like a reasonable intent, but the spec 11709 // really only says that checks for unqualified existing 11710 // declarations should stop at the nearest enclosing namespace, 11711 // not that they should only consider the nearest enclosing 11712 // namespace. 11713 while (DC->isRecord()) 11714 DC = DC->getParent(); 11715 11716 DeclContext *LookupDC = DC; 11717 while (LookupDC->isTransparentContext()) 11718 LookupDC = LookupDC->getParent(); 11719 11720 while (true) { 11721 LookupQualifiedName(Previous, LookupDC); 11722 11723 if (!Previous.empty()) { 11724 DC = LookupDC; 11725 break; 11726 } 11727 11728 if (isTemplateId) { 11729 if (isa<TranslationUnitDecl>(LookupDC)) break; 11730 } else { 11731 if (LookupDC->isFileContext()) break; 11732 } 11733 LookupDC = LookupDC->getParent(); 11734 } 11735 11736 DCScope = getScopeForDeclContext(S, DC); 11737 11738 // - There's a non-dependent scope specifier, in which case we 11739 // compute it and do a previous lookup there for a function 11740 // or function template. 11741 } else if (!SS.getScopeRep()->isDependent()) { 11742 DC = computeDeclContext(SS); 11743 if (!DC) return 0; 11744 11745 if (RequireCompleteDeclContext(SS, DC)) return 0; 11746 11747 LookupQualifiedName(Previous, DC); 11748 11749 // Ignore things found implicitly in the wrong scope. 11750 // TODO: better diagnostics for this case. Suggesting the right 11751 // qualified scope would be nice... 11752 LookupResult::Filter F = Previous.makeFilter(); 11753 while (F.hasNext()) { 11754 NamedDecl *D = F.next(); 11755 if (!DC->InEnclosingNamespaceSetOf( 11756 D->getDeclContext()->getRedeclContext())) 11757 F.erase(); 11758 } 11759 F.done(); 11760 11761 if (Previous.empty()) { 11762 D.setInvalidType(); 11763 Diag(Loc, diag::err_qualified_friend_not_found) 11764 << Name << TInfo->getType(); 11765 return 0; 11766 } 11767 11768 // C++ [class.friend]p1: A friend of a class is a function or 11769 // class that is not a member of the class . . . 11770 if (DC->Equals(CurContext)) 11771 Diag(DS.getFriendSpecLoc(), 11772 getLangOpts().CPlusPlus11 ? 11773 diag::warn_cxx98_compat_friend_is_member : 11774 diag::err_friend_is_member); 11775 11776 if (D.isFunctionDefinition()) { 11777 // C++ [class.friend]p6: 11778 // A function can be defined in a friend declaration of a class if and 11779 // only if the class is a non-local class (9.8), the function name is 11780 // unqualified, and the function has namespace scope. 11781 SemaDiagnosticBuilder DB 11782 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11783 11784 DB << SS.getScopeRep(); 11785 if (DC->isFileContext()) 11786 DB << FixItHint::CreateRemoval(SS.getRange()); 11787 SS.clear(); 11788 } 11789 11790 // - There's a scope specifier that does not match any template 11791 // parameter lists, in which case we use some arbitrary context, 11792 // create a method or method template, and wait for instantiation. 11793 // - There's a scope specifier that does match some template 11794 // parameter lists, which we don't handle right now. 11795 } else { 11796 if (D.isFunctionDefinition()) { 11797 // C++ [class.friend]p6: 11798 // A function can be defined in a friend declaration of a class if and 11799 // only if the class is a non-local class (9.8), the function name is 11800 // unqualified, and the function has namespace scope. 11801 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11802 << SS.getScopeRep(); 11803 } 11804 11805 DC = CurContext; 11806 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11807 } 11808 11809 if (!DC->isRecord()) { 11810 // This implies that it has to be an operator or function. 11811 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11812 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11813 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11814 Diag(Loc, diag::err_introducing_special_friend) << 11815 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11816 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11817 return 0; 11818 } 11819 } 11820 11821 // FIXME: This is an egregious hack to cope with cases where the scope stack 11822 // does not contain the declaration context, i.e., in an out-of-line 11823 // definition of a class. 11824 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11825 if (!DCScope) { 11826 FakeDCScope.setEntity(DC); 11827 DCScope = &FakeDCScope; 11828 } 11829 11830 bool AddToScope = true; 11831 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11832 TemplateParams, AddToScope); 11833 if (!ND) return 0; 11834 11835 assert(ND->getLexicalDeclContext() == CurContext); 11836 11837 // If we performed typo correction, we might have added a scope specifier 11838 // and changed the decl context. 11839 DC = ND->getDeclContext(); 11840 11841 // Add the function declaration to the appropriate lookup tables, 11842 // adjusting the redeclarations list as necessary. We don't 11843 // want to do this yet if the friending class is dependent. 11844 // 11845 // Also update the scope-based lookup if the target context's 11846 // lookup context is in lexical scope. 11847 if (!CurContext->isDependentContext()) { 11848 DC = DC->getRedeclContext(); 11849 DC->makeDeclVisibleInContext(ND); 11850 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11851 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11852 } 11853 11854 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11855 D.getIdentifierLoc(), ND, 11856 DS.getFriendSpecLoc()); 11857 FrD->setAccess(AS_public); 11858 CurContext->addDecl(FrD); 11859 11860 if (ND->isInvalidDecl()) { 11861 FrD->setInvalidDecl(); 11862 } else { 11863 if (DC->isRecord()) CheckFriendAccess(ND); 11864 11865 FunctionDecl *FD; 11866 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11867 FD = FTD->getTemplatedDecl(); 11868 else 11869 FD = cast<FunctionDecl>(ND); 11870 11871 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11872 // default argument expression, that declaration shall be a definition 11873 // and shall be the only declaration of the function or function 11874 // template in the translation unit. 11875 if (functionDeclHasDefaultArgument(FD)) { 11876 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11877 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11878 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11879 } else if (!D.isFunctionDefinition()) 11880 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11881 } 11882 11883 // Mark templated-scope function declarations as unsupported. 11884 if (FD->getNumTemplateParameterLists()) 11885 FrD->setUnsupportedFriend(true); 11886 } 11887 11888 return ND; 11889 } 11890 11891 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11892 AdjustDeclIfTemplate(Dcl); 11893 11894 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11895 if (!Fn) { 11896 Diag(DelLoc, diag::err_deleted_non_function); 11897 return; 11898 } 11899 11900 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11901 // Don't consider the implicit declaration we generate for explicit 11902 // specializations. FIXME: Do not generate these implicit declarations. 11903 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 11904 Prev->getPreviousDecl()) && 11905 !Prev->isDefined()) { 11906 Diag(DelLoc, diag::err_deleted_decl_not_first); 11907 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 11908 Prev->isImplicit() ? diag::note_previous_implicit_declaration 11909 : diag::note_previous_declaration); 11910 } 11911 // If the declaration wasn't the first, we delete the function anyway for 11912 // recovery. 11913 Fn = Fn->getCanonicalDecl(); 11914 } 11915 11916 if (Fn->isDeleted()) 11917 return; 11918 11919 // See if we're deleting a function which is already known to override a 11920 // non-deleted virtual function. 11921 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11922 bool IssuedDiagnostic = false; 11923 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11924 E = MD->end_overridden_methods(); 11925 I != E; ++I) { 11926 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11927 if (!IssuedDiagnostic) { 11928 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11929 IssuedDiagnostic = true; 11930 } 11931 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11932 } 11933 } 11934 } 11935 11936 // C++11 [basic.start.main]p3: 11937 // A program that defines main as deleted [...] is ill-formed. 11938 if (Fn->isMain()) 11939 Diag(DelLoc, diag::err_deleted_main); 11940 11941 Fn->setDeletedAsWritten(); 11942 } 11943 11944 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11945 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11946 11947 if (MD) { 11948 if (MD->getParent()->isDependentType()) { 11949 MD->setDefaulted(); 11950 MD->setExplicitlyDefaulted(); 11951 return; 11952 } 11953 11954 CXXSpecialMember Member = getSpecialMember(MD); 11955 if (Member == CXXInvalid) { 11956 if (!MD->isInvalidDecl()) 11957 Diag(DefaultLoc, diag::err_default_special_members); 11958 return; 11959 } 11960 11961 MD->setDefaulted(); 11962 MD->setExplicitlyDefaulted(); 11963 11964 // If this definition appears within the record, do the checking when 11965 // the record is complete. 11966 const FunctionDecl *Primary = MD; 11967 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11968 // Find the uninstantiated declaration that actually had the '= default' 11969 // on it. 11970 Pattern->isDefined(Primary); 11971 11972 // If the method was defaulted on its first declaration, we will have 11973 // already performed the checking in CheckCompletedCXXClass. Such a 11974 // declaration doesn't trigger an implicit definition. 11975 if (Primary == Primary->getCanonicalDecl()) 11976 return; 11977 11978 CheckExplicitlyDefaultedSpecialMember(MD); 11979 11980 // The exception specification is needed because we are defining the 11981 // function. 11982 ResolveExceptionSpec(DefaultLoc, 11983 MD->getType()->castAs<FunctionProtoType>()); 11984 11985 if (MD->isInvalidDecl()) 11986 return; 11987 11988 switch (Member) { 11989 case CXXDefaultConstructor: 11990 DefineImplicitDefaultConstructor(DefaultLoc, 11991 cast<CXXConstructorDecl>(MD)); 11992 break; 11993 case CXXCopyConstructor: 11994 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11995 break; 11996 case CXXCopyAssignment: 11997 DefineImplicitCopyAssignment(DefaultLoc, MD); 11998 break; 11999 case CXXDestructor: 12000 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12001 break; 12002 case CXXMoveConstructor: 12003 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12004 break; 12005 case CXXMoveAssignment: 12006 DefineImplicitMoveAssignment(DefaultLoc, MD); 12007 break; 12008 case CXXInvalid: 12009 llvm_unreachable("Invalid special member."); 12010 } 12011 } else { 12012 Diag(DefaultLoc, diag::err_default_special_members); 12013 } 12014 } 12015 12016 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12017 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12018 Stmt *SubStmt = *CI; 12019 if (!SubStmt) 12020 continue; 12021 if (isa<ReturnStmt>(SubStmt)) 12022 Self.Diag(SubStmt->getLocStart(), 12023 diag::err_return_in_constructor_handler); 12024 if (!isa<Expr>(SubStmt)) 12025 SearchForReturnInStmt(Self, SubStmt); 12026 } 12027 } 12028 12029 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12030 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12031 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12032 SearchForReturnInStmt(*this, Handler); 12033 } 12034 } 12035 12036 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12037 const CXXMethodDecl *Old) { 12038 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12039 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12040 12041 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12042 12043 // If the calling conventions match, everything is fine 12044 if (NewCC == OldCC) 12045 return false; 12046 12047 // If the calling conventions mismatch because the new function is static, 12048 // suppress the calling convention mismatch error; the error about static 12049 // function override (err_static_overrides_virtual from 12050 // Sema::CheckFunctionDeclaration) is more clear. 12051 if (New->getStorageClass() == SC_Static) 12052 return false; 12053 12054 Diag(New->getLocation(), 12055 diag::err_conflicting_overriding_cc_attributes) 12056 << New->getDeclName() << New->getType() << Old->getType(); 12057 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12058 return true; 12059 } 12060 12061 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12062 const CXXMethodDecl *Old) { 12063 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12064 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12065 12066 if (Context.hasSameType(NewTy, OldTy) || 12067 NewTy->isDependentType() || OldTy->isDependentType()) 12068 return false; 12069 12070 // Check if the return types are covariant 12071 QualType NewClassTy, OldClassTy; 12072 12073 /// Both types must be pointers or references to classes. 12074 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12075 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12076 NewClassTy = NewPT->getPointeeType(); 12077 OldClassTy = OldPT->getPointeeType(); 12078 } 12079 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12080 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12081 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12082 NewClassTy = NewRT->getPointeeType(); 12083 OldClassTy = OldRT->getPointeeType(); 12084 } 12085 } 12086 } 12087 12088 // The return types aren't either both pointers or references to a class type. 12089 if (NewClassTy.isNull()) { 12090 Diag(New->getLocation(), 12091 diag::err_different_return_type_for_overriding_virtual_function) 12092 << New->getDeclName() << NewTy << OldTy; 12093 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12094 12095 return true; 12096 } 12097 12098 // C++ [class.virtual]p6: 12099 // If the return type of D::f differs from the return type of B::f, the 12100 // class type in the return type of D::f shall be complete at the point of 12101 // declaration of D::f or shall be the class type D. 12102 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12103 if (!RT->isBeingDefined() && 12104 RequireCompleteType(New->getLocation(), NewClassTy, 12105 diag::err_covariant_return_incomplete, 12106 New->getDeclName())) 12107 return true; 12108 } 12109 12110 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12111 // Check if the new class derives from the old class. 12112 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12113 Diag(New->getLocation(), 12114 diag::err_covariant_return_not_derived) 12115 << New->getDeclName() << NewTy << OldTy; 12116 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12117 return true; 12118 } 12119 12120 // Check if we the conversion from derived to base is valid. 12121 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12122 diag::err_covariant_return_inaccessible_base, 12123 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12124 // FIXME: Should this point to the return type? 12125 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12126 // FIXME: this note won't trigger for delayed access control 12127 // diagnostics, and it's impossible to get an undelayed error 12128 // here from access control during the original parse because 12129 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12130 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12131 return true; 12132 } 12133 } 12134 12135 // The qualifiers of the return types must be the same. 12136 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12137 Diag(New->getLocation(), 12138 diag::err_covariant_return_type_different_qualifications) 12139 << New->getDeclName() << NewTy << OldTy; 12140 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12141 return true; 12142 }; 12143 12144 12145 // The new class type must have the same or less qualifiers as the old type. 12146 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12147 Diag(New->getLocation(), 12148 diag::err_covariant_return_type_class_type_more_qualified) 12149 << New->getDeclName() << NewTy << OldTy; 12150 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12151 return true; 12152 }; 12153 12154 return false; 12155 } 12156 12157 /// \brief Mark the given method pure. 12158 /// 12159 /// \param Method the method to be marked pure. 12160 /// 12161 /// \param InitRange the source range that covers the "0" initializer. 12162 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12163 SourceLocation EndLoc = InitRange.getEnd(); 12164 if (EndLoc.isValid()) 12165 Method->setRangeEnd(EndLoc); 12166 12167 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12168 Method->setPure(); 12169 return false; 12170 } 12171 12172 if (!Method->isInvalidDecl()) 12173 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12174 << Method->getDeclName() << InitRange; 12175 return true; 12176 } 12177 12178 /// \brief Determine whether the given declaration is a static data member. 12179 static bool isStaticDataMember(const Decl *D) { 12180 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12181 return Var->isStaticDataMember(); 12182 12183 return false; 12184 } 12185 12186 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12187 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12188 /// is a fresh scope pushed for just this purpose. 12189 /// 12190 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12191 /// static data member of class X, names should be looked up in the scope of 12192 /// class X. 12193 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12194 // If there is no declaration, there was an error parsing it. 12195 if (D == 0 || D->isInvalidDecl()) return; 12196 12197 // We will always have a nested name specifier here, but this declaration 12198 // might not be out of line if the specifier names the current namespace: 12199 // extern int n; 12200 // int ::n = 0; 12201 if (D->isOutOfLine()) 12202 EnterDeclaratorContext(S, D->getDeclContext()); 12203 12204 // If we are parsing the initializer for a static data member, push a 12205 // new expression evaluation context that is associated with this static 12206 // data member. 12207 if (isStaticDataMember(D)) 12208 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12209 } 12210 12211 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12212 /// initializer for the out-of-line declaration 'D'. 12213 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12214 // If there is no declaration, there was an error parsing it. 12215 if (D == 0 || D->isInvalidDecl()) return; 12216 12217 if (isStaticDataMember(D)) 12218 PopExpressionEvaluationContext(); 12219 12220 if (D->isOutOfLine()) 12221 ExitDeclaratorContext(S); 12222 } 12223 12224 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12225 /// C++ if/switch/while/for statement. 12226 /// e.g: "if (int x = f()) {...}" 12227 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12228 // C++ 6.4p2: 12229 // The declarator shall not specify a function or an array. 12230 // The type-specifier-seq shall not contain typedef and shall not declare a 12231 // new class or enumeration. 12232 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12233 "Parser allowed 'typedef' as storage class of condition decl."); 12234 12235 Decl *Dcl = ActOnDeclarator(S, D); 12236 if (!Dcl) 12237 return true; 12238 12239 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12240 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12241 << D.getSourceRange(); 12242 return true; 12243 } 12244 12245 return Dcl; 12246 } 12247 12248 void Sema::LoadExternalVTableUses() { 12249 if (!ExternalSource) 12250 return; 12251 12252 SmallVector<ExternalVTableUse, 4> VTables; 12253 ExternalSource->ReadUsedVTables(VTables); 12254 SmallVector<VTableUse, 4> NewUses; 12255 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12256 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12257 = VTablesUsed.find(VTables[I].Record); 12258 // Even if a definition wasn't required before, it may be required now. 12259 if (Pos != VTablesUsed.end()) { 12260 if (!Pos->second && VTables[I].DefinitionRequired) 12261 Pos->second = true; 12262 continue; 12263 } 12264 12265 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12266 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12267 } 12268 12269 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12270 } 12271 12272 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12273 bool DefinitionRequired) { 12274 // Ignore any vtable uses in unevaluated operands or for classes that do 12275 // not have a vtable. 12276 if (!Class->isDynamicClass() || Class->isDependentContext() || 12277 CurContext->isDependentContext() || isUnevaluatedContext()) 12278 return; 12279 12280 // Try to insert this class into the map. 12281 LoadExternalVTableUses(); 12282 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12283 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12284 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12285 if (!Pos.second) { 12286 // If we already had an entry, check to see if we are promoting this vtable 12287 // to required a definition. If so, we need to reappend to the VTableUses 12288 // list, since we may have already processed the first entry. 12289 if (DefinitionRequired && !Pos.first->second) { 12290 Pos.first->second = true; 12291 } else { 12292 // Otherwise, we can early exit. 12293 return; 12294 } 12295 } else { 12296 // The Microsoft ABI requires that we perform the destructor body 12297 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12298 // the deleting destructor is emitted with the vtable, not with the 12299 // destructor definition as in the Itanium ABI. 12300 // If it has a definition, we do the check at that point instead. 12301 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12302 Class->hasUserDeclaredDestructor() && 12303 !Class->getDestructor()->isDefined() && 12304 !Class->getDestructor()->isDeleted()) { 12305 CheckDestructor(Class->getDestructor()); 12306 } 12307 } 12308 12309 // Local classes need to have their virtual members marked 12310 // immediately. For all other classes, we mark their virtual members 12311 // at the end of the translation unit. 12312 if (Class->isLocalClass()) 12313 MarkVirtualMembersReferenced(Loc, Class); 12314 else 12315 VTableUses.push_back(std::make_pair(Class, Loc)); 12316 } 12317 12318 bool Sema::DefineUsedVTables() { 12319 LoadExternalVTableUses(); 12320 if (VTableUses.empty()) 12321 return false; 12322 12323 // Note: The VTableUses vector could grow as a result of marking 12324 // the members of a class as "used", so we check the size each 12325 // time through the loop and prefer indices (which are stable) to 12326 // iterators (which are not). 12327 bool DefinedAnything = false; 12328 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12329 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12330 if (!Class) 12331 continue; 12332 12333 SourceLocation Loc = VTableUses[I].second; 12334 12335 bool DefineVTable = true; 12336 12337 // If this class has a key function, but that key function is 12338 // defined in another translation unit, we don't need to emit the 12339 // vtable even though we're using it. 12340 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12341 if (KeyFunction && !KeyFunction->hasBody()) { 12342 // The key function is in another translation unit. 12343 DefineVTable = false; 12344 TemplateSpecializationKind TSK = 12345 KeyFunction->getTemplateSpecializationKind(); 12346 assert(TSK != TSK_ExplicitInstantiationDefinition && 12347 TSK != TSK_ImplicitInstantiation && 12348 "Instantiations don't have key functions"); 12349 (void)TSK; 12350 } else if (!KeyFunction) { 12351 // If we have a class with no key function that is the subject 12352 // of an explicit instantiation declaration, suppress the 12353 // vtable; it will live with the explicit instantiation 12354 // definition. 12355 bool IsExplicitInstantiationDeclaration 12356 = Class->getTemplateSpecializationKind() 12357 == TSK_ExplicitInstantiationDeclaration; 12358 for (auto R : Class->redecls()) { 12359 TemplateSpecializationKind TSK 12360 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12361 if (TSK == TSK_ExplicitInstantiationDeclaration) 12362 IsExplicitInstantiationDeclaration = true; 12363 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12364 IsExplicitInstantiationDeclaration = false; 12365 break; 12366 } 12367 } 12368 12369 if (IsExplicitInstantiationDeclaration) 12370 DefineVTable = false; 12371 } 12372 12373 // The exception specifications for all virtual members may be needed even 12374 // if we are not providing an authoritative form of the vtable in this TU. 12375 // We may choose to emit it available_externally anyway. 12376 if (!DefineVTable) { 12377 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12378 continue; 12379 } 12380 12381 // Mark all of the virtual members of this class as referenced, so 12382 // that we can build a vtable. Then, tell the AST consumer that a 12383 // vtable for this class is required. 12384 DefinedAnything = true; 12385 MarkVirtualMembersReferenced(Loc, Class); 12386 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12387 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12388 12389 // Optionally warn if we're emitting a weak vtable. 12390 if (Class->isExternallyVisible() && 12391 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12392 const FunctionDecl *KeyFunctionDef = 0; 12393 if (!KeyFunction || 12394 (KeyFunction->hasBody(KeyFunctionDef) && 12395 KeyFunctionDef->isInlined())) 12396 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12397 TSK_ExplicitInstantiationDefinition 12398 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12399 << Class; 12400 } 12401 } 12402 VTableUses.clear(); 12403 12404 return DefinedAnything; 12405 } 12406 12407 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12408 const CXXRecordDecl *RD) { 12409 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 12410 E = RD->method_end(); I != E; ++I) 12411 if ((*I)->isVirtual() && !(*I)->isPure()) 12412 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 12413 } 12414 12415 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12416 const CXXRecordDecl *RD) { 12417 // Mark all functions which will appear in RD's vtable as used. 12418 CXXFinalOverriderMap FinalOverriders; 12419 RD->getFinalOverriders(FinalOverriders); 12420 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12421 E = FinalOverriders.end(); 12422 I != E; ++I) { 12423 for (OverridingMethods::const_iterator OI = I->second.begin(), 12424 OE = I->second.end(); 12425 OI != OE; ++OI) { 12426 assert(OI->second.size() > 0 && "no final overrider"); 12427 CXXMethodDecl *Overrider = OI->second.front().Method; 12428 12429 // C++ [basic.def.odr]p2: 12430 // [...] A virtual member function is used if it is not pure. [...] 12431 if (!Overrider->isPure()) 12432 MarkFunctionReferenced(Loc, Overrider); 12433 } 12434 } 12435 12436 // Only classes that have virtual bases need a VTT. 12437 if (RD->getNumVBases() == 0) 12438 return; 12439 12440 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 12441 e = RD->bases_end(); i != e; ++i) { 12442 const CXXRecordDecl *Base = 12443 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 12444 if (Base->getNumVBases() == 0) 12445 continue; 12446 MarkVirtualMembersReferenced(Loc, Base); 12447 } 12448 } 12449 12450 /// SetIvarInitializers - This routine builds initialization ASTs for the 12451 /// Objective-C implementation whose ivars need be initialized. 12452 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12453 if (!getLangOpts().CPlusPlus) 12454 return; 12455 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12456 SmallVector<ObjCIvarDecl*, 8> ivars; 12457 CollectIvarsToConstructOrDestruct(OID, ivars); 12458 if (ivars.empty()) 12459 return; 12460 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12461 for (unsigned i = 0; i < ivars.size(); i++) { 12462 FieldDecl *Field = ivars[i]; 12463 if (Field->isInvalidDecl()) 12464 continue; 12465 12466 CXXCtorInitializer *Member; 12467 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12468 InitializationKind InitKind = 12469 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12470 12471 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12472 ExprResult MemberInit = 12473 InitSeq.Perform(*this, InitEntity, InitKind, None); 12474 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12475 // Note, MemberInit could actually come back empty if no initialization 12476 // is required (e.g., because it would call a trivial default constructor) 12477 if (!MemberInit.get() || MemberInit.isInvalid()) 12478 continue; 12479 12480 Member = 12481 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12482 SourceLocation(), 12483 MemberInit.takeAs<Expr>(), 12484 SourceLocation()); 12485 AllToInit.push_back(Member); 12486 12487 // Be sure that the destructor is accessible and is marked as referenced. 12488 if (const RecordType *RecordTy 12489 = Context.getBaseElementType(Field->getType()) 12490 ->getAs<RecordType>()) { 12491 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12492 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12493 MarkFunctionReferenced(Field->getLocation(), Destructor); 12494 CheckDestructorAccess(Field->getLocation(), Destructor, 12495 PDiag(diag::err_access_dtor_ivar) 12496 << Context.getBaseElementType(Field->getType())); 12497 } 12498 } 12499 } 12500 ObjCImplementation->setIvarInitializers(Context, 12501 AllToInit.data(), AllToInit.size()); 12502 } 12503 } 12504 12505 static 12506 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12507 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12508 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12509 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12510 Sema &S) { 12511 if (Ctor->isInvalidDecl()) 12512 return; 12513 12514 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12515 12516 // Target may not be determinable yet, for instance if this is a dependent 12517 // call in an uninstantiated template. 12518 if (Target) { 12519 const FunctionDecl *FNTarget = 0; 12520 (void)Target->hasBody(FNTarget); 12521 Target = const_cast<CXXConstructorDecl*>( 12522 cast_or_null<CXXConstructorDecl>(FNTarget)); 12523 } 12524 12525 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12526 // Avoid dereferencing a null pointer here. 12527 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12528 12529 if (!Current.insert(Canonical)) 12530 return; 12531 12532 // We know that beyond here, we aren't chaining into a cycle. 12533 if (!Target || !Target->isDelegatingConstructor() || 12534 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12535 Valid.insert(Current.begin(), Current.end()); 12536 Current.clear(); 12537 // We've hit a cycle. 12538 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12539 Current.count(TCanonical)) { 12540 // If we haven't diagnosed this cycle yet, do so now. 12541 if (!Invalid.count(TCanonical)) { 12542 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12543 diag::warn_delegating_ctor_cycle) 12544 << Ctor; 12545 12546 // Don't add a note for a function delegating directly to itself. 12547 if (TCanonical != Canonical) 12548 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12549 12550 CXXConstructorDecl *C = Target; 12551 while (C->getCanonicalDecl() != Canonical) { 12552 const FunctionDecl *FNTarget = 0; 12553 (void)C->getTargetConstructor()->hasBody(FNTarget); 12554 assert(FNTarget && "Ctor cycle through bodiless function"); 12555 12556 C = const_cast<CXXConstructorDecl*>( 12557 cast<CXXConstructorDecl>(FNTarget)); 12558 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12559 } 12560 } 12561 12562 Invalid.insert(Current.begin(), Current.end()); 12563 Current.clear(); 12564 } else { 12565 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12566 } 12567 } 12568 12569 12570 void Sema::CheckDelegatingCtorCycles() { 12571 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12572 12573 for (DelegatingCtorDeclsType::iterator 12574 I = DelegatingCtorDecls.begin(ExternalSource), 12575 E = DelegatingCtorDecls.end(); 12576 I != E; ++I) 12577 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12578 12579 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12580 CE = Invalid.end(); 12581 CI != CE; ++CI) 12582 (*CI)->setInvalidDecl(); 12583 } 12584 12585 namespace { 12586 /// \brief AST visitor that finds references to the 'this' expression. 12587 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12588 Sema &S; 12589 12590 public: 12591 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12592 12593 bool VisitCXXThisExpr(CXXThisExpr *E) { 12594 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12595 << E->isImplicit(); 12596 return false; 12597 } 12598 }; 12599 } 12600 12601 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12602 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12603 if (!TSInfo) 12604 return false; 12605 12606 TypeLoc TL = TSInfo->getTypeLoc(); 12607 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12608 if (!ProtoTL) 12609 return false; 12610 12611 // C++11 [expr.prim.general]p3: 12612 // [The expression this] shall not appear before the optional 12613 // cv-qualifier-seq and it shall not appear within the declaration of a 12614 // static member function (although its type and value category are defined 12615 // within a static member function as they are within a non-static member 12616 // function). [ Note: this is because declaration matching does not occur 12617 // until the complete declarator is known. - end note ] 12618 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12619 FindCXXThisExpr Finder(*this); 12620 12621 // If the return type came after the cv-qualifier-seq, check it now. 12622 if (Proto->hasTrailingReturn() && 12623 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12624 return true; 12625 12626 // Check the exception specification. 12627 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12628 return true; 12629 12630 return checkThisInStaticMemberFunctionAttributes(Method); 12631 } 12632 12633 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12634 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12635 if (!TSInfo) 12636 return false; 12637 12638 TypeLoc TL = TSInfo->getTypeLoc(); 12639 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12640 if (!ProtoTL) 12641 return false; 12642 12643 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12644 FindCXXThisExpr Finder(*this); 12645 12646 switch (Proto->getExceptionSpecType()) { 12647 case EST_Uninstantiated: 12648 case EST_Unevaluated: 12649 case EST_BasicNoexcept: 12650 case EST_DynamicNone: 12651 case EST_MSAny: 12652 case EST_None: 12653 break; 12654 12655 case EST_ComputedNoexcept: 12656 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12657 return true; 12658 12659 case EST_Dynamic: 12660 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12661 EEnd = Proto->exception_end(); 12662 E != EEnd; ++E) { 12663 if (!Finder.TraverseType(*E)) 12664 return true; 12665 } 12666 break; 12667 } 12668 12669 return false; 12670 } 12671 12672 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12673 FindCXXThisExpr Finder(*this); 12674 12675 // Check attributes. 12676 for (const auto *A : Method->attrs()) { 12677 // FIXME: This should be emitted by tblgen. 12678 Expr *Arg = 0; 12679 ArrayRef<Expr *> Args; 12680 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12681 Arg = G->getArg(); 12682 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12683 Arg = G->getArg(); 12684 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12685 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12686 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12687 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12688 else if (const auto *ELF = dyn_cast<ExclusiveLockFunctionAttr>(A)) 12689 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12690 else if (const auto *SLF = dyn_cast<SharedLockFunctionAttr>(A)) 12691 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12692 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12693 Arg = ETLF->getSuccessValue(); 12694 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12695 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12696 Arg = STLF->getSuccessValue(); 12697 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12698 } else if (const auto *UF = dyn_cast<UnlockFunctionAttr>(A)) 12699 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12700 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12701 Arg = LR->getArg(); 12702 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12703 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12704 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12705 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12706 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12707 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12708 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12709 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12710 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12711 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12712 12713 if (Arg && !Finder.TraverseStmt(Arg)) 12714 return true; 12715 12716 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12717 if (!Finder.TraverseStmt(Args[I])) 12718 return true; 12719 } 12720 } 12721 12722 return false; 12723 } 12724 12725 void 12726 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12727 ArrayRef<ParsedType> DynamicExceptions, 12728 ArrayRef<SourceRange> DynamicExceptionRanges, 12729 Expr *NoexceptExpr, 12730 SmallVectorImpl<QualType> &Exceptions, 12731 FunctionProtoType::ExtProtoInfo &EPI) { 12732 Exceptions.clear(); 12733 EPI.ExceptionSpecType = EST; 12734 if (EST == EST_Dynamic) { 12735 Exceptions.reserve(DynamicExceptions.size()); 12736 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12737 // FIXME: Preserve type source info. 12738 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12739 12740 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12741 collectUnexpandedParameterPacks(ET, Unexpanded); 12742 if (!Unexpanded.empty()) { 12743 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12744 UPPC_ExceptionType, 12745 Unexpanded); 12746 continue; 12747 } 12748 12749 // Check that the type is valid for an exception spec, and 12750 // drop it if not. 12751 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12752 Exceptions.push_back(ET); 12753 } 12754 EPI.NumExceptions = Exceptions.size(); 12755 EPI.Exceptions = Exceptions.data(); 12756 return; 12757 } 12758 12759 if (EST == EST_ComputedNoexcept) { 12760 // If an error occurred, there's no expression here. 12761 if (NoexceptExpr) { 12762 assert((NoexceptExpr->isTypeDependent() || 12763 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12764 Context.BoolTy) && 12765 "Parser should have made sure that the expression is boolean"); 12766 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12767 EPI.ExceptionSpecType = EST_BasicNoexcept; 12768 return; 12769 } 12770 12771 if (!NoexceptExpr->isValueDependent()) 12772 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12773 diag::err_noexcept_needs_constant_expression, 12774 /*AllowFold*/ false).take(); 12775 EPI.NoexceptExpr = NoexceptExpr; 12776 } 12777 return; 12778 } 12779 } 12780 12781 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12782 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12783 // Implicitly declared functions (e.g. copy constructors) are 12784 // __host__ __device__ 12785 if (D->isImplicit()) 12786 return CFT_HostDevice; 12787 12788 if (D->hasAttr<CUDAGlobalAttr>()) 12789 return CFT_Global; 12790 12791 if (D->hasAttr<CUDADeviceAttr>()) { 12792 if (D->hasAttr<CUDAHostAttr>()) 12793 return CFT_HostDevice; 12794 return CFT_Device; 12795 } 12796 12797 return CFT_Host; 12798 } 12799 12800 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12801 CUDAFunctionTarget CalleeTarget) { 12802 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12803 // Callable from the device only." 12804 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12805 return true; 12806 12807 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12808 // Callable from the host only." 12809 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12810 // Callable from the host only." 12811 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12812 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12813 return true; 12814 12815 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12816 return true; 12817 12818 return false; 12819 } 12820 12821 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12822 /// 12823 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12824 SourceLocation DeclStart, 12825 Declarator &D, Expr *BitWidth, 12826 InClassInitStyle InitStyle, 12827 AccessSpecifier AS, 12828 AttributeList *MSPropertyAttr) { 12829 IdentifierInfo *II = D.getIdentifier(); 12830 if (!II) { 12831 Diag(DeclStart, diag::err_anonymous_property); 12832 return NULL; 12833 } 12834 SourceLocation Loc = D.getIdentifierLoc(); 12835 12836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12837 QualType T = TInfo->getType(); 12838 if (getLangOpts().CPlusPlus) { 12839 CheckExtraCXXDefaultArguments(D); 12840 12841 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12842 UPPC_DataMemberType)) { 12843 D.setInvalidType(); 12844 T = Context.IntTy; 12845 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12846 } 12847 } 12848 12849 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12850 12851 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12852 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12853 diag::err_invalid_thread) 12854 << DeclSpec::getSpecifierName(TSCS); 12855 12856 // Check to see if this name was declared as a member previously 12857 NamedDecl *PrevDecl = 0; 12858 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12859 LookupName(Previous, S); 12860 switch (Previous.getResultKind()) { 12861 case LookupResult::Found: 12862 case LookupResult::FoundUnresolvedValue: 12863 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12864 break; 12865 12866 case LookupResult::FoundOverloaded: 12867 PrevDecl = Previous.getRepresentativeDecl(); 12868 break; 12869 12870 case LookupResult::NotFound: 12871 case LookupResult::NotFoundInCurrentInstantiation: 12872 case LookupResult::Ambiguous: 12873 break; 12874 } 12875 12876 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12877 // Maybe we will complain about the shadowed template parameter. 12878 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12879 // Just pretend that we didn't see the previous declaration. 12880 PrevDecl = 0; 12881 } 12882 12883 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12884 PrevDecl = 0; 12885 12886 SourceLocation TSSL = D.getLocStart(); 12887 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12888 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 12889 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 12890 ProcessDeclAttributes(TUScope, NewPD, D); 12891 NewPD->setAccess(AS); 12892 12893 if (NewPD->isInvalidDecl()) 12894 Record->setInvalidDecl(); 12895 12896 if (D.getDeclSpec().isModulePrivateSpecified()) 12897 NewPD->setModulePrivate(); 12898 12899 if (NewPD->isInvalidDecl() && PrevDecl) { 12900 // Don't introduce NewFD into scope; there's already something 12901 // with the same name in the same scope. 12902 } else if (II) { 12903 PushOnScopeChains(NewPD, S); 12904 } else 12905 Record->addDecl(NewPD); 12906 12907 return NewPD; 12908 } 12909