SemaDeclCXX.cpp revision 0943168ac126b8047f30f6bd215fbe7db14d61ba
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/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/CharUnits.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclVisitor.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Sema/DeclSpec.h" 29#include "clang/Sema/ParsedTemplate.h" 30#include "clang/Basic/PartialDiagnostic.h" 31#include "clang/Lex/Preprocessor.h" 32#include "llvm/ADT/DenseSet.h" 33#include "llvm/ADT/STLExtras.h" 34#include <map> 35#include <set> 36 37using namespace clang; 38 39//===----------------------------------------------------------------------===// 40// CheckDefaultArgumentVisitor 41//===----------------------------------------------------------------------===// 42 43namespace { 44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 45 /// the default argument of a parameter to determine whether it 46 /// contains any ill-formed subexpressions. For example, this will 47 /// diagnose the use of local variables or parameters within the 48 /// default argument expression. 49 class CheckDefaultArgumentVisitor 50 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 51 Expr *DefaultArg; 52 Sema *S; 53 54 public: 55 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 56 : DefaultArg(defarg), S(s) {} 57 58 bool VisitExpr(Expr *Node); 59 bool VisitDeclRefExpr(DeclRefExpr *DRE); 60 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 61 }; 62 63 /// VisitExpr - Visit all of the children of this expression. 64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 65 bool IsInvalid = false; 66 for (Stmt::child_iterator I = Node->child_begin(), 67 E = Node->child_end(); I != E; ++I) 68 IsInvalid |= Visit(*I); 69 return IsInvalid; 70 } 71 72 /// VisitDeclRefExpr - Visit a reference to a declaration, to 73 /// determine whether this declaration can be used in the default 74 /// argument expression. 75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 76 NamedDecl *Decl = DRE->getDecl(); 77 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 78 // C++ [dcl.fct.default]p9 79 // Default arguments are evaluated each time the function is 80 // called. The order of evaluation of function arguments is 81 // unspecified. Consequently, parameters of a function shall not 82 // be used in default argument expressions, even if they are not 83 // evaluated. Parameters of a function declared before a default 84 // argument expression are in scope and can hide namespace and 85 // class member names. 86 return S->Diag(DRE->getSourceRange().getBegin(), 87 diag::err_param_default_argument_references_param) 88 << Param->getDeclName() << DefaultArg->getSourceRange(); 89 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p7 91 // Local variables shall not be used in default argument 92 // expressions. 93 if (VDecl->isLocalVarDecl()) 94 return S->Diag(DRE->getSourceRange().getBegin(), 95 diag::err_param_default_argument_references_local) 96 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 97 } 98 99 return false; 100 } 101 102 /// VisitCXXThisExpr - Visit a C++ "this" expression. 103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 104 // C++ [dcl.fct.default]p8: 105 // The keyword this shall not be used in a default argument of a 106 // member function. 107 return S->Diag(ThisE->getSourceRange().getBegin(), 108 diag::err_param_default_argument_references_this) 109 << ThisE->getSourceRange(); 110 } 111} 112 113bool 114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 115 SourceLocation EqualLoc) { 116 if (RequireCompleteType(Param->getLocation(), Param->getType(), 117 diag::err_typecheck_decl_incomplete_type)) { 118 Param->setInvalidDecl(); 119 return true; 120 } 121 122 // C++ [dcl.fct.default]p5 123 // A default argument expression is implicitly converted (clause 124 // 4) to the parameter type. The default argument expression has 125 // the same semantic constraints as the initializer expression in 126 // a declaration of a variable of the parameter type, using the 127 // copy-initialization semantics (8.5). 128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 129 Param); 130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 131 EqualLoc); 132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 134 MultiExprArg(*this, &Arg, 1)); 135 if (Result.isInvalid()) 136 return true; 137 Arg = Result.takeAs<Expr>(); 138 139 CheckImplicitConversions(Arg, EqualLoc); 140 Arg = MaybeCreateCXXExprWithTemporaries(Arg); 141 142 // Okay: add the default argument to the parameter 143 Param->setDefaultArg(Arg); 144 145 // We have already instantiated this parameter; provide each of the 146 // instantiations with the uninstantiated default argument. 147 UnparsedDefaultArgInstantiationsMap::iterator InstPos 148 = UnparsedDefaultArgInstantiations.find(Param); 149 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 152 153 // We're done tracking this parameter's instantiations. 154 UnparsedDefaultArgInstantiations.erase(InstPos); 155 } 156 157 return false; 158} 159 160/// ActOnParamDefaultArgument - Check whether the default argument 161/// provided for a function parameter is well-formed. If so, attach it 162/// to the parameter declaration. 163void 164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 165 Expr *DefaultArg) { 166 if (!param || !DefaultArg) 167 return; 168 169 ParmVarDecl *Param = cast<ParmVarDecl>(param); 170 UnparsedDefaultArgLocs.erase(Param); 171 172 // Default arguments are only permitted in C++ 173 if (!getLangOptions().CPlusPlus) { 174 Diag(EqualLoc, diag::err_param_default_argument) 175 << DefaultArg->getSourceRange(); 176 Param->setInvalidDecl(); 177 return; 178 } 179 180 // Check that the default argument is well-formed 181 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 182 if (DefaultArgChecker.Visit(DefaultArg)) { 183 Param->setInvalidDecl(); 184 return; 185 } 186 187 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 188} 189 190/// ActOnParamUnparsedDefaultArgument - We've seen a default 191/// argument for a function parameter, but we can't parse it yet 192/// because we're inside a class definition. Note that this default 193/// argument will be parsed later. 194void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 195 SourceLocation EqualLoc, 196 SourceLocation ArgLoc) { 197 if (!param) 198 return; 199 200 ParmVarDecl *Param = cast<ParmVarDecl>(param); 201 if (Param) 202 Param->setUnparsedDefaultArg(); 203 204 UnparsedDefaultArgLocs[Param] = ArgLoc; 205} 206 207/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 208/// the default argument for the parameter param failed. 209void Sema::ActOnParamDefaultArgumentError(Decl *param) { 210 if (!param) 211 return; 212 213 ParmVarDecl *Param = cast<ParmVarDecl>(param); 214 215 Param->setInvalidDecl(); 216 217 UnparsedDefaultArgLocs.erase(Param); 218} 219 220/// CheckExtraCXXDefaultArguments - Check for any extra default 221/// arguments in the declarator, which is not a function declaration 222/// or definition and therefore is not permitted to have default 223/// arguments. This routine should be invoked for every declarator 224/// that is not a function declaration or definition. 225void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 226 // C++ [dcl.fct.default]p3 227 // A default argument expression shall be specified only in the 228 // parameter-declaration-clause of a function declaration or in a 229 // template-parameter (14.1). It shall not be specified for a 230 // parameter pack. If it is specified in a 231 // parameter-declaration-clause, it shall not occur within a 232 // declarator or abstract-declarator of a parameter-declaration. 233 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 234 DeclaratorChunk &chunk = D.getTypeObject(i); 235 if (chunk.Kind == DeclaratorChunk::Function) { 236 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 237 ParmVarDecl *Param = 238 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 239 if (Param->hasUnparsedDefaultArg()) { 240 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 241 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 242 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 243 delete Toks; 244 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 245 } else if (Param->getDefaultArg()) { 246 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 247 << Param->getDefaultArg()->getSourceRange(); 248 Param->setDefaultArg(0); 249 } 250 } 251 } 252 } 253} 254 255// MergeCXXFunctionDecl - Merge two declarations of the same C++ 256// function, once we already know that they have the same 257// type. Subroutine of MergeFunctionDecl. Returns true if there was an 258// error, false otherwise. 259bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 260 bool Invalid = false; 261 262 // C++ [dcl.fct.default]p4: 263 // For non-template functions, default arguments can be added in 264 // later declarations of a function in the same 265 // scope. Declarations in different scopes have completely 266 // distinct sets of default arguments. That is, declarations in 267 // inner scopes do not acquire default arguments from 268 // declarations in outer scopes, and vice versa. In a given 269 // function declaration, all parameters subsequent to a 270 // parameter with a default argument shall have default 271 // arguments supplied in this or previous declarations. A 272 // default argument shall not be redefined by a later 273 // declaration (not even to the same value). 274 // 275 // C++ [dcl.fct.default]p6: 276 // Except for member functions of class templates, the default arguments 277 // in a member function definition that appears outside of the class 278 // definition are added to the set of default arguments provided by the 279 // member function declaration in the class definition. 280 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 281 ParmVarDecl *OldParam = Old->getParamDecl(p); 282 ParmVarDecl *NewParam = New->getParamDecl(p); 283 284 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 285 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 286 // hint here. Alternatively, we could walk the type-source information 287 // for NewParam to find the last source location in the type... but it 288 // isn't worth the effort right now. This is the kind of test case that 289 // is hard to get right: 290 291 // int f(int); 292 // void g(int (*fp)(int) = f); 293 // void g(int (*fp)(int) = &f); 294 Diag(NewParam->getLocation(), 295 diag::err_param_default_argument_redefinition) 296 << NewParam->getDefaultArgRange(); 297 298 // Look for the function declaration where the default argument was 299 // actually written, which may be a declaration prior to Old. 300 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 301 Older; Older = Older->getPreviousDeclaration()) { 302 if (!Older->getParamDecl(p)->hasDefaultArg()) 303 break; 304 305 OldParam = Older->getParamDecl(p); 306 } 307 308 Diag(OldParam->getLocation(), diag::note_previous_definition) 309 << OldParam->getDefaultArgRange(); 310 Invalid = true; 311 } else if (OldParam->hasDefaultArg()) { 312 // Merge the old default argument into the new parameter. 313 // It's important to use getInit() here; getDefaultArg() 314 // strips off any top-level CXXExprWithTemporaries. 315 NewParam->setHasInheritedDefaultArg(); 316 if (OldParam->hasUninstantiatedDefaultArg()) 317 NewParam->setUninstantiatedDefaultArg( 318 OldParam->getUninstantiatedDefaultArg()); 319 else 320 NewParam->setDefaultArg(OldParam->getInit()); 321 } else if (NewParam->hasDefaultArg()) { 322 if (New->getDescribedFunctionTemplate()) { 323 // Paragraph 4, quoted above, only applies to non-template functions. 324 Diag(NewParam->getLocation(), 325 diag::err_param_default_argument_template_redecl) 326 << NewParam->getDefaultArgRange(); 327 Diag(Old->getLocation(), diag::note_template_prev_declaration) 328 << false; 329 } else if (New->getTemplateSpecializationKind() 330 != TSK_ImplicitInstantiation && 331 New->getTemplateSpecializationKind() != TSK_Undeclared) { 332 // C++ [temp.expr.spec]p21: 333 // Default function arguments shall not be specified in a declaration 334 // or a definition for one of the following explicit specializations: 335 // - the explicit specialization of a function template; 336 // - the explicit specialization of a member function template; 337 // - the explicit specialization of a member function of a class 338 // template where the class template specialization to which the 339 // member function specialization belongs is implicitly 340 // instantiated. 341 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 342 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 343 << New->getDeclName() 344 << NewParam->getDefaultArgRange(); 345 } else if (New->getDeclContext()->isDependentContext()) { 346 // C++ [dcl.fct.default]p6 (DR217): 347 // Default arguments for a member function of a class template shall 348 // be specified on the initial declaration of the member function 349 // within the class template. 350 // 351 // Reading the tea leaves a bit in DR217 and its reference to DR205 352 // leads me to the conclusion that one cannot add default function 353 // arguments for an out-of-line definition of a member function of a 354 // dependent type. 355 int WhichKind = 2; 356 if (CXXRecordDecl *Record 357 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 358 if (Record->getDescribedClassTemplate()) 359 WhichKind = 0; 360 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 361 WhichKind = 1; 362 else 363 WhichKind = 2; 364 } 365 366 Diag(NewParam->getLocation(), 367 diag::err_param_default_argument_member_template_redecl) 368 << WhichKind 369 << NewParam->getDefaultArgRange(); 370 } 371 } 372 } 373 374 if (CheckEquivalentExceptionSpec(Old, New)) 375 Invalid = true; 376 377 return Invalid; 378} 379 380/// CheckCXXDefaultArguments - Verify that the default arguments for a 381/// function declaration are well-formed according to C++ 382/// [dcl.fct.default]. 383void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 384 unsigned NumParams = FD->getNumParams(); 385 unsigned p; 386 387 // Find first parameter with a default argument 388 for (p = 0; p < NumParams; ++p) { 389 ParmVarDecl *Param = FD->getParamDecl(p); 390 if (Param->hasDefaultArg()) 391 break; 392 } 393 394 // C++ [dcl.fct.default]p4: 395 // In a given function declaration, all parameters 396 // subsequent to a parameter with a default argument shall 397 // have default arguments supplied in this or previous 398 // declarations. A default argument shall not be redefined 399 // by a later declaration (not even to the same value). 400 unsigned LastMissingDefaultArg = 0; 401 for (; p < NumParams; ++p) { 402 ParmVarDecl *Param = FD->getParamDecl(p); 403 if (!Param->hasDefaultArg()) { 404 if (Param->isInvalidDecl()) 405 /* We already complained about this parameter. */; 406 else if (Param->getIdentifier()) 407 Diag(Param->getLocation(), 408 diag::err_param_default_argument_missing_name) 409 << Param->getIdentifier(); 410 else 411 Diag(Param->getLocation(), 412 diag::err_param_default_argument_missing); 413 414 LastMissingDefaultArg = p; 415 } 416 } 417 418 if (LastMissingDefaultArg > 0) { 419 // Some default arguments were missing. Clear out all of the 420 // default arguments up to (and including) the last missing 421 // default argument, so that we leave the function parameters 422 // in a semantically valid state. 423 for (p = 0; p <= LastMissingDefaultArg; ++p) { 424 ParmVarDecl *Param = FD->getParamDecl(p); 425 if (Param->hasDefaultArg()) { 426 Param->setDefaultArg(0); 427 } 428 } 429 } 430} 431 432/// isCurrentClassName - Determine whether the identifier II is the 433/// name of the class type currently being defined. In the case of 434/// nested classes, this will only return true if II is the name of 435/// the innermost class. 436bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 437 const CXXScopeSpec *SS) { 438 assert(getLangOptions().CPlusPlus && "No class names in C!"); 439 440 CXXRecordDecl *CurDecl; 441 if (SS && SS->isSet() && !SS->isInvalid()) { 442 DeclContext *DC = computeDeclContext(*SS, true); 443 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 444 } else 445 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 446 447 if (CurDecl && CurDecl->getIdentifier()) 448 return &II == CurDecl->getIdentifier(); 449 else 450 return false; 451} 452 453/// \brief Check the validity of a C++ base class specifier. 454/// 455/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 456/// and returns NULL otherwise. 457CXXBaseSpecifier * 458Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 459 SourceRange SpecifierRange, 460 bool Virtual, AccessSpecifier Access, 461 TypeSourceInfo *TInfo) { 462 QualType BaseType = TInfo->getType(); 463 464 // C++ [class.union]p1: 465 // A union shall not have base classes. 466 if (Class->isUnion()) { 467 Diag(Class->getLocation(), diag::err_base_clause_on_union) 468 << SpecifierRange; 469 return 0; 470 } 471 472 if (BaseType->isDependentType()) 473 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 474 Class->getTagKind() == TTK_Class, 475 Access, TInfo); 476 477 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 478 479 // Base specifiers must be record types. 480 if (!BaseType->isRecordType()) { 481 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 482 return 0; 483 } 484 485 // C++ [class.union]p1: 486 // A union shall not be used as a base class. 487 if (BaseType->isUnionType()) { 488 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 489 return 0; 490 } 491 492 // C++ [class.derived]p2: 493 // The class-name in a base-specifier shall not be an incompletely 494 // defined class. 495 if (RequireCompleteType(BaseLoc, BaseType, 496 PDiag(diag::err_incomplete_base_class) 497 << SpecifierRange)) { 498 Class->setInvalidDecl(); 499 return 0; 500 } 501 502 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 503 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 504 assert(BaseDecl && "Record type has no declaration"); 505 BaseDecl = BaseDecl->getDefinition(); 506 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 507 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 508 assert(CXXBaseDecl && "Base type is not a C++ type"); 509 510 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 511 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 512 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 513 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 514 << BaseType; 515 return 0; 516 } 517 518 if (BaseDecl->isInvalidDecl()) 519 Class->setInvalidDecl(); 520 521 // Create the base specifier. 522 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 523 Class->getTagKind() == TTK_Class, 524 Access, TInfo); 525} 526 527/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 528/// one entry in the base class list of a class specifier, for 529/// example: 530/// class foo : public bar, virtual private baz { 531/// 'public bar' and 'virtual private baz' are each base-specifiers. 532BaseResult 533Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 534 bool Virtual, AccessSpecifier Access, 535 ParsedType basetype, SourceLocation BaseLoc) { 536 if (!classdecl) 537 return true; 538 539 AdjustDeclIfTemplate(classdecl); 540 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 541 if (!Class) 542 return true; 543 544 TypeSourceInfo *TInfo = 0; 545 GetTypeFromParser(basetype, &TInfo); 546 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 547 Virtual, Access, TInfo)) 548 return BaseSpec; 549 550 return true; 551} 552 553/// \brief Performs the actual work of attaching the given base class 554/// specifiers to a C++ class. 555bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 556 unsigned NumBases) { 557 if (NumBases == 0) 558 return false; 559 560 // Used to keep track of which base types we have already seen, so 561 // that we can properly diagnose redundant direct base types. Note 562 // that the key is always the unqualified canonical type of the base 563 // class. 564 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 565 566 // Copy non-redundant base specifiers into permanent storage. 567 unsigned NumGoodBases = 0; 568 bool Invalid = false; 569 for (unsigned idx = 0; idx < NumBases; ++idx) { 570 QualType NewBaseType 571 = Context.getCanonicalType(Bases[idx]->getType()); 572 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 573 if (!Class->hasObjectMember()) { 574 if (const RecordType *FDTTy = 575 NewBaseType.getTypePtr()->getAs<RecordType>()) 576 if (FDTTy->getDecl()->hasObjectMember()) 577 Class->setHasObjectMember(true); 578 } 579 580 if (KnownBaseTypes[NewBaseType]) { 581 // C++ [class.mi]p3: 582 // A class shall not be specified as a direct base class of a 583 // derived class more than once. 584 Diag(Bases[idx]->getSourceRange().getBegin(), 585 diag::err_duplicate_base_class) 586 << KnownBaseTypes[NewBaseType]->getType() 587 << Bases[idx]->getSourceRange(); 588 589 // Delete the duplicate base class specifier; we're going to 590 // overwrite its pointer later. 591 Context.Deallocate(Bases[idx]); 592 593 Invalid = true; 594 } else { 595 // Okay, add this new base class. 596 KnownBaseTypes[NewBaseType] = Bases[idx]; 597 Bases[NumGoodBases++] = Bases[idx]; 598 } 599 } 600 601 // Attach the remaining base class specifiers to the derived class. 602 Class->setBases(Bases, NumGoodBases); 603 604 // Delete the remaining (good) base class specifiers, since their 605 // data has been copied into the CXXRecordDecl. 606 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 607 Context.Deallocate(Bases[idx]); 608 609 return Invalid; 610} 611 612/// ActOnBaseSpecifiers - Attach the given base specifiers to the 613/// class, after checking whether there are any duplicate base 614/// classes. 615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, 616 unsigned NumBases) { 617 if (!ClassDecl || !Bases || !NumBases) 618 return; 619 620 AdjustDeclIfTemplate(ClassDecl); 621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 622 (CXXBaseSpecifier**)(Bases), NumBases); 623} 624 625static CXXRecordDecl *GetClassForType(QualType T) { 626 if (const RecordType *RT = T->getAs<RecordType>()) 627 return cast<CXXRecordDecl>(RT->getDecl()); 628 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 629 return ICT->getDecl(); 630 else 631 return 0; 632} 633 634/// \brief Determine whether the type \p Derived is a C++ class that is 635/// derived from the type \p Base. 636bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 637 if (!getLangOptions().CPlusPlus) 638 return false; 639 640 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 641 if (!DerivedRD) 642 return false; 643 644 CXXRecordDecl *BaseRD = GetClassForType(Base); 645 if (!BaseRD) 646 return false; 647 648 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 649 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 650} 651 652/// \brief Determine whether the type \p Derived is a C++ class that is 653/// derived from the type \p Base. 654bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 655 if (!getLangOptions().CPlusPlus) 656 return false; 657 658 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 659 if (!DerivedRD) 660 return false; 661 662 CXXRecordDecl *BaseRD = GetClassForType(Base); 663 if (!BaseRD) 664 return false; 665 666 return DerivedRD->isDerivedFrom(BaseRD, Paths); 667} 668 669void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 670 CXXCastPath &BasePathArray) { 671 assert(BasePathArray.empty() && "Base path array must be empty!"); 672 assert(Paths.isRecordingPaths() && "Must record paths!"); 673 674 const CXXBasePath &Path = Paths.front(); 675 676 // We first go backward and check if we have a virtual base. 677 // FIXME: It would be better if CXXBasePath had the base specifier for 678 // the nearest virtual base. 679 unsigned Start = 0; 680 for (unsigned I = Path.size(); I != 0; --I) { 681 if (Path[I - 1].Base->isVirtual()) { 682 Start = I - 1; 683 break; 684 } 685 } 686 687 // Now add all bases. 688 for (unsigned I = Start, E = Path.size(); I != E; ++I) 689 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 690} 691 692/// \brief Determine whether the given base path includes a virtual 693/// base class. 694bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 695 for (CXXCastPath::const_iterator B = BasePath.begin(), 696 BEnd = BasePath.end(); 697 B != BEnd; ++B) 698 if ((*B)->isVirtual()) 699 return true; 700 701 return false; 702} 703 704/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 705/// conversion (where Derived and Base are class types) is 706/// well-formed, meaning that the conversion is unambiguous (and 707/// that all of the base classes are accessible). Returns true 708/// and emits a diagnostic if the code is ill-formed, returns false 709/// otherwise. Loc is the location where this routine should point to 710/// if there is an error, and Range is the source range to highlight 711/// if there is an error. 712bool 713Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 714 unsigned InaccessibleBaseID, 715 unsigned AmbigiousBaseConvID, 716 SourceLocation Loc, SourceRange Range, 717 DeclarationName Name, 718 CXXCastPath *BasePath) { 719 // First, determine whether the path from Derived to Base is 720 // ambiguous. This is slightly more expensive than checking whether 721 // the Derived to Base conversion exists, because here we need to 722 // explore multiple paths to determine if there is an ambiguity. 723 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 724 /*DetectVirtual=*/false); 725 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 726 assert(DerivationOkay && 727 "Can only be used with a derived-to-base conversion"); 728 (void)DerivationOkay; 729 730 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 731 if (InaccessibleBaseID) { 732 // Check that the base class can be accessed. 733 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 734 InaccessibleBaseID)) { 735 case AR_inaccessible: 736 return true; 737 case AR_accessible: 738 case AR_dependent: 739 case AR_delayed: 740 break; 741 } 742 } 743 744 // Build a base path if necessary. 745 if (BasePath) 746 BuildBasePathArray(Paths, *BasePath); 747 return false; 748 } 749 750 // We know that the derived-to-base conversion is ambiguous, and 751 // we're going to produce a diagnostic. Perform the derived-to-base 752 // search just one more time to compute all of the possible paths so 753 // that we can print them out. This is more expensive than any of 754 // the previous derived-to-base checks we've done, but at this point 755 // performance isn't as much of an issue. 756 Paths.clear(); 757 Paths.setRecordingPaths(true); 758 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 759 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 760 (void)StillOkay; 761 762 // Build up a textual representation of the ambiguous paths, e.g., 763 // D -> B -> A, that will be used to illustrate the ambiguous 764 // conversions in the diagnostic. We only print one of the paths 765 // to each base class subobject. 766 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 767 768 Diag(Loc, AmbigiousBaseConvID) 769 << Derived << Base << PathDisplayStr << Range << Name; 770 return true; 771} 772 773bool 774Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 775 SourceLocation Loc, SourceRange Range, 776 CXXCastPath *BasePath, 777 bool IgnoreAccess) { 778 return CheckDerivedToBaseConversion(Derived, Base, 779 IgnoreAccess ? 0 780 : diag::err_upcast_to_inaccessible_base, 781 diag::err_ambiguous_derived_to_base_conv, 782 Loc, Range, DeclarationName(), 783 BasePath); 784} 785 786 787/// @brief Builds a string representing ambiguous paths from a 788/// specific derived class to different subobjects of the same base 789/// class. 790/// 791/// This function builds a string that can be used in error messages 792/// to show the different paths that one can take through the 793/// inheritance hierarchy to go from the derived class to different 794/// subobjects of a base class. The result looks something like this: 795/// @code 796/// struct D -> struct B -> struct A 797/// struct D -> struct C -> struct A 798/// @endcode 799std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 800 std::string PathDisplayStr; 801 std::set<unsigned> DisplayedPaths; 802 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 803 Path != Paths.end(); ++Path) { 804 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 805 // We haven't displayed a path to this particular base 806 // class subobject yet. 807 PathDisplayStr += "\n "; 808 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 809 for (CXXBasePath::const_iterator Element = Path->begin(); 810 Element != Path->end(); ++Element) 811 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 812 } 813 } 814 815 return PathDisplayStr; 816} 817 818//===----------------------------------------------------------------------===// 819// C++ class member Handling 820//===----------------------------------------------------------------------===// 821 822/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 823Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 824 SourceLocation ASLoc, 825 SourceLocation ColonLoc) { 826 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 827 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 828 ASLoc, ColonLoc); 829 CurContext->addHiddenDecl(ASDecl); 830 return ASDecl; 831} 832 833/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 834/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 835/// bitfield width if there is one and 'InitExpr' specifies the initializer if 836/// any. 837Decl * 838Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 839 MultiTemplateParamsArg TemplateParameterLists, 840 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 841 bool Deleted) { 842 const DeclSpec &DS = D.getDeclSpec(); 843 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 844 DeclarationName Name = NameInfo.getName(); 845 SourceLocation Loc = NameInfo.getLoc(); 846 847 // For anonymous bitfields, the location should point to the type. 848 if (Loc.isInvalid()) 849 Loc = D.getSourceRange().getBegin(); 850 851 Expr *BitWidth = static_cast<Expr*>(BW); 852 Expr *Init = static_cast<Expr*>(InitExpr); 853 854 assert(isa<CXXRecordDecl>(CurContext)); 855 assert(!DS.isFriendSpecified()); 856 857 bool isFunc = false; 858 if (D.isFunctionDeclarator()) 859 isFunc = true; 860 else if (D.getNumTypeObjects() == 0 && 861 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) { 862 QualType TDType = GetTypeFromParser(DS.getRepAsType()); 863 isFunc = TDType->isFunctionType(); 864 } 865 866 // C++ 9.2p6: A member shall not be declared to have automatic storage 867 // duration (auto, register) or with the extern storage-class-specifier. 868 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 869 // data members and cannot be applied to names declared const or static, 870 // and cannot be applied to reference members. 871 switch (DS.getStorageClassSpec()) { 872 case DeclSpec::SCS_unspecified: 873 case DeclSpec::SCS_typedef: 874 case DeclSpec::SCS_static: 875 // FALL THROUGH. 876 break; 877 case DeclSpec::SCS_mutable: 878 if (isFunc) { 879 if (DS.getStorageClassSpecLoc().isValid()) 880 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 881 else 882 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 883 884 // FIXME: It would be nicer if the keyword was ignored only for this 885 // declarator. Otherwise we could get follow-up errors. 886 D.getMutableDeclSpec().ClearStorageClassSpecs(); 887 } 888 break; 889 default: 890 if (DS.getStorageClassSpecLoc().isValid()) 891 Diag(DS.getStorageClassSpecLoc(), 892 diag::err_storageclass_invalid_for_member); 893 else 894 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 895 D.getMutableDeclSpec().ClearStorageClassSpecs(); 896 } 897 898 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 899 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 900 !isFunc); 901 902 Decl *Member; 903 if (isInstField) { 904 CXXScopeSpec &SS = D.getCXXScopeSpec(); 905 906 907 if (SS.isSet() && !SS.isInvalid()) { 908 // The user provided a superfluous scope specifier inside a class 909 // definition: 910 // 911 // class X { 912 // int X::member; 913 // }; 914 DeclContext *DC = 0; 915 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 916 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 917 << Name << FixItHint::CreateRemoval(SS.getRange()); 918 else 919 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 920 << Name << SS.getRange(); 921 922 SS.clear(); 923 } 924 925 // FIXME: Check for template parameters! 926 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 927 AS); 928 assert(Member && "HandleField never returns null"); 929 } else { 930 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 931 if (!Member) { 932 return 0; 933 } 934 935 // Non-instance-fields can't have a bitfield. 936 if (BitWidth) { 937 if (Member->isInvalidDecl()) { 938 // don't emit another diagnostic. 939 } else if (isa<VarDecl>(Member)) { 940 // C++ 9.6p3: A bit-field shall not be a static member. 941 // "static member 'A' cannot be a bit-field" 942 Diag(Loc, diag::err_static_not_bitfield) 943 << Name << BitWidth->getSourceRange(); 944 } else if (isa<TypedefDecl>(Member)) { 945 // "typedef member 'x' cannot be a bit-field" 946 Diag(Loc, diag::err_typedef_not_bitfield) 947 << Name << BitWidth->getSourceRange(); 948 } else { 949 // A function typedef ("typedef int f(); f a;"). 950 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 951 Diag(Loc, diag::err_not_integral_type_bitfield) 952 << Name << cast<ValueDecl>(Member)->getType() 953 << BitWidth->getSourceRange(); 954 } 955 956 BitWidth = 0; 957 Member->setInvalidDecl(); 958 } 959 960 Member->setAccess(AS); 961 962 // If we have declared a member function template, set the access of the 963 // templated declaration as well. 964 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 965 FunTmpl->getTemplatedDecl()->setAccess(AS); 966 } 967 968 assert((Name || isInstField) && "No identifier for non-field ?"); 969 970 if (Init) 971 AddInitializerToDecl(Member, Init, false); 972 if (Deleted) // FIXME: Source location is not very good. 973 SetDeclDeleted(Member, D.getSourceRange().getBegin()); 974 975 if (isInstField) { 976 FieldCollector->Add(cast<FieldDecl>(Member)); 977 return 0; 978 } 979 return Member; 980} 981 982/// \brief Find the direct and/or virtual base specifiers that 983/// correspond to the given base type, for use in base initialization 984/// within a constructor. 985static bool FindBaseInitializer(Sema &SemaRef, 986 CXXRecordDecl *ClassDecl, 987 QualType BaseType, 988 const CXXBaseSpecifier *&DirectBaseSpec, 989 const CXXBaseSpecifier *&VirtualBaseSpec) { 990 // First, check for a direct base class. 991 DirectBaseSpec = 0; 992 for (CXXRecordDecl::base_class_const_iterator Base 993 = ClassDecl->bases_begin(); 994 Base != ClassDecl->bases_end(); ++Base) { 995 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 996 // We found a direct base of this type. That's what we're 997 // initializing. 998 DirectBaseSpec = &*Base; 999 break; 1000 } 1001 } 1002 1003 // Check for a virtual base class. 1004 // FIXME: We might be able to short-circuit this if we know in advance that 1005 // there are no virtual bases. 1006 VirtualBaseSpec = 0; 1007 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1008 // We haven't found a base yet; search the class hierarchy for a 1009 // virtual base class. 1010 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1011 /*DetectVirtual=*/false); 1012 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1013 BaseType, Paths)) { 1014 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1015 Path != Paths.end(); ++Path) { 1016 if (Path->back().Base->isVirtual()) { 1017 VirtualBaseSpec = Path->back().Base; 1018 break; 1019 } 1020 } 1021 } 1022 } 1023 1024 return DirectBaseSpec || VirtualBaseSpec; 1025} 1026 1027/// ActOnMemInitializer - Handle a C++ member initializer. 1028MemInitResult 1029Sema::ActOnMemInitializer(Decl *ConstructorD, 1030 Scope *S, 1031 CXXScopeSpec &SS, 1032 IdentifierInfo *MemberOrBase, 1033 ParsedType TemplateTypeTy, 1034 SourceLocation IdLoc, 1035 SourceLocation LParenLoc, 1036 ExprTy **Args, unsigned NumArgs, 1037 SourceLocation RParenLoc) { 1038 if (!ConstructorD) 1039 return true; 1040 1041 AdjustDeclIfTemplate(ConstructorD); 1042 1043 CXXConstructorDecl *Constructor 1044 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1045 if (!Constructor) { 1046 // The user wrote a constructor initializer on a function that is 1047 // not a C++ constructor. Ignore the error for now, because we may 1048 // have more member initializers coming; we'll diagnose it just 1049 // once in ActOnMemInitializers. 1050 return true; 1051 } 1052 1053 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1054 1055 // C++ [class.base.init]p2: 1056 // Names in a mem-initializer-id are looked up in the scope of the 1057 // constructor’s class and, if not found in that scope, are looked 1058 // up in the scope containing the constructor’s 1059 // definition. [Note: if the constructor’s class contains a member 1060 // with the same name as a direct or virtual base class of the 1061 // class, a mem-initializer-id naming the member or base class and 1062 // composed of a single identifier refers to the class member. A 1063 // mem-initializer-id for the hidden base class may be specified 1064 // using a qualified name. ] 1065 if (!SS.getScopeRep() && !TemplateTypeTy) { 1066 // Look for a member, first. 1067 FieldDecl *Member = 0; 1068 DeclContext::lookup_result Result 1069 = ClassDecl->lookup(MemberOrBase); 1070 if (Result.first != Result.second) 1071 Member = dyn_cast<FieldDecl>(*Result.first); 1072 1073 // FIXME: Handle members of an anonymous union. 1074 1075 if (Member) 1076 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1077 LParenLoc, RParenLoc); 1078 } 1079 // It didn't name a member, so see if it names a class. 1080 QualType BaseType; 1081 TypeSourceInfo *TInfo = 0; 1082 1083 if (TemplateTypeTy) { 1084 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1085 } else { 1086 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1087 LookupParsedName(R, S, &SS); 1088 1089 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1090 if (!TyD) { 1091 if (R.isAmbiguous()) return true; 1092 1093 // We don't want access-control diagnostics here. 1094 R.suppressDiagnostics(); 1095 1096 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1097 bool NotUnknownSpecialization = false; 1098 DeclContext *DC = computeDeclContext(SS, false); 1099 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1100 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1101 1102 if (!NotUnknownSpecialization) { 1103 // When the scope specifier can refer to a member of an unknown 1104 // specialization, we take it as a type name. 1105 BaseType = CheckTypenameType(ETK_None, 1106 (NestedNameSpecifier *)SS.getScopeRep(), 1107 *MemberOrBase, SourceLocation(), 1108 SS.getRange(), IdLoc); 1109 if (BaseType.isNull()) 1110 return true; 1111 1112 R.clear(); 1113 R.setLookupName(MemberOrBase); 1114 } 1115 } 1116 1117 // If no results were found, try to correct typos. 1118 if (R.empty() && BaseType.isNull() && 1119 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1120 R.isSingleResult()) { 1121 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1122 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1123 // We have found a non-static data member with a similar 1124 // name to what was typed; complain and initialize that 1125 // member. 1126 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1127 << MemberOrBase << true << R.getLookupName() 1128 << FixItHint::CreateReplacement(R.getNameLoc(), 1129 R.getLookupName().getAsString()); 1130 Diag(Member->getLocation(), diag::note_previous_decl) 1131 << Member->getDeclName(); 1132 1133 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1134 LParenLoc, RParenLoc); 1135 } 1136 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1137 const CXXBaseSpecifier *DirectBaseSpec; 1138 const CXXBaseSpecifier *VirtualBaseSpec; 1139 if (FindBaseInitializer(*this, ClassDecl, 1140 Context.getTypeDeclType(Type), 1141 DirectBaseSpec, VirtualBaseSpec)) { 1142 // We have found a direct or virtual base class with a 1143 // similar name to what was typed; complain and initialize 1144 // that base class. 1145 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1146 << MemberOrBase << false << R.getLookupName() 1147 << FixItHint::CreateReplacement(R.getNameLoc(), 1148 R.getLookupName().getAsString()); 1149 1150 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1151 : VirtualBaseSpec; 1152 Diag(BaseSpec->getSourceRange().getBegin(), 1153 diag::note_base_class_specified_here) 1154 << BaseSpec->getType() 1155 << BaseSpec->getSourceRange(); 1156 1157 TyD = Type; 1158 } 1159 } 1160 } 1161 1162 if (!TyD && BaseType.isNull()) { 1163 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1164 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1165 return true; 1166 } 1167 } 1168 1169 if (BaseType.isNull()) { 1170 BaseType = Context.getTypeDeclType(TyD); 1171 if (SS.isSet()) { 1172 NestedNameSpecifier *Qualifier = 1173 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1174 1175 // FIXME: preserve source range information 1176 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1177 } 1178 } 1179 } 1180 1181 if (!TInfo) 1182 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1183 1184 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1185 LParenLoc, RParenLoc, ClassDecl); 1186} 1187 1188/// Checks an initializer expression for use of uninitialized fields, such as 1189/// containing the field that is being initialized. Returns true if there is an 1190/// uninitialized field was used an updates the SourceLocation parameter; false 1191/// otherwise. 1192static bool InitExprContainsUninitializedFields(const Stmt *S, 1193 const FieldDecl *LhsField, 1194 SourceLocation *L) { 1195 if (isa<CallExpr>(S)) { 1196 // Do not descend into function calls or constructors, as the use 1197 // of an uninitialized field may be valid. One would have to inspect 1198 // the contents of the function/ctor to determine if it is safe or not. 1199 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1200 // may be safe, depending on what the function/ctor does. 1201 return false; 1202 } 1203 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1204 const NamedDecl *RhsField = ME->getMemberDecl(); 1205 1206 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1207 // The member expression points to a static data member. 1208 assert(VD->isStaticDataMember() && 1209 "Member points to non-static data member!"); 1210 (void)VD; 1211 return false; 1212 } 1213 1214 if (isa<EnumConstantDecl>(RhsField)) { 1215 // The member expression points to an enum. 1216 return false; 1217 } 1218 1219 if (RhsField == LhsField) { 1220 // Initializing a field with itself. Throw a warning. 1221 // But wait; there are exceptions! 1222 // Exception #1: The field may not belong to this record. 1223 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1224 const Expr *base = ME->getBase(); 1225 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1226 // Even though the field matches, it does not belong to this record. 1227 return false; 1228 } 1229 // None of the exceptions triggered; return true to indicate an 1230 // uninitialized field was used. 1231 *L = ME->getMemberLoc(); 1232 return true; 1233 } 1234 } else if (isa<SizeOfAlignOfExpr>(S)) { 1235 // sizeof/alignof doesn't reference contents, do not warn. 1236 return false; 1237 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 1238 // address-of doesn't reference contents (the pointer may be dereferenced 1239 // in the same expression but it would be rare; and weird). 1240 if (UOE->getOpcode() == UO_AddrOf) 1241 return false; 1242 } 1243 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end(); 1244 it != e; ++it) { 1245 if (!*it) { 1246 // An expression such as 'member(arg ?: "")' may trigger this. 1247 continue; 1248 } 1249 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 1250 return true; 1251 } 1252 return false; 1253} 1254 1255MemInitResult 1256Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 1257 unsigned NumArgs, SourceLocation IdLoc, 1258 SourceLocation LParenLoc, 1259 SourceLocation RParenLoc) { 1260 if (Member->isInvalidDecl()) 1261 return true; 1262 1263 // Diagnose value-uses of fields to initialize themselves, e.g. 1264 // foo(foo) 1265 // where foo is not also a parameter to the constructor. 1266 // TODO: implement -Wuninitialized and fold this into that framework. 1267 for (unsigned i = 0; i < NumArgs; ++i) { 1268 SourceLocation L; 1269 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1270 // FIXME: Return true in the case when other fields are used before being 1271 // uninitialized. For example, let this field be the i'th field. When 1272 // initializing the i'th field, throw a warning if any of the >= i'th 1273 // fields are used, as they are not yet initialized. 1274 // Right now we are only handling the case where the i'th field uses 1275 // itself in its initializer. 1276 Diag(L, diag::warn_field_is_uninit); 1277 } 1278 } 1279 1280 bool HasDependentArg = false; 1281 for (unsigned i = 0; i < NumArgs; i++) 1282 HasDependentArg |= Args[i]->isTypeDependent(); 1283 1284 if (Member->getType()->isDependentType() || HasDependentArg) { 1285 // Can't check initialization for a member of dependent type or when 1286 // any of the arguments are type-dependent expressions. 1287 Expr *Init 1288 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1289 RParenLoc); 1290 1291 // Erase any temporaries within this evaluation context; we're not 1292 // going to track them in the AST, since we'll be rebuilding the 1293 // ASTs during template instantiation. 1294 ExprTemporaries.erase( 1295 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1296 ExprTemporaries.end()); 1297 1298 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1299 LParenLoc, 1300 Init, 1301 RParenLoc); 1302 1303 } 1304 1305 // Initialize the member. 1306 InitializedEntity MemberEntity = 1307 InitializedEntity::InitializeMember(Member, 0); 1308 InitializationKind Kind = 1309 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1310 1311 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1312 1313 ExprResult MemberInit = 1314 InitSeq.Perform(*this, MemberEntity, Kind, 1315 MultiExprArg(*this, Args, NumArgs), 0); 1316 if (MemberInit.isInvalid()) 1317 return true; 1318 1319 CheckImplicitConversions(MemberInit.get(), LParenLoc); 1320 1321 // C++0x [class.base.init]p7: 1322 // The initialization of each base and member constitutes a 1323 // full-expression. 1324 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get()); 1325 if (MemberInit.isInvalid()) 1326 return true; 1327 1328 // If we are in a dependent context, template instantiation will 1329 // perform this type-checking again. Just save the arguments that we 1330 // received in a ParenListExpr. 1331 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1332 // of the information that we have about the member 1333 // initializer. However, deconstructing the ASTs is a dicey process, 1334 // and this approach is far more likely to get the corner cases right. 1335 if (CurContext->isDependentContext()) { 1336 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1337 RParenLoc); 1338 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1339 LParenLoc, 1340 Init, 1341 RParenLoc); 1342 } 1343 1344 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1345 LParenLoc, 1346 MemberInit.get(), 1347 RParenLoc); 1348} 1349 1350MemInitResult 1351Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1352 Expr **Args, unsigned NumArgs, 1353 SourceLocation LParenLoc, SourceLocation RParenLoc, 1354 CXXRecordDecl *ClassDecl) { 1355 bool HasDependentArg = false; 1356 for (unsigned i = 0; i < NumArgs; i++) 1357 HasDependentArg |= Args[i]->isTypeDependent(); 1358 1359 SourceLocation BaseLoc 1360 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1361 1362 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 1363 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1364 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1365 1366 // C++ [class.base.init]p2: 1367 // [...] Unless the mem-initializer-id names a nonstatic data 1368 // member of the constructor’s class or a direct or virtual base 1369 // of that class, the mem-initializer is ill-formed. A 1370 // mem-initializer-list can initialize a base class using any 1371 // name that denotes that base class type. 1372 bool Dependent = BaseType->isDependentType() || HasDependentArg; 1373 1374 // Check for direct and virtual base classes. 1375 const CXXBaseSpecifier *DirectBaseSpec = 0; 1376 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1377 if (!Dependent) { 1378 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1379 VirtualBaseSpec); 1380 1381 // C++ [base.class.init]p2: 1382 // Unless the mem-initializer-id names a nonstatic data member of the 1383 // constructor's class or a direct or virtual base of that class, the 1384 // mem-initializer is ill-formed. 1385 if (!DirectBaseSpec && !VirtualBaseSpec) { 1386 // If the class has any dependent bases, then it's possible that 1387 // one of those types will resolve to the same type as 1388 // BaseType. Therefore, just treat this as a dependent base 1389 // class initialization. FIXME: Should we try to check the 1390 // initialization anyway? It seems odd. 1391 if (ClassDecl->hasAnyDependentBases()) 1392 Dependent = true; 1393 else 1394 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1395 << BaseType << Context.getTypeDeclType(ClassDecl) 1396 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1397 } 1398 } 1399 1400 if (Dependent) { 1401 // Can't check initialization for a base of dependent type or when 1402 // any of the arguments are type-dependent expressions. 1403 ExprResult BaseInit 1404 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1405 RParenLoc)); 1406 1407 // Erase any temporaries within this evaluation context; we're not 1408 // going to track them in the AST, since we'll be rebuilding the 1409 // ASTs during template instantiation. 1410 ExprTemporaries.erase( 1411 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1412 ExprTemporaries.end()); 1413 1414 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1415 /*IsVirtual=*/false, 1416 LParenLoc, 1417 BaseInit.takeAs<Expr>(), 1418 RParenLoc); 1419 } 1420 1421 // C++ [base.class.init]p2: 1422 // If a mem-initializer-id is ambiguous because it designates both 1423 // a direct non-virtual base class and an inherited virtual base 1424 // class, the mem-initializer is ill-formed. 1425 if (DirectBaseSpec && VirtualBaseSpec) 1426 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1427 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1428 1429 CXXBaseSpecifier *BaseSpec 1430 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1431 if (!BaseSpec) 1432 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1433 1434 // Initialize the base. 1435 InitializedEntity BaseEntity = 1436 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1437 InitializationKind Kind = 1438 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1439 1440 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1441 1442 ExprResult BaseInit = 1443 InitSeq.Perform(*this, BaseEntity, Kind, 1444 MultiExprArg(*this, Args, NumArgs), 0); 1445 if (BaseInit.isInvalid()) 1446 return true; 1447 1448 CheckImplicitConversions(BaseInit.get(), LParenLoc); 1449 1450 // C++0x [class.base.init]p7: 1451 // The initialization of each base and member constitutes a 1452 // full-expression. 1453 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get()); 1454 if (BaseInit.isInvalid()) 1455 return true; 1456 1457 // If we are in a dependent context, template instantiation will 1458 // perform this type-checking again. Just save the arguments that we 1459 // received in a ParenListExpr. 1460 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1461 // of the information that we have about the base 1462 // initializer. However, deconstructing the ASTs is a dicey process, 1463 // and this approach is far more likely to get the corner cases right. 1464 if (CurContext->isDependentContext()) { 1465 ExprResult Init 1466 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1467 RParenLoc)); 1468 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1469 BaseSpec->isVirtual(), 1470 LParenLoc, 1471 Init.takeAs<Expr>(), 1472 RParenLoc); 1473 } 1474 1475 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1476 BaseSpec->isVirtual(), 1477 LParenLoc, 1478 BaseInit.takeAs<Expr>(), 1479 RParenLoc); 1480} 1481 1482/// ImplicitInitializerKind - How an implicit base or member initializer should 1483/// initialize its base or member. 1484enum ImplicitInitializerKind { 1485 IIK_Default, 1486 IIK_Copy, 1487 IIK_Move 1488}; 1489 1490static bool 1491BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1492 ImplicitInitializerKind ImplicitInitKind, 1493 CXXBaseSpecifier *BaseSpec, 1494 bool IsInheritedVirtualBase, 1495 CXXBaseOrMemberInitializer *&CXXBaseInit) { 1496 InitializedEntity InitEntity 1497 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1498 IsInheritedVirtualBase); 1499 1500 ExprResult BaseInit; 1501 1502 switch (ImplicitInitKind) { 1503 case IIK_Default: { 1504 InitializationKind InitKind 1505 = InitializationKind::CreateDefault(Constructor->getLocation()); 1506 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1507 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1508 MultiExprArg(SemaRef, 0, 0)); 1509 break; 1510 } 1511 1512 case IIK_Copy: { 1513 ParmVarDecl *Param = Constructor->getParamDecl(0); 1514 QualType ParamType = Param->getType().getNonReferenceType(); 1515 1516 Expr *CopyCtorArg = 1517 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1518 Constructor->getLocation(), ParamType, 1519 VK_LValue, 0); 1520 1521 // Cast to the base class to avoid ambiguities. 1522 QualType ArgTy = 1523 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1524 ParamType.getQualifiers()); 1525 1526 CXXCastPath BasePath; 1527 BasePath.push_back(BaseSpec); 1528 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1529 CK_UncheckedDerivedToBase, 1530 VK_LValue, &BasePath); 1531 1532 InitializationKind InitKind 1533 = InitializationKind::CreateDirect(Constructor->getLocation(), 1534 SourceLocation(), SourceLocation()); 1535 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1536 &CopyCtorArg, 1); 1537 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1538 MultiExprArg(&CopyCtorArg, 1)); 1539 break; 1540 } 1541 1542 case IIK_Move: 1543 assert(false && "Unhandled initializer kind!"); 1544 } 1545 1546 if (BaseInit.isInvalid()) 1547 return true; 1548 1549 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get()); 1550 if (BaseInit.isInvalid()) 1551 return true; 1552 1553 CXXBaseInit = 1554 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1555 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1556 SourceLocation()), 1557 BaseSpec->isVirtual(), 1558 SourceLocation(), 1559 BaseInit.takeAs<Expr>(), 1560 SourceLocation()); 1561 1562 return false; 1563} 1564 1565static bool 1566BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1567 ImplicitInitializerKind ImplicitInitKind, 1568 FieldDecl *Field, 1569 CXXBaseOrMemberInitializer *&CXXMemberInit) { 1570 if (Field->isInvalidDecl()) 1571 return true; 1572 1573 SourceLocation Loc = Constructor->getLocation(); 1574 1575 if (ImplicitInitKind == IIK_Copy) { 1576 ParmVarDecl *Param = Constructor->getParamDecl(0); 1577 QualType ParamType = Param->getType().getNonReferenceType(); 1578 1579 Expr *MemberExprBase = 1580 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1581 Loc, ParamType, VK_LValue, 0); 1582 1583 // Build a reference to this field within the parameter. 1584 CXXScopeSpec SS; 1585 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 1586 Sema::LookupMemberName); 1587 MemberLookup.addDecl(Field, AS_public); 1588 MemberLookup.resolveKind(); 1589 ExprResult CopyCtorArg 1590 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 1591 ParamType, Loc, 1592 /*IsArrow=*/false, 1593 SS, 1594 /*FirstQualifierInScope=*/0, 1595 MemberLookup, 1596 /*TemplateArgs=*/0); 1597 if (CopyCtorArg.isInvalid()) 1598 return true; 1599 1600 // When the field we are copying is an array, create index variables for 1601 // each dimension of the array. We use these index variables to subscript 1602 // the source array, and other clients (e.g., CodeGen) will perform the 1603 // necessary iteration with these index variables. 1604 llvm::SmallVector<VarDecl *, 4> IndexVariables; 1605 QualType BaseType = Field->getType(); 1606 QualType SizeType = SemaRef.Context.getSizeType(); 1607 while (const ConstantArrayType *Array 1608 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 1609 // Create the iteration variable for this array index. 1610 IdentifierInfo *IterationVarName = 0; 1611 { 1612 llvm::SmallString<8> Str; 1613 llvm::raw_svector_ostream OS(Str); 1614 OS << "__i" << IndexVariables.size(); 1615 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 1616 } 1617 VarDecl *IterationVar 1618 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, 1619 IterationVarName, SizeType, 1620 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 1621 SC_None, SC_None); 1622 IndexVariables.push_back(IterationVar); 1623 1624 // Create a reference to the iteration variable. 1625 ExprResult IterationVarRef 1626 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 1627 assert(!IterationVarRef.isInvalid() && 1628 "Reference to invented variable cannot fail!"); 1629 1630 // Subscript the array with this iteration variable. 1631 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(), 1632 Loc, 1633 IterationVarRef.take(), 1634 Loc); 1635 if (CopyCtorArg.isInvalid()) 1636 return true; 1637 1638 BaseType = Array->getElementType(); 1639 } 1640 1641 // Construct the entity that we will be initializing. For an array, this 1642 // will be first element in the array, which may require several levels 1643 // of array-subscript entities. 1644 llvm::SmallVector<InitializedEntity, 4> Entities; 1645 Entities.reserve(1 + IndexVariables.size()); 1646 Entities.push_back(InitializedEntity::InitializeMember(Field)); 1647 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 1648 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 1649 0, 1650 Entities.back())); 1651 1652 // Direct-initialize to use the copy constructor. 1653 InitializationKind InitKind = 1654 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 1655 1656 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 1657 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 1658 &CopyCtorArgE, 1); 1659 1660 ExprResult MemberInit 1661 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 1662 MultiExprArg(&CopyCtorArgE, 1)); 1663 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get()); 1664 if (MemberInit.isInvalid()) 1665 return true; 1666 1667 CXXMemberInit 1668 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc, 1669 MemberInit.takeAs<Expr>(), Loc, 1670 IndexVariables.data(), 1671 IndexVariables.size()); 1672 return false; 1673 } 1674 1675 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 1676 1677 QualType FieldBaseElementType = 1678 SemaRef.Context.getBaseElementType(Field->getType()); 1679 1680 if (FieldBaseElementType->isRecordType()) { 1681 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1682 InitializationKind InitKind = 1683 InitializationKind::CreateDefault(Loc); 1684 1685 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1686 ExprResult MemberInit = 1687 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 1688 if (MemberInit.isInvalid()) 1689 return true; 1690 1691 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get()); 1692 if (MemberInit.isInvalid()) 1693 return true; 1694 1695 CXXMemberInit = 1696 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1697 Field, Loc, Loc, 1698 MemberInit.get(), 1699 Loc); 1700 return false; 1701 } 1702 1703 if (FieldBaseElementType->isReferenceType()) { 1704 SemaRef.Diag(Constructor->getLocation(), 1705 diag::err_uninitialized_member_in_ctor) 1706 << (int)Constructor->isImplicit() 1707 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1708 << 0 << Field->getDeclName(); 1709 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1710 return true; 1711 } 1712 1713 if (FieldBaseElementType.isConstQualified()) { 1714 SemaRef.Diag(Constructor->getLocation(), 1715 diag::err_uninitialized_member_in_ctor) 1716 << (int)Constructor->isImplicit() 1717 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1718 << 1 << Field->getDeclName(); 1719 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1720 return true; 1721 } 1722 1723 // Nothing to initialize. 1724 CXXMemberInit = 0; 1725 return false; 1726} 1727 1728namespace { 1729struct BaseAndFieldInfo { 1730 Sema &S; 1731 CXXConstructorDecl *Ctor; 1732 bool AnyErrorsInInits; 1733 ImplicitInitializerKind IIK; 1734 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1735 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit; 1736 1737 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 1738 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 1739 // FIXME: Handle implicit move constructors. 1740 if (Ctor->isImplicit() && Ctor->isCopyConstructor()) 1741 IIK = IIK_Copy; 1742 else 1743 IIK = IIK_Default; 1744 } 1745}; 1746} 1747 1748static void RecordFieldInitializer(BaseAndFieldInfo &Info, 1749 FieldDecl *Top, FieldDecl *Field, 1750 CXXBaseOrMemberInitializer *Init) { 1751 // If the member doesn't need to be initialized, Init will still be null. 1752 if (!Init) 1753 return; 1754 1755 Info.AllToInit.push_back(Init); 1756 if (Field != Top) { 1757 Init->setMember(Top); 1758 Init->setAnonUnionMember(Field); 1759 } 1760} 1761 1762static bool CollectFieldInitializer(BaseAndFieldInfo &Info, 1763 FieldDecl *Top, FieldDecl *Field) { 1764 1765 // Overwhelmingly common case: we have a direct initializer for this field. 1766 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) { 1767 RecordFieldInitializer(Info, Top, Field, Init); 1768 return false; 1769 } 1770 1771 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) { 1772 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>(); 1773 assert(FieldClassType && "anonymous struct/union without record type"); 1774 CXXRecordDecl *FieldClassDecl 1775 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1776 1777 // Even though union members never have non-trivial default 1778 // constructions in C++03, we still build member initializers for aggregate 1779 // record types which can be union members, and C++0x allows non-trivial 1780 // default constructors for union members, so we ensure that only one 1781 // member is initialized for these. 1782 if (FieldClassDecl->isUnion()) { 1783 // First check for an explicit initializer for one field. 1784 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1785 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1786 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) { 1787 RecordFieldInitializer(Info, Top, *FA, Init); 1788 1789 // Once we've initialized a field of an anonymous union, the union 1790 // field in the class is also initialized, so exit immediately. 1791 return false; 1792 } else if ((*FA)->isAnonymousStructOrUnion()) { 1793 if (CollectFieldInitializer(Info, Top, *FA)) 1794 return true; 1795 } 1796 } 1797 1798 // Fallthrough and construct a default initializer for the union as 1799 // a whole, which can call its default constructor if such a thing exists 1800 // (C++0x perhaps). FIXME: It's not clear that this is the correct 1801 // behavior going forward with C++0x, when anonymous unions there are 1802 // finalized, we should revisit this. 1803 } else { 1804 // For structs, we simply descend through to initialize all members where 1805 // necessary. 1806 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1807 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1808 if (CollectFieldInitializer(Info, Top, *FA)) 1809 return true; 1810 } 1811 } 1812 } 1813 1814 // Don't try to build an implicit initializer if there were semantic 1815 // errors in any of the initializers (and therefore we might be 1816 // missing some that the user actually wrote). 1817 if (Info.AnyErrorsInInits) 1818 return false; 1819 1820 CXXBaseOrMemberInitializer *Init = 0; 1821 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init)) 1822 return true; 1823 1824 RecordFieldInitializer(Info, Top, Field, Init); 1825 return false; 1826} 1827 1828bool 1829Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1830 CXXBaseOrMemberInitializer **Initializers, 1831 unsigned NumInitializers, 1832 bool AnyErrors) { 1833 if (Constructor->getDeclContext()->isDependentContext()) { 1834 // Just store the initializers as written, they will be checked during 1835 // instantiation. 1836 if (NumInitializers > 0) { 1837 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1838 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1839 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1840 memcpy(baseOrMemberInitializers, Initializers, 1841 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1842 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1843 } 1844 1845 return false; 1846 } 1847 1848 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 1849 1850 // We need to build the initializer AST according to order of construction 1851 // and not what user specified in the Initializers list. 1852 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 1853 if (!ClassDecl) 1854 return true; 1855 1856 bool HadError = false; 1857 1858 for (unsigned i = 0; i < NumInitializers; i++) { 1859 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1860 1861 if (Member->isBaseInitializer()) 1862 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1863 else 1864 Info.AllBaseFields[Member->getMember()] = Member; 1865 } 1866 1867 // Keep track of the direct virtual bases. 1868 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 1869 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 1870 E = ClassDecl->bases_end(); I != E; ++I) { 1871 if (I->isVirtual()) 1872 DirectVBases.insert(I); 1873 } 1874 1875 // Push virtual bases before others. 1876 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1877 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1878 1879 if (CXXBaseOrMemberInitializer *Value 1880 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1881 Info.AllToInit.push_back(Value); 1882 } else if (!AnyErrors) { 1883 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 1884 CXXBaseOrMemberInitializer *CXXBaseInit; 1885 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 1886 VBase, IsInheritedVirtualBase, 1887 CXXBaseInit)) { 1888 HadError = true; 1889 continue; 1890 } 1891 1892 Info.AllToInit.push_back(CXXBaseInit); 1893 } 1894 } 1895 1896 // Non-virtual bases. 1897 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1898 E = ClassDecl->bases_end(); Base != E; ++Base) { 1899 // Virtuals are in the virtual base list and already constructed. 1900 if (Base->isVirtual()) 1901 continue; 1902 1903 if (CXXBaseOrMemberInitializer *Value 1904 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1905 Info.AllToInit.push_back(Value); 1906 } else if (!AnyErrors) { 1907 CXXBaseOrMemberInitializer *CXXBaseInit; 1908 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 1909 Base, /*IsInheritedVirtualBase=*/false, 1910 CXXBaseInit)) { 1911 HadError = true; 1912 continue; 1913 } 1914 1915 Info.AllToInit.push_back(CXXBaseInit); 1916 } 1917 } 1918 1919 // Fields. 1920 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1921 E = ClassDecl->field_end(); Field != E; ++Field) { 1922 if ((*Field)->getType()->isIncompleteArrayType()) { 1923 assert(ClassDecl->hasFlexibleArrayMember() && 1924 "Incomplete array type is not valid"); 1925 continue; 1926 } 1927 if (CollectFieldInitializer(Info, *Field, *Field)) 1928 HadError = true; 1929 } 1930 1931 NumInitializers = Info.AllToInit.size(); 1932 if (NumInitializers > 0) { 1933 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1934 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1935 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1936 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 1937 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1938 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1939 1940 // Constructors implicitly reference the base and member 1941 // destructors. 1942 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 1943 Constructor->getParent()); 1944 } 1945 1946 return HadError; 1947} 1948 1949static void *GetKeyForTopLevelField(FieldDecl *Field) { 1950 // For anonymous unions, use the class declaration as the key. 1951 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1952 if (RT->getDecl()->isAnonymousStructOrUnion()) 1953 return static_cast<void *>(RT->getDecl()); 1954 } 1955 return static_cast<void *>(Field); 1956} 1957 1958static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 1959 return Context.getCanonicalType(BaseType).getTypePtr(); 1960} 1961 1962static void *GetKeyForMember(ASTContext &Context, 1963 CXXBaseOrMemberInitializer *Member, 1964 bool MemberMaybeAnon = false) { 1965 if (!Member->isMemberInitializer()) 1966 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 1967 1968 // For fields injected into the class via declaration of an anonymous union, 1969 // use its anonymous union class declaration as the unique key. 1970 FieldDecl *Field = Member->getMember(); 1971 1972 // After SetBaseOrMemberInitializers call, Field is the anonymous union 1973 // data member of the class. Data member used in the initializer list is 1974 // in AnonUnionMember field. 1975 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1976 Field = Member->getAnonUnionMember(); 1977 1978 // If the field is a member of an anonymous struct or union, our key 1979 // is the anonymous record decl that's a direct child of the class. 1980 RecordDecl *RD = Field->getParent(); 1981 if (RD->isAnonymousStructOrUnion()) { 1982 while (true) { 1983 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 1984 if (Parent->isAnonymousStructOrUnion()) 1985 RD = Parent; 1986 else 1987 break; 1988 } 1989 1990 return static_cast<void *>(RD); 1991 } 1992 1993 return static_cast<void *>(Field); 1994} 1995 1996static void 1997DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 1998 const CXXConstructorDecl *Constructor, 1999 CXXBaseOrMemberInitializer **Inits, 2000 unsigned NumInits) { 2001 if (Constructor->getDeclContext()->isDependentContext()) 2002 return; 2003 2004 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order) 2005 == Diagnostic::Ignored) 2006 return; 2007 2008 // Build the list of bases and members in the order that they'll 2009 // actually be initialized. The explicit initializers should be in 2010 // this same order but may be missing things. 2011 llvm::SmallVector<const void*, 32> IdealInitKeys; 2012 2013 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2014 2015 // 1. Virtual bases. 2016 for (CXXRecordDecl::base_class_const_iterator VBase = 2017 ClassDecl->vbases_begin(), 2018 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2019 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2020 2021 // 2. Non-virtual bases. 2022 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2023 E = ClassDecl->bases_end(); Base != E; ++Base) { 2024 if (Base->isVirtual()) 2025 continue; 2026 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2027 } 2028 2029 // 3. Direct fields. 2030 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2031 E = ClassDecl->field_end(); Field != E; ++Field) 2032 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2033 2034 unsigned NumIdealInits = IdealInitKeys.size(); 2035 unsigned IdealIndex = 0; 2036 2037 CXXBaseOrMemberInitializer *PrevInit = 0; 2038 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2039 CXXBaseOrMemberInitializer *Init = Inits[InitIndex]; 2040 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true); 2041 2042 // Scan forward to try to find this initializer in the idealized 2043 // initializers list. 2044 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2045 if (InitKey == IdealInitKeys[IdealIndex]) 2046 break; 2047 2048 // If we didn't find this initializer, it must be because we 2049 // scanned past it on a previous iteration. That can only 2050 // happen if we're out of order; emit a warning. 2051 if (IdealIndex == NumIdealInits && PrevInit) { 2052 Sema::SemaDiagnosticBuilder D = 2053 SemaRef.Diag(PrevInit->getSourceLocation(), 2054 diag::warn_initializer_out_of_order); 2055 2056 if (PrevInit->isMemberInitializer()) 2057 D << 0 << PrevInit->getMember()->getDeclName(); 2058 else 2059 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2060 2061 if (Init->isMemberInitializer()) 2062 D << 0 << Init->getMember()->getDeclName(); 2063 else 2064 D << 1 << Init->getBaseClassInfo()->getType(); 2065 2066 // Move back to the initializer's location in the ideal list. 2067 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2068 if (InitKey == IdealInitKeys[IdealIndex]) 2069 break; 2070 2071 assert(IdealIndex != NumIdealInits && 2072 "initializer not found in initializer list"); 2073 } 2074 2075 PrevInit = Init; 2076 } 2077} 2078 2079namespace { 2080bool CheckRedundantInit(Sema &S, 2081 CXXBaseOrMemberInitializer *Init, 2082 CXXBaseOrMemberInitializer *&PrevInit) { 2083 if (!PrevInit) { 2084 PrevInit = Init; 2085 return false; 2086 } 2087 2088 if (FieldDecl *Field = Init->getMember()) 2089 S.Diag(Init->getSourceLocation(), 2090 diag::err_multiple_mem_initialization) 2091 << Field->getDeclName() 2092 << Init->getSourceRange(); 2093 else { 2094 Type *BaseClass = Init->getBaseClass(); 2095 assert(BaseClass && "neither field nor base"); 2096 S.Diag(Init->getSourceLocation(), 2097 diag::err_multiple_base_initialization) 2098 << QualType(BaseClass, 0) 2099 << Init->getSourceRange(); 2100 } 2101 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2102 << 0 << PrevInit->getSourceRange(); 2103 2104 return true; 2105} 2106 2107typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry; 2108typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2109 2110bool CheckRedundantUnionInit(Sema &S, 2111 CXXBaseOrMemberInitializer *Init, 2112 RedundantUnionMap &Unions) { 2113 FieldDecl *Field = Init->getMember(); 2114 RecordDecl *Parent = Field->getParent(); 2115 if (!Parent->isAnonymousStructOrUnion()) 2116 return false; 2117 2118 NamedDecl *Child = Field; 2119 do { 2120 if (Parent->isUnion()) { 2121 UnionEntry &En = Unions[Parent]; 2122 if (En.first && En.first != Child) { 2123 S.Diag(Init->getSourceLocation(), 2124 diag::err_multiple_mem_union_initialization) 2125 << Field->getDeclName() 2126 << Init->getSourceRange(); 2127 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2128 << 0 << En.second->getSourceRange(); 2129 return true; 2130 } else if (!En.first) { 2131 En.first = Child; 2132 En.second = Init; 2133 } 2134 } 2135 2136 Child = Parent; 2137 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2138 } while (Parent->isAnonymousStructOrUnion()); 2139 2140 return false; 2141} 2142} 2143 2144/// ActOnMemInitializers - Handle the member initializers for a constructor. 2145void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 2146 SourceLocation ColonLoc, 2147 MemInitTy **meminits, unsigned NumMemInits, 2148 bool AnyErrors) { 2149 if (!ConstructorDecl) 2150 return; 2151 2152 AdjustDeclIfTemplate(ConstructorDecl); 2153 2154 CXXConstructorDecl *Constructor 2155 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 2156 2157 if (!Constructor) { 2158 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2159 return; 2160 } 2161 2162 CXXBaseOrMemberInitializer **MemInits = 2163 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits); 2164 2165 // Mapping for the duplicate initializers check. 2166 // For member initializers, this is keyed with a FieldDecl*. 2167 // For base initializers, this is keyed with a Type*. 2168 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members; 2169 2170 // Mapping for the inconsistent anonymous-union initializers check. 2171 RedundantUnionMap MemberUnions; 2172 2173 bool HadError = false; 2174 for (unsigned i = 0; i < NumMemInits; i++) { 2175 CXXBaseOrMemberInitializer *Init = MemInits[i]; 2176 2177 // Set the source order index. 2178 Init->setSourceOrder(i); 2179 2180 if (Init->isMemberInitializer()) { 2181 FieldDecl *Field = Init->getMember(); 2182 if (CheckRedundantInit(*this, Init, Members[Field]) || 2183 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2184 HadError = true; 2185 } else { 2186 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2187 if (CheckRedundantInit(*this, Init, Members[Key])) 2188 HadError = true; 2189 } 2190 } 2191 2192 if (HadError) 2193 return; 2194 2195 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2196 2197 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2198} 2199 2200void 2201Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2202 CXXRecordDecl *ClassDecl) { 2203 // Ignore dependent contexts. 2204 if (ClassDecl->isDependentContext()) 2205 return; 2206 2207 // FIXME: all the access-control diagnostics are positioned on the 2208 // field/base declaration. That's probably good; that said, the 2209 // user might reasonably want to know why the destructor is being 2210 // emitted, and we currently don't say. 2211 2212 // Non-static data members. 2213 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2214 E = ClassDecl->field_end(); I != E; ++I) { 2215 FieldDecl *Field = *I; 2216 if (Field->isInvalidDecl()) 2217 continue; 2218 QualType FieldType = Context.getBaseElementType(Field->getType()); 2219 2220 const RecordType* RT = FieldType->getAs<RecordType>(); 2221 if (!RT) 2222 continue; 2223 2224 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2225 if (FieldClassDecl->hasTrivialDestructor()) 2226 continue; 2227 2228 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2229 CheckDestructorAccess(Field->getLocation(), Dtor, 2230 PDiag(diag::err_access_dtor_field) 2231 << Field->getDeclName() 2232 << FieldType); 2233 2234 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2235 } 2236 2237 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2238 2239 // Bases. 2240 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2241 E = ClassDecl->bases_end(); Base != E; ++Base) { 2242 // Bases are always records in a well-formed non-dependent class. 2243 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2244 2245 // Remember direct virtual bases. 2246 if (Base->isVirtual()) 2247 DirectVirtualBases.insert(RT); 2248 2249 // Ignore trivial destructors. 2250 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2251 if (BaseClassDecl->hasTrivialDestructor()) 2252 continue; 2253 2254 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2255 2256 // FIXME: caret should be on the start of the class name 2257 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2258 PDiag(diag::err_access_dtor_base) 2259 << Base->getType() 2260 << Base->getSourceRange()); 2261 2262 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2263 } 2264 2265 // Virtual bases. 2266 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2267 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2268 2269 // Bases are always records in a well-formed non-dependent class. 2270 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2271 2272 // Ignore direct virtual bases. 2273 if (DirectVirtualBases.count(RT)) 2274 continue; 2275 2276 // Ignore trivial destructors. 2277 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2278 if (BaseClassDecl->hasTrivialDestructor()) 2279 continue; 2280 2281 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2282 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2283 PDiag(diag::err_access_dtor_vbase) 2284 << VBase->getType()); 2285 2286 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2287 } 2288} 2289 2290void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2291 if (!CDtorDecl) 2292 return; 2293 2294 if (CXXConstructorDecl *Constructor 2295 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2296 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2297} 2298 2299bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2300 unsigned DiagID, AbstractDiagSelID SelID) { 2301 if (SelID == -1) 2302 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2303 else 2304 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2305} 2306 2307bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2308 const PartialDiagnostic &PD) { 2309 if (!getLangOptions().CPlusPlus) 2310 return false; 2311 2312 if (const ArrayType *AT = Context.getAsArrayType(T)) 2313 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2314 2315 if (const PointerType *PT = T->getAs<PointerType>()) { 2316 // Find the innermost pointer type. 2317 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2318 PT = T; 2319 2320 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2321 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2322 } 2323 2324 const RecordType *RT = T->getAs<RecordType>(); 2325 if (!RT) 2326 return false; 2327 2328 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2329 2330 // We can't answer whether something is abstract until it has a 2331 // definition. If it's currently being defined, we'll walk back 2332 // over all the declarations when we have a full definition. 2333 const CXXRecordDecl *Def = RD->getDefinition(); 2334 if (!Def || Def->isBeingDefined()) 2335 return false; 2336 2337 if (!RD->isAbstract()) 2338 return false; 2339 2340 Diag(Loc, PD) << RD->getDeclName(); 2341 DiagnoseAbstractType(RD); 2342 2343 return true; 2344} 2345 2346void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2347 // Check if we've already emitted the list of pure virtual functions 2348 // for this class. 2349 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2350 return; 2351 2352 CXXFinalOverriderMap FinalOverriders; 2353 RD->getFinalOverriders(FinalOverriders); 2354 2355 // Keep a set of seen pure methods so we won't diagnose the same method 2356 // more than once. 2357 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2358 2359 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2360 MEnd = FinalOverriders.end(); 2361 M != MEnd; 2362 ++M) { 2363 for (OverridingMethods::iterator SO = M->second.begin(), 2364 SOEnd = M->second.end(); 2365 SO != SOEnd; ++SO) { 2366 // C++ [class.abstract]p4: 2367 // A class is abstract if it contains or inherits at least one 2368 // pure virtual function for which the final overrider is pure 2369 // virtual. 2370 2371 // 2372 if (SO->second.size() != 1) 2373 continue; 2374 2375 if (!SO->second.front().Method->isPure()) 2376 continue; 2377 2378 if (!SeenPureMethods.insert(SO->second.front().Method)) 2379 continue; 2380 2381 Diag(SO->second.front().Method->getLocation(), 2382 diag::note_pure_virtual_function) 2383 << SO->second.front().Method->getDeclName(); 2384 } 2385 } 2386 2387 if (!PureVirtualClassDiagSet) 2388 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2389 PureVirtualClassDiagSet->insert(RD); 2390} 2391 2392namespace { 2393struct AbstractUsageInfo { 2394 Sema &S; 2395 CXXRecordDecl *Record; 2396 CanQualType AbstractType; 2397 bool Invalid; 2398 2399 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2400 : S(S), Record(Record), 2401 AbstractType(S.Context.getCanonicalType( 2402 S.Context.getTypeDeclType(Record))), 2403 Invalid(false) {} 2404 2405 void DiagnoseAbstractType() { 2406 if (Invalid) return; 2407 S.DiagnoseAbstractType(Record); 2408 Invalid = true; 2409 } 2410 2411 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2412}; 2413 2414struct CheckAbstractUsage { 2415 AbstractUsageInfo &Info; 2416 const NamedDecl *Ctx; 2417 2418 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 2419 : Info(Info), Ctx(Ctx) {} 2420 2421 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2422 switch (TL.getTypeLocClass()) { 2423#define ABSTRACT_TYPELOC(CLASS, PARENT) 2424#define TYPELOC(CLASS, PARENT) \ 2425 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 2426#include "clang/AST/TypeLocNodes.def" 2427 } 2428 } 2429 2430 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2431 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 2432 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2433 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 2434 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 2435 } 2436 } 2437 2438 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2439 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 2440 } 2441 2442 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2443 // Visit the type parameters from a permissive context. 2444 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2445 TemplateArgumentLoc TAL = TL.getArgLoc(I); 2446 if (TAL.getArgument().getKind() == TemplateArgument::Type) 2447 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 2448 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 2449 // TODO: other template argument types? 2450 } 2451 } 2452 2453 // Visit pointee types from a permissive context. 2454#define CheckPolymorphic(Type) \ 2455 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 2456 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 2457 } 2458 CheckPolymorphic(PointerTypeLoc) 2459 CheckPolymorphic(ReferenceTypeLoc) 2460 CheckPolymorphic(MemberPointerTypeLoc) 2461 CheckPolymorphic(BlockPointerTypeLoc) 2462 2463 /// Handle all the types we haven't given a more specific 2464 /// implementation for above. 2465 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2466 // Every other kind of type that we haven't called out already 2467 // that has an inner type is either (1) sugar or (2) contains that 2468 // inner type in some way as a subobject. 2469 if (TypeLoc Next = TL.getNextTypeLoc()) 2470 return Visit(Next, Sel); 2471 2472 // If there's no inner type and we're in a permissive context, 2473 // don't diagnose. 2474 if (Sel == Sema::AbstractNone) return; 2475 2476 // Check whether the type matches the abstract type. 2477 QualType T = TL.getType(); 2478 if (T->isArrayType()) { 2479 Sel = Sema::AbstractArrayType; 2480 T = Info.S.Context.getBaseElementType(T); 2481 } 2482 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 2483 if (CT != Info.AbstractType) return; 2484 2485 // It matched; do some magic. 2486 if (Sel == Sema::AbstractArrayType) { 2487 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 2488 << T << TL.getSourceRange(); 2489 } else { 2490 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 2491 << Sel << T << TL.getSourceRange(); 2492 } 2493 Info.DiagnoseAbstractType(); 2494 } 2495}; 2496 2497void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 2498 Sema::AbstractDiagSelID Sel) { 2499 CheckAbstractUsage(*this, D).Visit(TL, Sel); 2500} 2501 2502} 2503 2504/// Check for invalid uses of an abstract type in a method declaration. 2505static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2506 CXXMethodDecl *MD) { 2507 // No need to do the check on definitions, which require that 2508 // the return/param types be complete. 2509 if (MD->isThisDeclarationADefinition()) 2510 return; 2511 2512 // For safety's sake, just ignore it if we don't have type source 2513 // information. This should never happen for non-implicit methods, 2514 // but... 2515 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 2516 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 2517} 2518 2519/// Check for invalid uses of an abstract type within a class definition. 2520static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2521 CXXRecordDecl *RD) { 2522 for (CXXRecordDecl::decl_iterator 2523 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 2524 Decl *D = *I; 2525 if (D->isImplicit()) continue; 2526 2527 // Methods and method templates. 2528 if (isa<CXXMethodDecl>(D)) { 2529 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 2530 } else if (isa<FunctionTemplateDecl>(D)) { 2531 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 2532 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 2533 2534 // Fields and static variables. 2535 } else if (isa<FieldDecl>(D)) { 2536 FieldDecl *FD = cast<FieldDecl>(D); 2537 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 2538 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 2539 } else if (isa<VarDecl>(D)) { 2540 VarDecl *VD = cast<VarDecl>(D); 2541 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 2542 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 2543 2544 // Nested classes and class templates. 2545 } else if (isa<CXXRecordDecl>(D)) { 2546 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 2547 } else if (isa<ClassTemplateDecl>(D)) { 2548 CheckAbstractClassUsage(Info, 2549 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 2550 } 2551 } 2552} 2553 2554/// \brief Perform semantic checks on a class definition that has been 2555/// completing, introducing implicitly-declared members, checking for 2556/// abstract types, etc. 2557void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2558 if (!Record) 2559 return; 2560 2561 if (Record->isAbstract() && !Record->isInvalidDecl()) { 2562 AbstractUsageInfo Info(*this, Record); 2563 CheckAbstractClassUsage(Info, Record); 2564 } 2565 2566 // If this is not an aggregate type and has no user-declared constructor, 2567 // complain about any non-static data members of reference or const scalar 2568 // type, since they will never get initializers. 2569 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2570 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2571 bool Complained = false; 2572 for (RecordDecl::field_iterator F = Record->field_begin(), 2573 FEnd = Record->field_end(); 2574 F != FEnd; ++F) { 2575 if (F->getType()->isReferenceType() || 2576 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2577 if (!Complained) { 2578 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2579 << Record->getTagKind() << Record; 2580 Complained = true; 2581 } 2582 2583 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2584 << F->getType()->isReferenceType() 2585 << F->getDeclName(); 2586 } 2587 } 2588 } 2589 2590 if (Record->isDynamicClass()) 2591 DynamicClasses.push_back(Record); 2592 2593 if (Record->getIdentifier()) { 2594 // C++ [class.mem]p13: 2595 // If T is the name of a class, then each of the following shall have a 2596 // name different from T: 2597 // - every member of every anonymous union that is a member of class T. 2598 // 2599 // C++ [class.mem]p14: 2600 // In addition, if class T has a user-declared constructor (12.1), every 2601 // non-static data member of class T shall have a name different from T. 2602 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 2603 R.first != R.second; ++R.first) 2604 if (FieldDecl *Field = dyn_cast<FieldDecl>(*R.first)) { 2605 if (Record->hasUserDeclaredConstructor() || 2606 !Field->getDeclContext()->Equals(Record)) { 2607 Diag(Field->getLocation(), diag::err_member_name_of_class) 2608 << Field->getDeclName(); 2609 break; 2610 } 2611 } 2612 } 2613} 2614 2615void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2616 Decl *TagDecl, 2617 SourceLocation LBrac, 2618 SourceLocation RBrac, 2619 AttributeList *AttrList) { 2620 if (!TagDecl) 2621 return; 2622 2623 AdjustDeclIfTemplate(TagDecl); 2624 2625 ActOnFields(S, RLoc, TagDecl, 2626 // strict aliasing violation! 2627 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 2628 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 2629 2630 CheckCompletedCXXClass( 2631 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 2632} 2633 2634namespace { 2635 /// \brief Helper class that collects exception specifications for 2636 /// implicitly-declared special member functions. 2637 class ImplicitExceptionSpecification { 2638 ASTContext &Context; 2639 bool AllowsAllExceptions; 2640 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 2641 llvm::SmallVector<QualType, 4> Exceptions; 2642 2643 public: 2644 explicit ImplicitExceptionSpecification(ASTContext &Context) 2645 : Context(Context), AllowsAllExceptions(false) { } 2646 2647 /// \brief Whether the special member function should have any 2648 /// exception specification at all. 2649 bool hasExceptionSpecification() const { 2650 return !AllowsAllExceptions; 2651 } 2652 2653 /// \brief Whether the special member function should have a 2654 /// throw(...) exception specification (a Microsoft extension). 2655 bool hasAnyExceptionSpecification() const { 2656 return false; 2657 } 2658 2659 /// \brief The number of exceptions in the exception specification. 2660 unsigned size() const { return Exceptions.size(); } 2661 2662 /// \brief The set of exceptions in the exception specification. 2663 const QualType *data() const { return Exceptions.data(); } 2664 2665 /// \brief Note that 2666 void CalledDecl(CXXMethodDecl *Method) { 2667 // If we already know that we allow all exceptions, do nothing. 2668 if (AllowsAllExceptions || !Method) 2669 return; 2670 2671 const FunctionProtoType *Proto 2672 = Method->getType()->getAs<FunctionProtoType>(); 2673 2674 // If this function can throw any exceptions, make a note of that. 2675 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) { 2676 AllowsAllExceptions = true; 2677 ExceptionsSeen.clear(); 2678 Exceptions.clear(); 2679 return; 2680 } 2681 2682 // Record the exceptions in this function's exception specification. 2683 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 2684 EEnd = Proto->exception_end(); 2685 E != EEnd; ++E) 2686 if (ExceptionsSeen.insert(Context.getCanonicalType(*E))) 2687 Exceptions.push_back(*E); 2688 } 2689 }; 2690} 2691 2692 2693/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 2694/// special functions, such as the default constructor, copy 2695/// constructor, or destructor, to the given C++ class (C++ 2696/// [special]p1). This routine can only be executed just before the 2697/// definition of the class is complete. 2698void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 2699 if (!ClassDecl->hasUserDeclaredConstructor()) 2700 ++ASTContext::NumImplicitDefaultConstructors; 2701 2702 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 2703 ++ASTContext::NumImplicitCopyConstructors; 2704 2705 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2706 ++ASTContext::NumImplicitCopyAssignmentOperators; 2707 2708 // If we have a dynamic class, then the copy assignment operator may be 2709 // virtual, so we have to declare it immediately. This ensures that, e.g., 2710 // it shows up in the right place in the vtable and that we diagnose 2711 // problems with the implicit exception specification. 2712 if (ClassDecl->isDynamicClass()) 2713 DeclareImplicitCopyAssignment(ClassDecl); 2714 } 2715 2716 if (!ClassDecl->hasUserDeclaredDestructor()) { 2717 ++ASTContext::NumImplicitDestructors; 2718 2719 // If we have a dynamic class, then the destructor may be virtual, so we 2720 // have to declare the destructor immediately. This ensures that, e.g., it 2721 // shows up in the right place in the vtable and that we diagnose problems 2722 // with the implicit exception specification. 2723 if (ClassDecl->isDynamicClass()) 2724 DeclareImplicitDestructor(ClassDecl); 2725 } 2726} 2727 2728void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 2729 if (!D) 2730 return; 2731 2732 TemplateParameterList *Params = 0; 2733 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2734 Params = Template->getTemplateParameters(); 2735 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2736 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2737 Params = PartialSpec->getTemplateParameters(); 2738 else 2739 return; 2740 2741 for (TemplateParameterList::iterator Param = Params->begin(), 2742 ParamEnd = Params->end(); 2743 Param != ParamEnd; ++Param) { 2744 NamedDecl *Named = cast<NamedDecl>(*Param); 2745 if (Named->getDeclName()) { 2746 S->AddDecl(Named); 2747 IdResolver.AddDecl(Named); 2748 } 2749 } 2750} 2751 2752void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 2753 if (!RecordD) return; 2754 AdjustDeclIfTemplate(RecordD); 2755 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 2756 PushDeclContext(S, Record); 2757} 2758 2759void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 2760 if (!RecordD) return; 2761 PopDeclContext(); 2762} 2763 2764/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2765/// parsing a top-level (non-nested) C++ class, and we are now 2766/// parsing those parts of the given Method declaration that could 2767/// not be parsed earlier (C++ [class.mem]p2), such as default 2768/// arguments. This action should enter the scope of the given 2769/// Method declaration as if we had just parsed the qualified method 2770/// name. However, it should not bring the parameters into scope; 2771/// that will be performed by ActOnDelayedCXXMethodParameter. 2772void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 2773} 2774 2775/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2776/// C++ method declaration. We're (re-)introducing the given 2777/// function parameter into scope for use in parsing later parts of 2778/// the method declaration. For example, we could see an 2779/// ActOnParamDefaultArgument event for this parameter. 2780void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 2781 if (!ParamD) 2782 return; 2783 2784 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 2785 2786 // If this parameter has an unparsed default argument, clear it out 2787 // to make way for the parsed default argument. 2788 if (Param->hasUnparsedDefaultArg()) 2789 Param->setDefaultArg(0); 2790 2791 S->AddDecl(Param); 2792 if (Param->getDeclName()) 2793 IdResolver.AddDecl(Param); 2794} 2795 2796/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2797/// processing the delayed method declaration for Method. The method 2798/// declaration is now considered finished. There may be a separate 2799/// ActOnStartOfFunctionDef action later (not necessarily 2800/// immediately!) for this method, if it was also defined inside the 2801/// class body. 2802void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 2803 if (!MethodD) 2804 return; 2805 2806 AdjustDeclIfTemplate(MethodD); 2807 2808 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 2809 2810 // Now that we have our default arguments, check the constructor 2811 // again. It could produce additional diagnostics or affect whether 2812 // the class has implicitly-declared destructors, among other 2813 // things. 2814 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2815 CheckConstructor(Constructor); 2816 2817 // Check the default arguments, which we may have added. 2818 if (!Method->isInvalidDecl()) 2819 CheckCXXDefaultArguments(Method); 2820} 2821 2822/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2823/// the well-formedness of the constructor declarator @p D with type @p 2824/// R. If there are any errors in the declarator, this routine will 2825/// emit diagnostics and set the invalid bit to true. In any case, the type 2826/// will be updated to reflect a well-formed type for the constructor and 2827/// returned. 2828QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2829 StorageClass &SC) { 2830 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2831 2832 // C++ [class.ctor]p3: 2833 // A constructor shall not be virtual (10.3) or static (9.4). A 2834 // constructor can be invoked for a const, volatile or const 2835 // volatile object. A constructor shall not be declared const, 2836 // volatile, or const volatile (9.3.2). 2837 if (isVirtual) { 2838 if (!D.isInvalidType()) 2839 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2840 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2841 << SourceRange(D.getIdentifierLoc()); 2842 D.setInvalidType(); 2843 } 2844 if (SC == SC_Static) { 2845 if (!D.isInvalidType()) 2846 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2847 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2848 << SourceRange(D.getIdentifierLoc()); 2849 D.setInvalidType(); 2850 SC = SC_None; 2851 } 2852 2853 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2854 if (FTI.TypeQuals != 0) { 2855 if (FTI.TypeQuals & Qualifiers::Const) 2856 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2857 << "const" << SourceRange(D.getIdentifierLoc()); 2858 if (FTI.TypeQuals & Qualifiers::Volatile) 2859 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2860 << "volatile" << SourceRange(D.getIdentifierLoc()); 2861 if (FTI.TypeQuals & Qualifiers::Restrict) 2862 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2863 << "restrict" << SourceRange(D.getIdentifierLoc()); 2864 } 2865 2866 // Rebuild the function type "R" without any type qualifiers (in 2867 // case any of the errors above fired) and with "void" as the 2868 // return type, since constructors don't have return types. 2869 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2870 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2871 Proto->getNumArgs(), 2872 Proto->isVariadic(), 0, 2873 Proto->hasExceptionSpec(), 2874 Proto->hasAnyExceptionSpec(), 2875 Proto->getNumExceptions(), 2876 Proto->exception_begin(), 2877 Proto->getExtInfo()); 2878} 2879 2880/// CheckConstructor - Checks a fully-formed constructor for 2881/// well-formedness, issuing any diagnostics required. Returns true if 2882/// the constructor declarator is invalid. 2883void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2884 CXXRecordDecl *ClassDecl 2885 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2886 if (!ClassDecl) 2887 return Constructor->setInvalidDecl(); 2888 2889 // C++ [class.copy]p3: 2890 // A declaration of a constructor for a class X is ill-formed if 2891 // its first parameter is of type (optionally cv-qualified) X and 2892 // either there are no other parameters or else all other 2893 // parameters have default arguments. 2894 if (!Constructor->isInvalidDecl() && 2895 ((Constructor->getNumParams() == 1) || 2896 (Constructor->getNumParams() > 1 && 2897 Constructor->getParamDecl(1)->hasDefaultArg())) && 2898 Constructor->getTemplateSpecializationKind() 2899 != TSK_ImplicitInstantiation) { 2900 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2901 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2902 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2903 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2904 const char *ConstRef 2905 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 2906 : " const &"; 2907 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2908 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 2909 2910 // FIXME: Rather that making the constructor invalid, we should endeavor 2911 // to fix the type. 2912 Constructor->setInvalidDecl(); 2913 } 2914 } 2915} 2916 2917/// CheckDestructor - Checks a fully-formed destructor definition for 2918/// well-formedness, issuing any diagnostics required. Returns true 2919/// on error. 2920bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 2921 CXXRecordDecl *RD = Destructor->getParent(); 2922 2923 if (Destructor->isVirtual()) { 2924 SourceLocation Loc; 2925 2926 if (!Destructor->isImplicit()) 2927 Loc = Destructor->getLocation(); 2928 else 2929 Loc = RD->getLocation(); 2930 2931 // If we have a virtual destructor, look up the deallocation function 2932 FunctionDecl *OperatorDelete = 0; 2933 DeclarationName Name = 2934 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2935 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2936 return true; 2937 2938 MarkDeclarationReferenced(Loc, OperatorDelete); 2939 2940 Destructor->setOperatorDelete(OperatorDelete); 2941 } 2942 2943 return false; 2944} 2945 2946static inline bool 2947FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2948 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2949 FTI.ArgInfo[0].Param && 2950 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 2951} 2952 2953/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2954/// the well-formednes of the destructor declarator @p D with type @p 2955/// R. If there are any errors in the declarator, this routine will 2956/// emit diagnostics and set the declarator to invalid. Even if this happens, 2957/// will be updated to reflect a well-formed type for the destructor and 2958/// returned. 2959QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 2960 StorageClass& SC) { 2961 // C++ [class.dtor]p1: 2962 // [...] A typedef-name that names a class is a class-name 2963 // (7.1.3); however, a typedef-name that names a class shall not 2964 // be used as the identifier in the declarator for a destructor 2965 // declaration. 2966 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 2967 if (isa<TypedefType>(DeclaratorType)) 2968 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2969 << DeclaratorType; 2970 2971 // C++ [class.dtor]p2: 2972 // A destructor is used to destroy objects of its class type. A 2973 // destructor takes no parameters, and no return type can be 2974 // specified for it (not even void). The address of a destructor 2975 // shall not be taken. A destructor shall not be static. A 2976 // destructor can be invoked for a const, volatile or const 2977 // volatile object. A destructor shall not be declared const, 2978 // volatile or const volatile (9.3.2). 2979 if (SC == SC_Static) { 2980 if (!D.isInvalidType()) 2981 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2982 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2983 << SourceRange(D.getIdentifierLoc()) 2984 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 2985 2986 SC = SC_None; 2987 } 2988 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2989 // Destructors don't have return types, but the parser will 2990 // happily parse something like: 2991 // 2992 // class X { 2993 // float ~X(); 2994 // }; 2995 // 2996 // The return type will be eliminated later. 2997 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2998 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2999 << SourceRange(D.getIdentifierLoc()); 3000 } 3001 3002 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3003 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 3004 if (FTI.TypeQuals & Qualifiers::Const) 3005 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3006 << "const" << SourceRange(D.getIdentifierLoc()); 3007 if (FTI.TypeQuals & Qualifiers::Volatile) 3008 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3009 << "volatile" << SourceRange(D.getIdentifierLoc()); 3010 if (FTI.TypeQuals & Qualifiers::Restrict) 3011 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3012 << "restrict" << SourceRange(D.getIdentifierLoc()); 3013 D.setInvalidType(); 3014 } 3015 3016 // Make sure we don't have any parameters. 3017 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 3018 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 3019 3020 // Delete the parameters. 3021 FTI.freeArgs(); 3022 D.setInvalidType(); 3023 } 3024 3025 // Make sure the destructor isn't variadic. 3026 if (FTI.isVariadic) { 3027 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 3028 D.setInvalidType(); 3029 } 3030 3031 // Rebuild the function type "R" without any type qualifiers or 3032 // parameters (in case any of the errors above fired) and with 3033 // "void" as the return type, since destructors don't have return 3034 // types. 3035 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3036 if (!Proto) 3037 return QualType(); 3038 3039 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0, 3040 Proto->hasExceptionSpec(), 3041 Proto->hasAnyExceptionSpec(), 3042 Proto->getNumExceptions(), 3043 Proto->exception_begin(), 3044 Proto->getExtInfo()); 3045} 3046 3047/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 3048/// well-formednes of the conversion function declarator @p D with 3049/// type @p R. If there are any errors in the declarator, this routine 3050/// will emit diagnostics and return true. Otherwise, it will return 3051/// false. Either way, the type @p R will be updated to reflect a 3052/// well-formed type for the conversion operator. 3053void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 3054 StorageClass& SC) { 3055 // C++ [class.conv.fct]p1: 3056 // Neither parameter types nor return type can be specified. The 3057 // type of a conversion function (8.3.5) is "function taking no 3058 // parameter returning conversion-type-id." 3059 if (SC == SC_Static) { 3060 if (!D.isInvalidType()) 3061 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 3062 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3063 << SourceRange(D.getIdentifierLoc()); 3064 D.setInvalidType(); 3065 SC = SC_None; 3066 } 3067 3068 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 3069 3070 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3071 // Conversion functions don't have return types, but the parser will 3072 // happily parse something like: 3073 // 3074 // class X { 3075 // float operator bool(); 3076 // }; 3077 // 3078 // The return type will be changed later anyway. 3079 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 3080 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3081 << SourceRange(D.getIdentifierLoc()); 3082 D.setInvalidType(); 3083 } 3084 3085 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3086 3087 // Make sure we don't have any parameters. 3088 if (Proto->getNumArgs() > 0) { 3089 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3090 3091 // Delete the parameters. 3092 D.getTypeObject(0).Fun.freeArgs(); 3093 D.setInvalidType(); 3094 } else if (Proto->isVariadic()) { 3095 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3096 D.setInvalidType(); 3097 } 3098 3099 // Diagnose "&operator bool()" and other such nonsense. This 3100 // is actually a gcc extension which we don't support. 3101 if (Proto->getResultType() != ConvType) { 3102 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3103 << Proto->getResultType(); 3104 D.setInvalidType(); 3105 ConvType = Proto->getResultType(); 3106 } 3107 3108 // C++ [class.conv.fct]p4: 3109 // The conversion-type-id shall not represent a function type nor 3110 // an array type. 3111 if (ConvType->isArrayType()) { 3112 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3113 ConvType = Context.getPointerType(ConvType); 3114 D.setInvalidType(); 3115 } else if (ConvType->isFunctionType()) { 3116 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3117 ConvType = Context.getPointerType(ConvType); 3118 D.setInvalidType(); 3119 } 3120 3121 // Rebuild the function type "R" without any parameters (in case any 3122 // of the errors above fired) and with the conversion type as the 3123 // return type. 3124 if (D.isInvalidType()) { 3125 R = Context.getFunctionType(ConvType, 0, 0, false, 3126 Proto->getTypeQuals(), 3127 Proto->hasExceptionSpec(), 3128 Proto->hasAnyExceptionSpec(), 3129 Proto->getNumExceptions(), 3130 Proto->exception_begin(), 3131 Proto->getExtInfo()); 3132 } 3133 3134 // C++0x explicit conversion operators. 3135 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3136 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3137 diag::warn_explicit_conversion_functions) 3138 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3139} 3140 3141/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3142/// the declaration of the given C++ conversion function. This routine 3143/// is responsible for recording the conversion function in the C++ 3144/// class, if possible. 3145Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3146 assert(Conversion && "Expected to receive a conversion function declaration"); 3147 3148 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3149 3150 // Make sure we aren't redeclaring the conversion function. 3151 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3152 3153 // C++ [class.conv.fct]p1: 3154 // [...] A conversion function is never used to convert a 3155 // (possibly cv-qualified) object to the (possibly cv-qualified) 3156 // same object type (or a reference to it), to a (possibly 3157 // cv-qualified) base class of that type (or a reference to it), 3158 // or to (possibly cv-qualified) void. 3159 // FIXME: Suppress this warning if the conversion function ends up being a 3160 // virtual function that overrides a virtual function in a base class. 3161 QualType ClassType 3162 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3163 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3164 ConvType = ConvTypeRef->getPointeeType(); 3165 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 3166 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 3167 /* Suppress diagnostics for instantiations. */; 3168 else if (ConvType->isRecordType()) { 3169 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3170 if (ConvType == ClassType) 3171 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3172 << ClassType; 3173 else if (IsDerivedFrom(ClassType, ConvType)) 3174 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3175 << ClassType << ConvType; 3176 } else if (ConvType->isVoidType()) { 3177 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3178 << ClassType << ConvType; 3179 } 3180 3181 if (FunctionTemplateDecl *ConversionTemplate 3182 = Conversion->getDescribedFunctionTemplate()) 3183 return ConversionTemplate; 3184 3185 return Conversion; 3186} 3187 3188//===----------------------------------------------------------------------===// 3189// Namespace Handling 3190//===----------------------------------------------------------------------===// 3191 3192 3193 3194/// ActOnStartNamespaceDef - This is called at the start of a namespace 3195/// definition. 3196Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3197 SourceLocation InlineLoc, 3198 SourceLocation IdentLoc, 3199 IdentifierInfo *II, 3200 SourceLocation LBrace, 3201 AttributeList *AttrList) { 3202 // anonymous namespace starts at its left brace 3203 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 3204 (II ? IdentLoc : LBrace) , II); 3205 Namespc->setLBracLoc(LBrace); 3206 Namespc->setInline(InlineLoc.isValid()); 3207 3208 Scope *DeclRegionScope = NamespcScope->getParent(); 3209 3210 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3211 3212 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>()) 3213 PushVisibilityAttr(attr); 3214 3215 if (II) { 3216 // C++ [namespace.def]p2: 3217 // The identifier in an original-namespace-definition shall not 3218 // have been previously defined in the declarative region in 3219 // which the original-namespace-definition appears. The 3220 // identifier in an original-namespace-definition is the name of 3221 // the namespace. Subsequently in that declarative region, it is 3222 // treated as an original-namespace-name. 3223 // 3224 // Since namespace names are unique in their scope, and we don't 3225 // look through using directives, just 3226 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 3227 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first; 3228 3229 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3230 // This is an extended namespace definition. 3231 if (Namespc->isInline() != OrigNS->isInline()) { 3232 // inline-ness must match 3233 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3234 << Namespc->isInline(); 3235 Diag(OrigNS->getLocation(), diag::note_previous_definition); 3236 Namespc->setInvalidDecl(); 3237 // Recover by ignoring the new namespace's inline status. 3238 Namespc->setInline(OrigNS->isInline()); 3239 } 3240 3241 // Attach this namespace decl to the chain of extended namespace 3242 // definitions. 3243 OrigNS->setNextNamespace(Namespc); 3244 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3245 3246 // Remove the previous declaration from the scope. 3247 if (DeclRegionScope->isDeclScope(OrigNS)) { 3248 IdResolver.RemoveDecl(OrigNS); 3249 DeclRegionScope->RemoveDecl(OrigNS); 3250 } 3251 } else if (PrevDecl) { 3252 // This is an invalid name redefinition. 3253 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3254 << Namespc->getDeclName(); 3255 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3256 Namespc->setInvalidDecl(); 3257 // Continue on to push Namespc as current DeclContext and return it. 3258 } else if (II->isStr("std") && 3259 CurContext->getRedeclContext()->isTranslationUnit()) { 3260 // This is the first "real" definition of the namespace "std", so update 3261 // our cache of the "std" namespace to point at this definition. 3262 if (NamespaceDecl *StdNS = getStdNamespace()) { 3263 // We had already defined a dummy namespace "std". Link this new 3264 // namespace definition to the dummy namespace "std". 3265 StdNS->setNextNamespace(Namespc); 3266 StdNS->setLocation(IdentLoc); 3267 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 3268 } 3269 3270 // Make our StdNamespace cache point at the first real definition of the 3271 // "std" namespace. 3272 StdNamespace = Namespc; 3273 } 3274 3275 PushOnScopeChains(Namespc, DeclRegionScope); 3276 } else { 3277 // Anonymous namespaces. 3278 assert(Namespc->isAnonymousNamespace()); 3279 3280 // Link the anonymous namespace into its parent. 3281 NamespaceDecl *PrevDecl; 3282 DeclContext *Parent = CurContext->getRedeclContext(); 3283 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3284 PrevDecl = TU->getAnonymousNamespace(); 3285 TU->setAnonymousNamespace(Namespc); 3286 } else { 3287 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3288 PrevDecl = ND->getAnonymousNamespace(); 3289 ND->setAnonymousNamespace(Namespc); 3290 } 3291 3292 // Link the anonymous namespace with its previous declaration. 3293 if (PrevDecl) { 3294 assert(PrevDecl->isAnonymousNamespace()); 3295 assert(!PrevDecl->getNextNamespace()); 3296 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3297 PrevDecl->setNextNamespace(Namespc); 3298 3299 if (Namespc->isInline() != PrevDecl->isInline()) { 3300 // inline-ness must match 3301 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3302 << Namespc->isInline(); 3303 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3304 Namespc->setInvalidDecl(); 3305 // Recover by ignoring the new namespace's inline status. 3306 Namespc->setInline(PrevDecl->isInline()); 3307 } 3308 } 3309 3310 CurContext->addDecl(Namespc); 3311 3312 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3313 // behaves as if it were replaced by 3314 // namespace unique { /* empty body */ } 3315 // using namespace unique; 3316 // namespace unique { namespace-body } 3317 // where all occurrences of 'unique' in a translation unit are 3318 // replaced by the same identifier and this identifier differs 3319 // from all other identifiers in the entire program. 3320 3321 // We just create the namespace with an empty name and then add an 3322 // implicit using declaration, just like the standard suggests. 3323 // 3324 // CodeGen enforces the "universally unique" aspect by giving all 3325 // declarations semantically contained within an anonymous 3326 // namespace internal linkage. 3327 3328 if (!PrevDecl) { 3329 UsingDirectiveDecl* UD 3330 = UsingDirectiveDecl::Create(Context, CurContext, 3331 /* 'using' */ LBrace, 3332 /* 'namespace' */ SourceLocation(), 3333 /* qualifier */ SourceRange(), 3334 /* NNS */ NULL, 3335 /* identifier */ SourceLocation(), 3336 Namespc, 3337 /* Ancestor */ CurContext); 3338 UD->setImplicit(); 3339 CurContext->addDecl(UD); 3340 } 3341 } 3342 3343 // Although we could have an invalid decl (i.e. the namespace name is a 3344 // redefinition), push it as current DeclContext and try to continue parsing. 3345 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3346 // for the namespace has the declarations that showed up in that particular 3347 // namespace definition. 3348 PushDeclContext(NamespcScope, Namespc); 3349 return Namespc; 3350} 3351 3352/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3353/// is a namespace alias, returns the namespace it points to. 3354static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3355 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3356 return AD->getNamespace(); 3357 return dyn_cast_or_null<NamespaceDecl>(D); 3358} 3359 3360/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3361/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3362void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 3363 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3364 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3365 Namespc->setRBracLoc(RBrace); 3366 PopDeclContext(); 3367 if (Namespc->hasAttr<VisibilityAttr>()) 3368 PopPragmaVisibility(); 3369} 3370 3371CXXRecordDecl *Sema::getStdBadAlloc() const { 3372 return cast_or_null<CXXRecordDecl>( 3373 StdBadAlloc.get(Context.getExternalSource())); 3374} 3375 3376NamespaceDecl *Sema::getStdNamespace() const { 3377 return cast_or_null<NamespaceDecl>( 3378 StdNamespace.get(Context.getExternalSource())); 3379} 3380 3381/// \brief Retrieve the special "std" namespace, which may require us to 3382/// implicitly define the namespace. 3383NamespaceDecl *Sema::getOrCreateStdNamespace() { 3384 if (!StdNamespace) { 3385 // The "std" namespace has not yet been defined, so build one implicitly. 3386 StdNamespace = NamespaceDecl::Create(Context, 3387 Context.getTranslationUnitDecl(), 3388 SourceLocation(), 3389 &PP.getIdentifierTable().get("std")); 3390 getStdNamespace()->setImplicit(true); 3391 } 3392 3393 return getStdNamespace(); 3394} 3395 3396Decl *Sema::ActOnUsingDirective(Scope *S, 3397 SourceLocation UsingLoc, 3398 SourceLocation NamespcLoc, 3399 CXXScopeSpec &SS, 3400 SourceLocation IdentLoc, 3401 IdentifierInfo *NamespcName, 3402 AttributeList *AttrList) { 3403 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3404 assert(NamespcName && "Invalid NamespcName."); 3405 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3406 3407 // This can only happen along a recovery path. 3408 while (S->getFlags() & Scope::TemplateParamScope) 3409 S = S->getParent(); 3410 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3411 3412 UsingDirectiveDecl *UDir = 0; 3413 NestedNameSpecifier *Qualifier = 0; 3414 if (SS.isSet()) 3415 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3416 3417 // Lookup namespace name. 3418 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3419 LookupParsedName(R, S, &SS); 3420 if (R.isAmbiguous()) 3421 return 0; 3422 3423 if (R.empty()) { 3424 // Allow "using namespace std;" or "using namespace ::std;" even if 3425 // "std" hasn't been defined yet, for GCC compatibility. 3426 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 3427 NamespcName->isStr("std")) { 3428 Diag(IdentLoc, diag::ext_using_undefined_std); 3429 R.addDecl(getOrCreateStdNamespace()); 3430 R.resolveKind(); 3431 } 3432 // Otherwise, attempt typo correction. 3433 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 3434 CTC_NoKeywords, 0)) { 3435 if (R.getAsSingle<NamespaceDecl>() || 3436 R.getAsSingle<NamespaceAliasDecl>()) { 3437 if (DeclContext *DC = computeDeclContext(SS, false)) 3438 Diag(IdentLoc, diag::err_using_directive_member_suggest) 3439 << NamespcName << DC << Corrected << SS.getRange() 3440 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3441 else 3442 Diag(IdentLoc, diag::err_using_directive_suggest) 3443 << NamespcName << Corrected 3444 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3445 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 3446 << Corrected; 3447 3448 NamespcName = Corrected.getAsIdentifierInfo(); 3449 } else { 3450 R.clear(); 3451 R.setLookupName(NamespcName); 3452 } 3453 } 3454 } 3455 3456 if (!R.empty()) { 3457 NamedDecl *Named = R.getFoundDecl(); 3458 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3459 && "expected namespace decl"); 3460 // C++ [namespace.udir]p1: 3461 // A using-directive specifies that the names in the nominated 3462 // namespace can be used in the scope in which the 3463 // using-directive appears after the using-directive. During 3464 // unqualified name lookup (3.4.1), the names appear as if they 3465 // were declared in the nearest enclosing namespace which 3466 // contains both the using-directive and the nominated 3467 // namespace. [Note: in this context, "contains" means "contains 3468 // directly or indirectly". ] 3469 3470 // Find enclosing context containing both using-directive and 3471 // nominated namespace. 3472 NamespaceDecl *NS = getNamespaceDecl(Named); 3473 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3474 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3475 CommonAncestor = CommonAncestor->getParent(); 3476 3477 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3478 SS.getRange(), 3479 (NestedNameSpecifier *)SS.getScopeRep(), 3480 IdentLoc, Named, CommonAncestor); 3481 PushUsingDirective(S, UDir); 3482 } else { 3483 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3484 } 3485 3486 // FIXME: We ignore attributes for now. 3487 return UDir; 3488} 3489 3490void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3491 // If scope has associated entity, then using directive is at namespace 3492 // or translation unit scope. We add UsingDirectiveDecls, into 3493 // it's lookup structure. 3494 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3495 Ctx->addDecl(UDir); 3496 else 3497 // Otherwise it is block-sope. using-directives will affect lookup 3498 // only to the end of scope. 3499 S->PushUsingDirective(UDir); 3500} 3501 3502 3503Decl *Sema::ActOnUsingDeclaration(Scope *S, 3504 AccessSpecifier AS, 3505 bool HasUsingKeyword, 3506 SourceLocation UsingLoc, 3507 CXXScopeSpec &SS, 3508 UnqualifiedId &Name, 3509 AttributeList *AttrList, 3510 bool IsTypeName, 3511 SourceLocation TypenameLoc) { 3512 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3513 3514 switch (Name.getKind()) { 3515 case UnqualifiedId::IK_Identifier: 3516 case UnqualifiedId::IK_OperatorFunctionId: 3517 case UnqualifiedId::IK_LiteralOperatorId: 3518 case UnqualifiedId::IK_ConversionFunctionId: 3519 break; 3520 3521 case UnqualifiedId::IK_ConstructorName: 3522 case UnqualifiedId::IK_ConstructorTemplateId: 3523 // C++0x inherited constructors. 3524 if (getLangOptions().CPlusPlus0x) break; 3525 3526 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3527 << SS.getRange(); 3528 return 0; 3529 3530 case UnqualifiedId::IK_DestructorName: 3531 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3532 << SS.getRange(); 3533 return 0; 3534 3535 case UnqualifiedId::IK_TemplateId: 3536 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3537 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3538 return 0; 3539 } 3540 3541 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 3542 DeclarationName TargetName = TargetNameInfo.getName(); 3543 if (!TargetName) 3544 return 0; 3545 3546 // Warn about using declarations. 3547 // TODO: store that the declaration was written without 'using' and 3548 // talk about access decls instead of using decls in the 3549 // diagnostics. 3550 if (!HasUsingKeyword) { 3551 UsingLoc = Name.getSourceRange().getBegin(); 3552 3553 Diag(UsingLoc, diag::warn_access_decl_deprecated) 3554 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 3555 } 3556 3557 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3558 TargetNameInfo, AttrList, 3559 /* IsInstantiation */ false, 3560 IsTypeName, TypenameLoc); 3561 if (UD) 3562 PushOnScopeChains(UD, S, /*AddToContext*/ false); 3563 3564 return UD; 3565} 3566 3567/// \brief Determine whether a using declaration considers the given 3568/// declarations as "equivalent", e.g., if they are redeclarations of 3569/// the same entity or are both typedefs of the same type. 3570static bool 3571IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 3572 bool &SuppressRedeclaration) { 3573 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 3574 SuppressRedeclaration = false; 3575 return true; 3576 } 3577 3578 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1)) 3579 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) { 3580 SuppressRedeclaration = true; 3581 return Context.hasSameType(TD1->getUnderlyingType(), 3582 TD2->getUnderlyingType()); 3583 } 3584 3585 return false; 3586} 3587 3588 3589/// Determines whether to create a using shadow decl for a particular 3590/// decl, given the set of decls existing prior to this using lookup. 3591bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 3592 const LookupResult &Previous) { 3593 // Diagnose finding a decl which is not from a base class of the 3594 // current class. We do this now because there are cases where this 3595 // function will silently decide not to build a shadow decl, which 3596 // will pre-empt further diagnostics. 3597 // 3598 // We don't need to do this in C++0x because we do the check once on 3599 // the qualifier. 3600 // 3601 // FIXME: diagnose the following if we care enough: 3602 // struct A { int foo; }; 3603 // struct B : A { using A::foo; }; 3604 // template <class T> struct C : A {}; 3605 // template <class T> struct D : C<T> { using B::foo; } // <--- 3606 // This is invalid (during instantiation) in C++03 because B::foo 3607 // resolves to the using decl in B, which is not a base class of D<T>. 3608 // We can't diagnose it immediately because C<T> is an unknown 3609 // specialization. The UsingShadowDecl in D<T> then points directly 3610 // to A::foo, which will look well-formed when we instantiate. 3611 // The right solution is to not collapse the shadow-decl chain. 3612 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 3613 DeclContext *OrigDC = Orig->getDeclContext(); 3614 3615 // Handle enums and anonymous structs. 3616 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 3617 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 3618 while (OrigRec->isAnonymousStructOrUnion()) 3619 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 3620 3621 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 3622 if (OrigDC == CurContext) { 3623 Diag(Using->getLocation(), 3624 diag::err_using_decl_nested_name_specifier_is_current_class) 3625 << Using->getNestedNameRange(); 3626 Diag(Orig->getLocation(), diag::note_using_decl_target); 3627 return true; 3628 } 3629 3630 Diag(Using->getNestedNameRange().getBegin(), 3631 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3632 << Using->getTargetNestedNameDecl() 3633 << cast<CXXRecordDecl>(CurContext) 3634 << Using->getNestedNameRange(); 3635 Diag(Orig->getLocation(), diag::note_using_decl_target); 3636 return true; 3637 } 3638 } 3639 3640 if (Previous.empty()) return false; 3641 3642 NamedDecl *Target = Orig; 3643 if (isa<UsingShadowDecl>(Target)) 3644 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3645 3646 // If the target happens to be one of the previous declarations, we 3647 // don't have a conflict. 3648 // 3649 // FIXME: but we might be increasing its access, in which case we 3650 // should redeclare it. 3651 NamedDecl *NonTag = 0, *Tag = 0; 3652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3653 I != E; ++I) { 3654 NamedDecl *D = (*I)->getUnderlyingDecl(); 3655 bool Result; 3656 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 3657 return Result; 3658 3659 (isa<TagDecl>(D) ? Tag : NonTag) = D; 3660 } 3661 3662 if (Target->isFunctionOrFunctionTemplate()) { 3663 FunctionDecl *FD; 3664 if (isa<FunctionTemplateDecl>(Target)) 3665 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 3666 else 3667 FD = cast<FunctionDecl>(Target); 3668 3669 NamedDecl *OldDecl = 0; 3670 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 3671 case Ovl_Overload: 3672 return false; 3673 3674 case Ovl_NonFunction: 3675 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3676 break; 3677 3678 // We found a decl with the exact signature. 3679 case Ovl_Match: 3680 // If we're in a record, we want to hide the target, so we 3681 // return true (without a diagnostic) to tell the caller not to 3682 // build a shadow decl. 3683 if (CurContext->isRecord()) 3684 return true; 3685 3686 // If we're not in a record, this is an error. 3687 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3688 break; 3689 } 3690 3691 Diag(Target->getLocation(), diag::note_using_decl_target); 3692 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 3693 return true; 3694 } 3695 3696 // Target is not a function. 3697 3698 if (isa<TagDecl>(Target)) { 3699 // No conflict between a tag and a non-tag. 3700 if (!Tag) return false; 3701 3702 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3703 Diag(Target->getLocation(), diag::note_using_decl_target); 3704 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 3705 return true; 3706 } 3707 3708 // No conflict between a tag and a non-tag. 3709 if (!NonTag) return false; 3710 3711 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3712 Diag(Target->getLocation(), diag::note_using_decl_target); 3713 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 3714 return true; 3715} 3716 3717/// Builds a shadow declaration corresponding to a 'using' declaration. 3718UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 3719 UsingDecl *UD, 3720 NamedDecl *Orig) { 3721 3722 // If we resolved to another shadow declaration, just coalesce them. 3723 NamedDecl *Target = Orig; 3724 if (isa<UsingShadowDecl>(Target)) { 3725 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3726 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 3727 } 3728 3729 UsingShadowDecl *Shadow 3730 = UsingShadowDecl::Create(Context, CurContext, 3731 UD->getLocation(), UD, Target); 3732 UD->addShadowDecl(Shadow); 3733 3734 Shadow->setAccess(UD->getAccess()); 3735 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 3736 Shadow->setInvalidDecl(); 3737 3738 if (S) 3739 PushOnScopeChains(Shadow, S); 3740 else 3741 CurContext->addDecl(Shadow); 3742 3743 3744 return Shadow; 3745} 3746 3747/// Hides a using shadow declaration. This is required by the current 3748/// using-decl implementation when a resolvable using declaration in a 3749/// class is followed by a declaration which would hide or override 3750/// one or more of the using decl's targets; for example: 3751/// 3752/// struct Base { void foo(int); }; 3753/// struct Derived : Base { 3754/// using Base::foo; 3755/// void foo(int); 3756/// }; 3757/// 3758/// The governing language is C++03 [namespace.udecl]p12: 3759/// 3760/// When a using-declaration brings names from a base class into a 3761/// derived class scope, member functions in the derived class 3762/// override and/or hide member functions with the same name and 3763/// parameter types in a base class (rather than conflicting). 3764/// 3765/// There are two ways to implement this: 3766/// (1) optimistically create shadow decls when they're not hidden 3767/// by existing declarations, or 3768/// (2) don't create any shadow decls (or at least don't make them 3769/// visible) until we've fully parsed/instantiated the class. 3770/// The problem with (1) is that we might have to retroactively remove 3771/// a shadow decl, which requires several O(n) operations because the 3772/// decl structures are (very reasonably) not designed for removal. 3773/// (2) avoids this but is very fiddly and phase-dependent. 3774void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 3775 if (Shadow->getDeclName().getNameKind() == 3776 DeclarationName::CXXConversionFunctionName) 3777 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 3778 3779 // Remove it from the DeclContext... 3780 Shadow->getDeclContext()->removeDecl(Shadow); 3781 3782 // ...and the scope, if applicable... 3783 if (S) { 3784 S->RemoveDecl(Shadow); 3785 IdResolver.RemoveDecl(Shadow); 3786 } 3787 3788 // ...and the using decl. 3789 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 3790 3791 // TODO: complain somehow if Shadow was used. It shouldn't 3792 // be possible for this to happen, because...? 3793} 3794 3795/// Builds a using declaration. 3796/// 3797/// \param IsInstantiation - Whether this call arises from an 3798/// instantiation of an unresolved using declaration. We treat 3799/// the lookup differently for these declarations. 3800NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3801 SourceLocation UsingLoc, 3802 CXXScopeSpec &SS, 3803 const DeclarationNameInfo &NameInfo, 3804 AttributeList *AttrList, 3805 bool IsInstantiation, 3806 bool IsTypeName, 3807 SourceLocation TypenameLoc) { 3808 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3809 SourceLocation IdentLoc = NameInfo.getLoc(); 3810 assert(IdentLoc.isValid() && "Invalid TargetName location."); 3811 3812 // FIXME: We ignore attributes for now. 3813 3814 if (SS.isEmpty()) { 3815 Diag(IdentLoc, diag::err_using_requires_qualname); 3816 return 0; 3817 } 3818 3819 // Do the redeclaration lookup in the current scope. 3820 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 3821 ForRedeclaration); 3822 Previous.setHideTags(false); 3823 if (S) { 3824 LookupName(Previous, S); 3825 3826 // It is really dumb that we have to do this. 3827 LookupResult::Filter F = Previous.makeFilter(); 3828 while (F.hasNext()) { 3829 NamedDecl *D = F.next(); 3830 if (!isDeclInScope(D, CurContext, S)) 3831 F.erase(); 3832 } 3833 F.done(); 3834 } else { 3835 assert(IsInstantiation && "no scope in non-instantiation"); 3836 assert(CurContext->isRecord() && "scope not record in instantiation"); 3837 LookupQualifiedName(Previous, CurContext); 3838 } 3839 3840 NestedNameSpecifier *NNS = 3841 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3842 3843 // Check for invalid redeclarations. 3844 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 3845 return 0; 3846 3847 // Check for bad qualifiers. 3848 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 3849 return 0; 3850 3851 DeclContext *LookupContext = computeDeclContext(SS); 3852 NamedDecl *D; 3853 if (!LookupContext) { 3854 if (IsTypeName) { 3855 // FIXME: not all declaration name kinds are legal here 3856 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 3857 UsingLoc, TypenameLoc, 3858 SS.getRange(), NNS, 3859 IdentLoc, NameInfo.getName()); 3860 } else { 3861 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 3862 UsingLoc, SS.getRange(), 3863 NNS, NameInfo); 3864 } 3865 } else { 3866 D = UsingDecl::Create(Context, CurContext, 3867 SS.getRange(), UsingLoc, NNS, NameInfo, 3868 IsTypeName); 3869 } 3870 D->setAccess(AS); 3871 CurContext->addDecl(D); 3872 3873 if (!LookupContext) return D; 3874 UsingDecl *UD = cast<UsingDecl>(D); 3875 3876 if (RequireCompleteDeclContext(SS, LookupContext)) { 3877 UD->setInvalidDecl(); 3878 return UD; 3879 } 3880 3881 // Look up the target name. 3882 3883 LookupResult R(*this, NameInfo, LookupOrdinaryName); 3884 3885 // Unlike most lookups, we don't always want to hide tag 3886 // declarations: tag names are visible through the using declaration 3887 // even if hidden by ordinary names, *except* in a dependent context 3888 // where it's important for the sanity of two-phase lookup. 3889 if (!IsInstantiation) 3890 R.setHideTags(false); 3891 3892 LookupQualifiedName(R, LookupContext); 3893 3894 if (R.empty()) { 3895 Diag(IdentLoc, diag::err_no_member) 3896 << NameInfo.getName() << LookupContext << SS.getRange(); 3897 UD->setInvalidDecl(); 3898 return UD; 3899 } 3900 3901 if (R.isAmbiguous()) { 3902 UD->setInvalidDecl(); 3903 return UD; 3904 } 3905 3906 if (IsTypeName) { 3907 // If we asked for a typename and got a non-type decl, error out. 3908 if (!R.getAsSingle<TypeDecl>()) { 3909 Diag(IdentLoc, diag::err_using_typename_non_type); 3910 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3911 Diag((*I)->getUnderlyingDecl()->getLocation(), 3912 diag::note_using_decl_target); 3913 UD->setInvalidDecl(); 3914 return UD; 3915 } 3916 } else { 3917 // If we asked for a non-typename and we got a type, error out, 3918 // but only if this is an instantiation of an unresolved using 3919 // decl. Otherwise just silently find the type name. 3920 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 3921 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 3922 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 3923 UD->setInvalidDecl(); 3924 return UD; 3925 } 3926 } 3927 3928 // C++0x N2914 [namespace.udecl]p6: 3929 // A using-declaration shall not name a namespace. 3930 if (R.getAsSingle<NamespaceDecl>()) { 3931 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3932 << SS.getRange(); 3933 UD->setInvalidDecl(); 3934 return UD; 3935 } 3936 3937 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3938 if (!CheckUsingShadowDecl(UD, *I, Previous)) 3939 BuildUsingShadowDecl(S, UD, *I); 3940 } 3941 3942 return UD; 3943} 3944 3945/// Checks that the given using declaration is not an invalid 3946/// redeclaration. Note that this is checking only for the using decl 3947/// itself, not for any ill-formedness among the UsingShadowDecls. 3948bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3949 bool isTypeName, 3950 const CXXScopeSpec &SS, 3951 SourceLocation NameLoc, 3952 const LookupResult &Prev) { 3953 // C++03 [namespace.udecl]p8: 3954 // C++0x [namespace.udecl]p10: 3955 // A using-declaration is a declaration and can therefore be used 3956 // repeatedly where (and only where) multiple declarations are 3957 // allowed. 3958 // 3959 // That's in non-member contexts. 3960 if (!CurContext->getRedeclContext()->isRecord()) 3961 return false; 3962 3963 NestedNameSpecifier *Qual 3964 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 3965 3966 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 3967 NamedDecl *D = *I; 3968 3969 bool DTypename; 3970 NestedNameSpecifier *DQual; 3971 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 3972 DTypename = UD->isTypeName(); 3973 DQual = UD->getTargetNestedNameDecl(); 3974 } else if (UnresolvedUsingValueDecl *UD 3975 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3976 DTypename = false; 3977 DQual = UD->getTargetNestedNameSpecifier(); 3978 } else if (UnresolvedUsingTypenameDecl *UD 3979 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3980 DTypename = true; 3981 DQual = UD->getTargetNestedNameSpecifier(); 3982 } else continue; 3983 3984 // using decls differ if one says 'typename' and the other doesn't. 3985 // FIXME: non-dependent using decls? 3986 if (isTypeName != DTypename) continue; 3987 3988 // using decls differ if they name different scopes (but note that 3989 // template instantiation can cause this check to trigger when it 3990 // didn't before instantiation). 3991 if (Context.getCanonicalNestedNameSpecifier(Qual) != 3992 Context.getCanonicalNestedNameSpecifier(DQual)) 3993 continue; 3994 3995 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 3996 Diag(D->getLocation(), diag::note_using_decl) << 1; 3997 return true; 3998 } 3999 4000 return false; 4001} 4002 4003 4004/// Checks that the given nested-name qualifier used in a using decl 4005/// in the current context is appropriately related to the current 4006/// scope. If an error is found, diagnoses it and returns true. 4007bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 4008 const CXXScopeSpec &SS, 4009 SourceLocation NameLoc) { 4010 DeclContext *NamedContext = computeDeclContext(SS); 4011 4012 if (!CurContext->isRecord()) { 4013 // C++03 [namespace.udecl]p3: 4014 // C++0x [namespace.udecl]p8: 4015 // A using-declaration for a class member shall be a member-declaration. 4016 4017 // If we weren't able to compute a valid scope, it must be a 4018 // dependent class scope. 4019 if (!NamedContext || NamedContext->isRecord()) { 4020 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 4021 << SS.getRange(); 4022 return true; 4023 } 4024 4025 // Otherwise, everything is known to be fine. 4026 return false; 4027 } 4028 4029 // The current scope is a record. 4030 4031 // If the named context is dependent, we can't decide much. 4032 if (!NamedContext) { 4033 // FIXME: in C++0x, we can diagnose if we can prove that the 4034 // nested-name-specifier does not refer to a base class, which is 4035 // still possible in some cases. 4036 4037 // Otherwise we have to conservatively report that things might be 4038 // okay. 4039 return false; 4040 } 4041 4042 if (!NamedContext->isRecord()) { 4043 // Ideally this would point at the last name in the specifier, 4044 // but we don't have that level of source info. 4045 Diag(SS.getRange().getBegin(), 4046 diag::err_using_decl_nested_name_specifier_is_not_class) 4047 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 4048 return true; 4049 } 4050 4051 if (getLangOptions().CPlusPlus0x) { 4052 // C++0x [namespace.udecl]p3: 4053 // In a using-declaration used as a member-declaration, the 4054 // nested-name-specifier shall name a base class of the class 4055 // being defined. 4056 4057 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 4058 cast<CXXRecordDecl>(NamedContext))) { 4059 if (CurContext == NamedContext) { 4060 Diag(NameLoc, 4061 diag::err_using_decl_nested_name_specifier_is_current_class) 4062 << SS.getRange(); 4063 return true; 4064 } 4065 4066 Diag(SS.getRange().getBegin(), 4067 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4068 << (NestedNameSpecifier*) SS.getScopeRep() 4069 << cast<CXXRecordDecl>(CurContext) 4070 << SS.getRange(); 4071 return true; 4072 } 4073 4074 return false; 4075 } 4076 4077 // C++03 [namespace.udecl]p4: 4078 // A using-declaration used as a member-declaration shall refer 4079 // to a member of a base class of the class being defined [etc.]. 4080 4081 // Salient point: SS doesn't have to name a base class as long as 4082 // lookup only finds members from base classes. Therefore we can 4083 // diagnose here only if we can prove that that can't happen, 4084 // i.e. if the class hierarchies provably don't intersect. 4085 4086 // TODO: it would be nice if "definitely valid" results were cached 4087 // in the UsingDecl and UsingShadowDecl so that these checks didn't 4088 // need to be repeated. 4089 4090 struct UserData { 4091 llvm::DenseSet<const CXXRecordDecl*> Bases; 4092 4093 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 4094 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4095 Data->Bases.insert(Base); 4096 return true; 4097 } 4098 4099 bool hasDependentBases(const CXXRecordDecl *Class) { 4100 return !Class->forallBases(collect, this); 4101 } 4102 4103 /// Returns true if the base is dependent or is one of the 4104 /// accumulated base classes. 4105 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 4106 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4107 return !Data->Bases.count(Base); 4108 } 4109 4110 bool mightShareBases(const CXXRecordDecl *Class) { 4111 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 4112 } 4113 }; 4114 4115 UserData Data; 4116 4117 // Returns false if we find a dependent base. 4118 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 4119 return false; 4120 4121 // Returns false if the class has a dependent base or if it or one 4122 // of its bases is present in the base set of the current context. 4123 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 4124 return false; 4125 4126 Diag(SS.getRange().getBegin(), 4127 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4128 << (NestedNameSpecifier*) SS.getScopeRep() 4129 << cast<CXXRecordDecl>(CurContext) 4130 << SS.getRange(); 4131 4132 return true; 4133} 4134 4135Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 4136 SourceLocation NamespaceLoc, 4137 SourceLocation AliasLoc, 4138 IdentifierInfo *Alias, 4139 CXXScopeSpec &SS, 4140 SourceLocation IdentLoc, 4141 IdentifierInfo *Ident) { 4142 4143 // Lookup the namespace name. 4144 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 4145 LookupParsedName(R, S, &SS); 4146 4147 // Check if we have a previous declaration with the same name. 4148 NamedDecl *PrevDecl 4149 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 4150 ForRedeclaration); 4151 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 4152 PrevDecl = 0; 4153 4154 if (PrevDecl) { 4155 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 4156 // We already have an alias with the same name that points to the same 4157 // namespace, so don't create a new one. 4158 // FIXME: At some point, we'll want to create the (redundant) 4159 // declaration to maintain better source information. 4160 if (!R.isAmbiguous() && !R.empty() && 4161 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 4162 return 0; 4163 } 4164 4165 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 4166 diag::err_redefinition_different_kind; 4167 Diag(AliasLoc, DiagID) << Alias; 4168 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4169 return 0; 4170 } 4171 4172 if (R.isAmbiguous()) 4173 return 0; 4174 4175 if (R.empty()) { 4176 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 4177 CTC_NoKeywords, 0)) { 4178 if (R.getAsSingle<NamespaceDecl>() || 4179 R.getAsSingle<NamespaceAliasDecl>()) { 4180 if (DeclContext *DC = computeDeclContext(SS, false)) 4181 Diag(IdentLoc, diag::err_using_directive_member_suggest) 4182 << Ident << DC << Corrected << SS.getRange() 4183 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4184 else 4185 Diag(IdentLoc, diag::err_using_directive_suggest) 4186 << Ident << Corrected 4187 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4188 4189 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 4190 << Corrected; 4191 4192 Ident = Corrected.getAsIdentifierInfo(); 4193 } else { 4194 R.clear(); 4195 R.setLookupName(Ident); 4196 } 4197 } 4198 4199 if (R.empty()) { 4200 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 4201 return 0; 4202 } 4203 } 4204 4205 NamespaceAliasDecl *AliasDecl = 4206 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 4207 Alias, SS.getRange(), 4208 (NestedNameSpecifier *)SS.getScopeRep(), 4209 IdentLoc, R.getFoundDecl()); 4210 4211 PushOnScopeChains(AliasDecl, S); 4212 return AliasDecl; 4213} 4214 4215namespace { 4216 /// \brief Scoped object used to handle the state changes required in Sema 4217 /// to implicitly define the body of a C++ member function; 4218 class ImplicitlyDefinedFunctionScope { 4219 Sema &S; 4220 DeclContext *PreviousContext; 4221 4222 public: 4223 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 4224 : S(S), PreviousContext(S.CurContext) 4225 { 4226 S.CurContext = Method; 4227 S.PushFunctionScope(); 4228 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 4229 } 4230 4231 ~ImplicitlyDefinedFunctionScope() { 4232 S.PopExpressionEvaluationContext(); 4233 S.PopFunctionOrBlockScope(); 4234 S.CurContext = PreviousContext; 4235 } 4236 }; 4237} 4238 4239static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self, 4240 CXXRecordDecl *D) { 4241 ASTContext &Context = Self.Context; 4242 QualType ClassType = Context.getTypeDeclType(D); 4243 DeclarationName ConstructorName 4244 = Context.DeclarationNames.getCXXConstructorName( 4245 Context.getCanonicalType(ClassType.getUnqualifiedType())); 4246 4247 DeclContext::lookup_const_iterator Con, ConEnd; 4248 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 4249 Con != ConEnd; ++Con) { 4250 // FIXME: In C++0x, a constructor template can be a default constructor. 4251 if (isa<FunctionTemplateDecl>(*Con)) 4252 continue; 4253 4254 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 4255 if (Constructor->isDefaultConstructor()) 4256 return Constructor; 4257 } 4258 return 0; 4259} 4260 4261CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 4262 CXXRecordDecl *ClassDecl) { 4263 // C++ [class.ctor]p5: 4264 // A default constructor for a class X is a constructor of class X 4265 // that can be called without an argument. If there is no 4266 // user-declared constructor for class X, a default constructor is 4267 // implicitly declared. An implicitly-declared default constructor 4268 // is an inline public member of its class. 4269 assert(!ClassDecl->hasUserDeclaredConstructor() && 4270 "Should not build implicit default constructor!"); 4271 4272 // C++ [except.spec]p14: 4273 // An implicitly declared special member function (Clause 12) shall have an 4274 // exception-specification. [...] 4275 ImplicitExceptionSpecification ExceptSpec(Context); 4276 4277 // Direct base-class destructors. 4278 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4279 BEnd = ClassDecl->bases_end(); 4280 B != BEnd; ++B) { 4281 if (B->isVirtual()) // Handled below. 4282 continue; 4283 4284 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4285 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4286 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4287 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4288 else if (CXXConstructorDecl *Constructor 4289 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4290 ExceptSpec.CalledDecl(Constructor); 4291 } 4292 } 4293 4294 // Virtual base-class destructors. 4295 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4296 BEnd = ClassDecl->vbases_end(); 4297 B != BEnd; ++B) { 4298 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4299 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4300 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4301 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4302 else if (CXXConstructorDecl *Constructor 4303 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4304 ExceptSpec.CalledDecl(Constructor); 4305 } 4306 } 4307 4308 // Field destructors. 4309 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4310 FEnd = ClassDecl->field_end(); 4311 F != FEnd; ++F) { 4312 if (const RecordType *RecordTy 4313 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4314 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4315 if (!FieldClassDecl->hasDeclaredDefaultConstructor()) 4316 ExceptSpec.CalledDecl( 4317 DeclareImplicitDefaultConstructor(FieldClassDecl)); 4318 else if (CXXConstructorDecl *Constructor 4319 = getDefaultConstructorUnsafe(*this, FieldClassDecl)) 4320 ExceptSpec.CalledDecl(Constructor); 4321 } 4322 } 4323 4324 4325 // Create the actual constructor declaration. 4326 CanQualType ClassType 4327 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4328 DeclarationName Name 4329 = Context.DeclarationNames.getCXXConstructorName(ClassType); 4330 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 4331 CXXConstructorDecl *DefaultCon 4332 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo, 4333 Context.getFunctionType(Context.VoidTy, 4334 0, 0, false, 0, 4335 ExceptSpec.hasExceptionSpecification(), 4336 ExceptSpec.hasAnyExceptionSpecification(), 4337 ExceptSpec.size(), 4338 ExceptSpec.data(), 4339 FunctionType::ExtInfo()), 4340 /*TInfo=*/0, 4341 /*isExplicit=*/false, 4342 /*isInline=*/true, 4343 /*isImplicitlyDeclared=*/true); 4344 DefaultCon->setAccess(AS_public); 4345 DefaultCon->setImplicit(); 4346 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 4347 4348 // Note that we have declared this constructor. 4349 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 4350 4351 if (Scope *S = getScopeForContext(ClassDecl)) 4352 PushOnScopeChains(DefaultCon, S, false); 4353 ClassDecl->addDecl(DefaultCon); 4354 4355 return DefaultCon; 4356} 4357 4358void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4359 CXXConstructorDecl *Constructor) { 4360 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4361 !Constructor->isUsed(false)) && 4362 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4363 4364 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4365 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4366 4367 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 4368 ErrorTrap Trap(*this); 4369 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 4370 Trap.hasErrorOccurred()) { 4371 Diag(CurrentLocation, diag::note_member_synthesized_at) 4372 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4373 Constructor->setInvalidDecl(); 4374 return; 4375 } 4376 4377 SourceLocation Loc = Constructor->getLocation(); 4378 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4379 4380 Constructor->setUsed(); 4381 MarkVTableUsed(CurrentLocation, ClassDecl); 4382} 4383 4384CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 4385 // C++ [class.dtor]p2: 4386 // If a class has no user-declared destructor, a destructor is 4387 // declared implicitly. An implicitly-declared destructor is an 4388 // inline public member of its class. 4389 4390 // C++ [except.spec]p14: 4391 // An implicitly declared special member function (Clause 12) shall have 4392 // an exception-specification. 4393 ImplicitExceptionSpecification ExceptSpec(Context); 4394 4395 // Direct base-class destructors. 4396 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4397 BEnd = ClassDecl->bases_end(); 4398 B != BEnd; ++B) { 4399 if (B->isVirtual()) // Handled below. 4400 continue; 4401 4402 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 4403 ExceptSpec.CalledDecl( 4404 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 4405 } 4406 4407 // Virtual base-class destructors. 4408 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4409 BEnd = ClassDecl->vbases_end(); 4410 B != BEnd; ++B) { 4411 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 4412 ExceptSpec.CalledDecl( 4413 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 4414 } 4415 4416 // Field destructors. 4417 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4418 FEnd = ClassDecl->field_end(); 4419 F != FEnd; ++F) { 4420 if (const RecordType *RecordTy 4421 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 4422 ExceptSpec.CalledDecl( 4423 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 4424 } 4425 4426 // Create the actual destructor declaration. 4427 QualType Ty = Context.getFunctionType(Context.VoidTy, 4428 0, 0, false, 0, 4429 ExceptSpec.hasExceptionSpecification(), 4430 ExceptSpec.hasAnyExceptionSpecification(), 4431 ExceptSpec.size(), 4432 ExceptSpec.data(), 4433 FunctionType::ExtInfo()); 4434 4435 CanQualType ClassType 4436 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4437 DeclarationName Name 4438 = Context.DeclarationNames.getCXXDestructorName(ClassType); 4439 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 4440 CXXDestructorDecl *Destructor 4441 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty, 0, 4442 /*isInline=*/true, 4443 /*isImplicitlyDeclared=*/true); 4444 Destructor->setAccess(AS_public); 4445 Destructor->setImplicit(); 4446 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 4447 4448 // Note that we have declared this destructor. 4449 ++ASTContext::NumImplicitDestructorsDeclared; 4450 4451 // Introduce this destructor into its scope. 4452 if (Scope *S = getScopeForContext(ClassDecl)) 4453 PushOnScopeChains(Destructor, S, false); 4454 ClassDecl->addDecl(Destructor); 4455 4456 // This could be uniqued if it ever proves significant. 4457 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 4458 4459 AddOverriddenMethods(ClassDecl, Destructor); 4460 4461 return Destructor; 4462} 4463 4464void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 4465 CXXDestructorDecl *Destructor) { 4466 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) && 4467 "DefineImplicitDestructor - call it for implicit default dtor"); 4468 CXXRecordDecl *ClassDecl = Destructor->getParent(); 4469 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 4470 4471 if (Destructor->isInvalidDecl()) 4472 return; 4473 4474 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 4475 4476 ErrorTrap Trap(*this); 4477 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 4478 Destructor->getParent()); 4479 4480 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 4481 Diag(CurrentLocation, diag::note_member_synthesized_at) 4482 << CXXDestructor << Context.getTagDeclType(ClassDecl); 4483 4484 Destructor->setInvalidDecl(); 4485 return; 4486 } 4487 4488 SourceLocation Loc = Destructor->getLocation(); 4489 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4490 4491 Destructor->setUsed(); 4492 MarkVTableUsed(CurrentLocation, ClassDecl); 4493} 4494 4495/// \brief Builds a statement that copies the given entity from \p From to 4496/// \c To. 4497/// 4498/// This routine is used to copy the members of a class with an 4499/// implicitly-declared copy assignment operator. When the entities being 4500/// copied are arrays, this routine builds for loops to copy them. 4501/// 4502/// \param S The Sema object used for type-checking. 4503/// 4504/// \param Loc The location where the implicit copy is being generated. 4505/// 4506/// \param T The type of the expressions being copied. Both expressions must 4507/// have this type. 4508/// 4509/// \param To The expression we are copying to. 4510/// 4511/// \param From The expression we are copying from. 4512/// 4513/// \param CopyingBaseSubobject Whether we're copying a base subobject. 4514/// Otherwise, it's a non-static member subobject. 4515/// 4516/// \param Depth Internal parameter recording the depth of the recursion. 4517/// 4518/// \returns A statement or a loop that copies the expressions. 4519static StmtResult 4520BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 4521 Expr *To, Expr *From, 4522 bool CopyingBaseSubobject, unsigned Depth = 0) { 4523 // C++0x [class.copy]p30: 4524 // Each subobject is assigned in the manner appropriate to its type: 4525 // 4526 // - if the subobject is of class type, the copy assignment operator 4527 // for the class is used (as if by explicit qualification; that is, 4528 // ignoring any possible virtual overriding functions in more derived 4529 // classes); 4530 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 4531 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4532 4533 // Look for operator=. 4534 DeclarationName Name 4535 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4536 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 4537 S.LookupQualifiedName(OpLookup, ClassDecl, false); 4538 4539 // Filter out any result that isn't a copy-assignment operator. 4540 LookupResult::Filter F = OpLookup.makeFilter(); 4541 while (F.hasNext()) { 4542 NamedDecl *D = F.next(); 4543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 4544 if (Method->isCopyAssignmentOperator()) 4545 continue; 4546 4547 F.erase(); 4548 } 4549 F.done(); 4550 4551 // Suppress the protected check (C++ [class.protected]) for each of the 4552 // assignment operators we found. This strange dance is required when 4553 // we're assigning via a base classes's copy-assignment operator. To 4554 // ensure that we're getting the right base class subobject (without 4555 // ambiguities), we need to cast "this" to that subobject type; to 4556 // ensure that we don't go through the virtual call mechanism, we need 4557 // to qualify the operator= name with the base class (see below). However, 4558 // this means that if the base class has a protected copy assignment 4559 // operator, the protected member access check will fail. So, we 4560 // rewrite "protected" access to "public" access in this case, since we 4561 // know by construction that we're calling from a derived class. 4562 if (CopyingBaseSubobject) { 4563 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 4564 L != LEnd; ++L) { 4565 if (L.getAccess() == AS_protected) 4566 L.setAccess(AS_public); 4567 } 4568 } 4569 4570 // Create the nested-name-specifier that will be used to qualify the 4571 // reference to operator=; this is required to suppress the virtual 4572 // call mechanism. 4573 CXXScopeSpec SS; 4574 SS.setRange(Loc); 4575 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false, 4576 T.getTypePtr())); 4577 4578 // Create the reference to operator=. 4579 ExprResult OpEqualRef 4580 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 4581 /*FirstQualifierInScope=*/0, OpLookup, 4582 /*TemplateArgs=*/0, 4583 /*SuppressQualifierCheck=*/true); 4584 if (OpEqualRef.isInvalid()) 4585 return StmtError(); 4586 4587 // Build the call to the assignment operator. 4588 4589 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 4590 OpEqualRef.takeAs<Expr>(), 4591 Loc, &From, 1, Loc); 4592 if (Call.isInvalid()) 4593 return StmtError(); 4594 4595 return S.Owned(Call.takeAs<Stmt>()); 4596 } 4597 4598 // - if the subobject is of scalar type, the built-in assignment 4599 // operator is used. 4600 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 4601 if (!ArrayTy) { 4602 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 4603 if (Assignment.isInvalid()) 4604 return StmtError(); 4605 4606 return S.Owned(Assignment.takeAs<Stmt>()); 4607 } 4608 4609 // - if the subobject is an array, each element is assigned, in the 4610 // manner appropriate to the element type; 4611 4612 // Construct a loop over the array bounds, e.g., 4613 // 4614 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 4615 // 4616 // that will copy each of the array elements. 4617 QualType SizeType = S.Context.getSizeType(); 4618 4619 // Create the iteration variable. 4620 IdentifierInfo *IterationVarName = 0; 4621 { 4622 llvm::SmallString<8> Str; 4623 llvm::raw_svector_ostream OS(Str); 4624 OS << "__i" << Depth; 4625 IterationVarName = &S.Context.Idents.get(OS.str()); 4626 } 4627 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, 4628 IterationVarName, SizeType, 4629 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 4630 SC_None, SC_None); 4631 4632 // Initialize the iteration variable to zero. 4633 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 4634 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 4635 4636 // Create a reference to the iteration variable; we'll use this several 4637 // times throughout. 4638 Expr *IterationVarRef 4639 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 4640 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 4641 4642 // Create the DeclStmt that holds the iteration variable. 4643 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 4644 4645 // Create the comparison against the array bound. 4646 llvm::APInt Upper = ArrayTy->getSize(); 4647 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType)); 4648 Expr *Comparison 4649 = new (S.Context) BinaryOperator(IterationVarRef, 4650 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 4651 BO_NE, S.Context.BoolTy, 4652 VK_RValue, OK_Ordinary, Loc); 4653 4654 // Create the pre-increment of the iteration variable. 4655 Expr *Increment 4656 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 4657 VK_LValue, OK_Ordinary, Loc); 4658 4659 // Subscript the "from" and "to" expressions with the iteration variable. 4660 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 4661 IterationVarRef, Loc)); 4662 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 4663 IterationVarRef, Loc)); 4664 4665 // Build the copy for an individual element of the array. 4666 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 4667 To, From, CopyingBaseSubobject, 4668 Depth + 1); 4669 if (Copy.isInvalid()) 4670 return StmtError(); 4671 4672 // Construct the loop that copies all elements of this array. 4673 return S.ActOnForStmt(Loc, Loc, InitStmt, 4674 S.MakeFullExpr(Comparison), 4675 0, S.MakeFullExpr(Increment), 4676 Loc, Copy.take()); 4677} 4678 4679/// \brief Determine whether the given class has a copy assignment operator 4680/// that accepts a const-qualified argument. 4681static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) { 4682 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass); 4683 4684 if (!Class->hasDeclaredCopyAssignment()) 4685 S.DeclareImplicitCopyAssignment(Class); 4686 4687 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)); 4688 DeclarationName OpName 4689 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4690 4691 DeclContext::lookup_const_iterator Op, OpEnd; 4692 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) { 4693 // C++ [class.copy]p9: 4694 // A user-declared copy assignment operator is a non-static non-template 4695 // member function of class X with exactly one parameter of type X, X&, 4696 // const X&, volatile X& or const volatile X&. 4697 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op); 4698 if (!Method) 4699 continue; 4700 4701 if (Method->isStatic()) 4702 continue; 4703 if (Method->getPrimaryTemplate()) 4704 continue; 4705 const FunctionProtoType *FnType = 4706 Method->getType()->getAs<FunctionProtoType>(); 4707 assert(FnType && "Overloaded operator has no prototype."); 4708 // Don't assert on this; an invalid decl might have been left in the AST. 4709 if (FnType->getNumArgs() != 1 || FnType->isVariadic()) 4710 continue; 4711 bool AcceptsConst = true; 4712 QualType ArgType = FnType->getArgType(0); 4713 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){ 4714 ArgType = Ref->getPointeeType(); 4715 // Is it a non-const lvalue reference? 4716 if (!ArgType.isConstQualified()) 4717 AcceptsConst = false; 4718 } 4719 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType)) 4720 continue; 4721 4722 // We have a single argument of type cv X or cv X&, i.e. we've found the 4723 // copy assignment operator. Return whether it accepts const arguments. 4724 return AcceptsConst; 4725 } 4726 assert(Class->isInvalidDecl() && 4727 "No copy assignment operator declared in valid code."); 4728 return false; 4729} 4730 4731CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 4732 // Note: The following rules are largely analoguous to the copy 4733 // constructor rules. Note that virtual bases are not taken into account 4734 // for determining the argument type of the operator. Note also that 4735 // operators taking an object instead of a reference are allowed. 4736 4737 4738 // C++ [class.copy]p10: 4739 // If the class definition does not explicitly declare a copy 4740 // assignment operator, one is declared implicitly. 4741 // The implicitly-defined copy assignment operator for a class X 4742 // will have the form 4743 // 4744 // X& X::operator=(const X&) 4745 // 4746 // if 4747 bool HasConstCopyAssignment = true; 4748 4749 // -- each direct base class B of X has a copy assignment operator 4750 // whose parameter is of type const B&, const volatile B& or B, 4751 // and 4752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4753 BaseEnd = ClassDecl->bases_end(); 4754 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 4755 assert(!Base->getType()->isDependentType() && 4756 "Cannot generate implicit members for class with dependent bases."); 4757 const CXXRecordDecl *BaseClassDecl 4758 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 4759 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl); 4760 } 4761 4762 // -- for all the nonstatic data members of X that are of a class 4763 // type M (or array thereof), each such class type has a copy 4764 // assignment operator whose parameter is of type const M&, 4765 // const volatile M& or M. 4766 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4767 FieldEnd = ClassDecl->field_end(); 4768 HasConstCopyAssignment && Field != FieldEnd; 4769 ++Field) { 4770 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 4771 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 4772 const CXXRecordDecl *FieldClassDecl 4773 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 4774 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl); 4775 } 4776 } 4777 4778 // Otherwise, the implicitly declared copy assignment operator will 4779 // have the form 4780 // 4781 // X& X::operator=(X&) 4782 QualType ArgType = Context.getTypeDeclType(ClassDecl); 4783 QualType RetType = Context.getLValueReferenceType(ArgType); 4784 if (HasConstCopyAssignment) 4785 ArgType = ArgType.withConst(); 4786 ArgType = Context.getLValueReferenceType(ArgType); 4787 4788 // C++ [except.spec]p14: 4789 // An implicitly declared special member function (Clause 12) shall have an 4790 // exception-specification. [...] 4791 ImplicitExceptionSpecification ExceptSpec(Context); 4792 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4793 BaseEnd = ClassDecl->bases_end(); 4794 Base != BaseEnd; ++Base) { 4795 CXXRecordDecl *BaseClassDecl 4796 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 4797 4798 if (!BaseClassDecl->hasDeclaredCopyAssignment()) 4799 DeclareImplicitCopyAssignment(BaseClassDecl); 4800 4801 if (CXXMethodDecl *CopyAssign 4802 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 4803 ExceptSpec.CalledDecl(CopyAssign); 4804 } 4805 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4806 FieldEnd = ClassDecl->field_end(); 4807 Field != FieldEnd; 4808 ++Field) { 4809 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 4810 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 4811 CXXRecordDecl *FieldClassDecl 4812 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 4813 4814 if (!FieldClassDecl->hasDeclaredCopyAssignment()) 4815 DeclareImplicitCopyAssignment(FieldClassDecl); 4816 4817 if (CXXMethodDecl *CopyAssign 4818 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 4819 ExceptSpec.CalledDecl(CopyAssign); 4820 } 4821 } 4822 4823 // An implicitly-declared copy assignment operator is an inline public 4824 // member of its class. 4825 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4826 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 4827 CXXMethodDecl *CopyAssignment 4828 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo, 4829 Context.getFunctionType(RetType, &ArgType, 1, 4830 false, 0, 4831 ExceptSpec.hasExceptionSpecification(), 4832 ExceptSpec.hasAnyExceptionSpecification(), 4833 ExceptSpec.size(), 4834 ExceptSpec.data(), 4835 FunctionType::ExtInfo()), 4836 /*TInfo=*/0, /*isStatic=*/false, 4837 /*StorageClassAsWritten=*/SC_None, 4838 /*isInline=*/true); 4839 CopyAssignment->setAccess(AS_public); 4840 CopyAssignment->setImplicit(); 4841 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 4842 4843 // Add the parameter to the operator. 4844 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 4845 ClassDecl->getLocation(), 4846 /*Id=*/0, 4847 ArgType, /*TInfo=*/0, 4848 SC_None, 4849 SC_None, 0); 4850 CopyAssignment->setParams(&FromParam, 1); 4851 4852 // Note that we have added this copy-assignment operator. 4853 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 4854 4855 if (Scope *S = getScopeForContext(ClassDecl)) 4856 PushOnScopeChains(CopyAssignment, S, false); 4857 ClassDecl->addDecl(CopyAssignment); 4858 4859 AddOverriddenMethods(ClassDecl, CopyAssignment); 4860 return CopyAssignment; 4861} 4862 4863void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 4864 CXXMethodDecl *CopyAssignOperator) { 4865 assert((CopyAssignOperator->isImplicit() && 4866 CopyAssignOperator->isOverloadedOperator() && 4867 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 4868 !CopyAssignOperator->isUsed(false)) && 4869 "DefineImplicitCopyAssignment called for wrong function"); 4870 4871 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 4872 4873 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 4874 CopyAssignOperator->setInvalidDecl(); 4875 return; 4876 } 4877 4878 CopyAssignOperator->setUsed(); 4879 4880 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 4881 ErrorTrap Trap(*this); 4882 4883 // C++0x [class.copy]p30: 4884 // The implicitly-defined or explicitly-defaulted copy assignment operator 4885 // for a non-union class X performs memberwise copy assignment of its 4886 // subobjects. The direct base classes of X are assigned first, in the 4887 // order of their declaration in the base-specifier-list, and then the 4888 // immediate non-static data members of X are assigned, in the order in 4889 // which they were declared in the class definition. 4890 4891 // The statements that form the synthesized function body. 4892 ASTOwningVector<Stmt*> Statements(*this); 4893 4894 // The parameter for the "other" object, which we are copying from. 4895 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 4896 Qualifiers OtherQuals = Other->getType().getQualifiers(); 4897 QualType OtherRefType = Other->getType(); 4898 if (const LValueReferenceType *OtherRef 4899 = OtherRefType->getAs<LValueReferenceType>()) { 4900 OtherRefType = OtherRef->getPointeeType(); 4901 OtherQuals = OtherRefType.getQualifiers(); 4902 } 4903 4904 // Our location for everything implicitly-generated. 4905 SourceLocation Loc = CopyAssignOperator->getLocation(); 4906 4907 // Construct a reference to the "other" object. We'll be using this 4908 // throughout the generated ASTs. 4909 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 4910 assert(OtherRef && "Reference to parameter cannot fail!"); 4911 4912 // Construct the "this" pointer. We'll be using this throughout the generated 4913 // ASTs. 4914 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 4915 assert(This && "Reference to this cannot fail!"); 4916 4917 // Assign base classes. 4918 bool Invalid = false; 4919 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4920 E = ClassDecl->bases_end(); Base != E; ++Base) { 4921 // Form the assignment: 4922 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 4923 QualType BaseType = Base->getType().getUnqualifiedType(); 4924 CXXRecordDecl *BaseClassDecl = 0; 4925 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>()) 4926 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl()); 4927 else { 4928 Invalid = true; 4929 continue; 4930 } 4931 4932 CXXCastPath BasePath; 4933 BasePath.push_back(Base); 4934 4935 // Construct the "from" expression, which is an implicit cast to the 4936 // appropriately-qualified base type. 4937 Expr *From = OtherRef; 4938 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 4939 CK_UncheckedDerivedToBase, 4940 VK_LValue, &BasePath); 4941 4942 // Dereference "this". 4943 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 4944 4945 // Implicitly cast "this" to the appropriately-qualified base type. 4946 Expr *ToE = To.takeAs<Expr>(); 4947 ImpCastExprToType(ToE, 4948 Context.getCVRQualifiedType(BaseType, 4949 CopyAssignOperator->getTypeQualifiers()), 4950 CK_UncheckedDerivedToBase, 4951 VK_LValue, &BasePath); 4952 To = Owned(ToE); 4953 4954 // Build the copy. 4955 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 4956 To.get(), From, 4957 /*CopyingBaseSubobject=*/true); 4958 if (Copy.isInvalid()) { 4959 Diag(CurrentLocation, diag::note_member_synthesized_at) 4960 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4961 CopyAssignOperator->setInvalidDecl(); 4962 return; 4963 } 4964 4965 // Success! Record the copy. 4966 Statements.push_back(Copy.takeAs<Expr>()); 4967 } 4968 4969 // \brief Reference to the __builtin_memcpy function. 4970 Expr *BuiltinMemCpyRef = 0; 4971 // \brief Reference to the __builtin_objc_memmove_collectable function. 4972 Expr *CollectableMemCpyRef = 0; 4973 4974 // Assign non-static members. 4975 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4976 FieldEnd = ClassDecl->field_end(); 4977 Field != FieldEnd; ++Field) { 4978 // Check for members of reference type; we can't copy those. 4979 if (Field->getType()->isReferenceType()) { 4980 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4981 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 4982 Diag(Field->getLocation(), diag::note_declared_at); 4983 Diag(CurrentLocation, diag::note_member_synthesized_at) 4984 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4985 Invalid = true; 4986 continue; 4987 } 4988 4989 // Check for members of const-qualified, non-class type. 4990 QualType BaseType = Context.getBaseElementType(Field->getType()); 4991 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 4992 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4993 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 4994 Diag(Field->getLocation(), diag::note_declared_at); 4995 Diag(CurrentLocation, diag::note_member_synthesized_at) 4996 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4997 Invalid = true; 4998 continue; 4999 } 5000 5001 QualType FieldType = Field->getType().getNonReferenceType(); 5002 if (FieldType->isIncompleteArrayType()) { 5003 assert(ClassDecl->hasFlexibleArrayMember() && 5004 "Incomplete array type is not valid"); 5005 continue; 5006 } 5007 5008 // Build references to the field in the object we're copying from and to. 5009 CXXScopeSpec SS; // Intentionally empty 5010 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 5011 LookupMemberName); 5012 MemberLookup.addDecl(*Field); 5013 MemberLookup.resolveKind(); 5014 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 5015 Loc, /*IsArrow=*/false, 5016 SS, 0, MemberLookup, 0); 5017 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 5018 Loc, /*IsArrow=*/true, 5019 SS, 0, MemberLookup, 0); 5020 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 5021 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 5022 5023 // If the field should be copied with __builtin_memcpy rather than via 5024 // explicit assignments, do so. This optimization only applies for arrays 5025 // of scalars and arrays of class type with trivial copy-assignment 5026 // operators. 5027 if (FieldType->isArrayType() && 5028 (!BaseType->isRecordType() || 5029 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 5030 ->hasTrivialCopyAssignment())) { 5031 // Compute the size of the memory buffer to be copied. 5032 QualType SizeType = Context.getSizeType(); 5033 llvm::APInt Size(Context.getTypeSize(SizeType), 5034 Context.getTypeSizeInChars(BaseType).getQuantity()); 5035 for (const ConstantArrayType *Array 5036 = Context.getAsConstantArrayType(FieldType); 5037 Array; 5038 Array = Context.getAsConstantArrayType(Array->getElementType())) { 5039 llvm::APInt ArraySize = Array->getSize(); 5040 ArraySize.zextOrTrunc(Size.getBitWidth()); 5041 Size *= ArraySize; 5042 } 5043 5044 // Take the address of the field references for "from" and "to". 5045 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 5046 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 5047 5048 bool NeedsCollectableMemCpy = 5049 (BaseType->isRecordType() && 5050 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 5051 5052 if (NeedsCollectableMemCpy) { 5053 if (!CollectableMemCpyRef) { 5054 // Create a reference to the __builtin_objc_memmove_collectable function. 5055 LookupResult R(*this, 5056 &Context.Idents.get("__builtin_objc_memmove_collectable"), 5057 Loc, LookupOrdinaryName); 5058 LookupName(R, TUScope, true); 5059 5060 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 5061 if (!CollectableMemCpy) { 5062 // Something went horribly wrong earlier, and we will have 5063 // complained about it. 5064 Invalid = true; 5065 continue; 5066 } 5067 5068 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 5069 CollectableMemCpy->getType(), 5070 VK_LValue, Loc, 0).take(); 5071 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 5072 } 5073 } 5074 // Create a reference to the __builtin_memcpy builtin function. 5075 else if (!BuiltinMemCpyRef) { 5076 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 5077 LookupOrdinaryName); 5078 LookupName(R, TUScope, true); 5079 5080 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 5081 if (!BuiltinMemCpy) { 5082 // Something went horribly wrong earlier, and we will have complained 5083 // about it. 5084 Invalid = true; 5085 continue; 5086 } 5087 5088 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 5089 BuiltinMemCpy->getType(), 5090 VK_LValue, Loc, 0).take(); 5091 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 5092 } 5093 5094 ASTOwningVector<Expr*> CallArgs(*this); 5095 CallArgs.push_back(To.takeAs<Expr>()); 5096 CallArgs.push_back(From.takeAs<Expr>()); 5097 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 5098 ExprResult Call = ExprError(); 5099 if (NeedsCollectableMemCpy) 5100 Call = ActOnCallExpr(/*Scope=*/0, 5101 CollectableMemCpyRef, 5102 Loc, move_arg(CallArgs), 5103 Loc); 5104 else 5105 Call = ActOnCallExpr(/*Scope=*/0, 5106 BuiltinMemCpyRef, 5107 Loc, move_arg(CallArgs), 5108 Loc); 5109 5110 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 5111 Statements.push_back(Call.takeAs<Expr>()); 5112 continue; 5113 } 5114 5115 // Build the copy of this field. 5116 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 5117 To.get(), From.get(), 5118 /*CopyingBaseSubobject=*/false); 5119 if (Copy.isInvalid()) { 5120 Diag(CurrentLocation, diag::note_member_synthesized_at) 5121 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5122 CopyAssignOperator->setInvalidDecl(); 5123 return; 5124 } 5125 5126 // Success! Record the copy. 5127 Statements.push_back(Copy.takeAs<Stmt>()); 5128 } 5129 5130 if (!Invalid) { 5131 // Add a "return *this;" 5132 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5133 5134 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 5135 if (Return.isInvalid()) 5136 Invalid = true; 5137 else { 5138 Statements.push_back(Return.takeAs<Stmt>()); 5139 5140 if (Trap.hasErrorOccurred()) { 5141 Diag(CurrentLocation, diag::note_member_synthesized_at) 5142 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5143 Invalid = true; 5144 } 5145 } 5146 } 5147 5148 if (Invalid) { 5149 CopyAssignOperator->setInvalidDecl(); 5150 return; 5151 } 5152 5153 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 5154 /*isStmtExpr=*/false); 5155 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 5156 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 5157} 5158 5159CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 5160 CXXRecordDecl *ClassDecl) { 5161 // C++ [class.copy]p4: 5162 // If the class definition does not explicitly declare a copy 5163 // constructor, one is declared implicitly. 5164 5165 // C++ [class.copy]p5: 5166 // The implicitly-declared copy constructor for a class X will 5167 // have the form 5168 // 5169 // X::X(const X&) 5170 // 5171 // if 5172 bool HasConstCopyConstructor = true; 5173 5174 // -- each direct or virtual base class B of X has a copy 5175 // constructor whose first parameter is of type const B& or 5176 // const volatile B&, and 5177 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5178 BaseEnd = ClassDecl->bases_end(); 5179 HasConstCopyConstructor && Base != BaseEnd; 5180 ++Base) { 5181 // Virtual bases are handled below. 5182 if (Base->isVirtual()) 5183 continue; 5184 5185 CXXRecordDecl *BaseClassDecl 5186 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5187 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5188 DeclareImplicitCopyConstructor(BaseClassDecl); 5189 5190 HasConstCopyConstructor 5191 = BaseClassDecl->hasConstCopyConstructor(Context); 5192 } 5193 5194 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5195 BaseEnd = ClassDecl->vbases_end(); 5196 HasConstCopyConstructor && Base != BaseEnd; 5197 ++Base) { 5198 CXXRecordDecl *BaseClassDecl 5199 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5200 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5201 DeclareImplicitCopyConstructor(BaseClassDecl); 5202 5203 HasConstCopyConstructor 5204 = BaseClassDecl->hasConstCopyConstructor(Context); 5205 } 5206 5207 // -- for all the nonstatic data members of X that are of a 5208 // class type M (or array thereof), each such class type 5209 // has a copy constructor whose first parameter is of type 5210 // const M& or const volatile M&. 5211 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5212 FieldEnd = ClassDecl->field_end(); 5213 HasConstCopyConstructor && Field != FieldEnd; 5214 ++Field) { 5215 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5216 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5217 CXXRecordDecl *FieldClassDecl 5218 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5219 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5220 DeclareImplicitCopyConstructor(FieldClassDecl); 5221 5222 HasConstCopyConstructor 5223 = FieldClassDecl->hasConstCopyConstructor(Context); 5224 } 5225 } 5226 5227 // Otherwise, the implicitly declared copy constructor will have 5228 // the form 5229 // 5230 // X::X(X&) 5231 QualType ClassType = Context.getTypeDeclType(ClassDecl); 5232 QualType ArgType = ClassType; 5233 if (HasConstCopyConstructor) 5234 ArgType = ArgType.withConst(); 5235 ArgType = Context.getLValueReferenceType(ArgType); 5236 5237 // C++ [except.spec]p14: 5238 // An implicitly declared special member function (Clause 12) shall have an 5239 // exception-specification. [...] 5240 ImplicitExceptionSpecification ExceptSpec(Context); 5241 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 5242 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5243 BaseEnd = ClassDecl->bases_end(); 5244 Base != BaseEnd; 5245 ++Base) { 5246 // Virtual bases are handled below. 5247 if (Base->isVirtual()) 5248 continue; 5249 5250 CXXRecordDecl *BaseClassDecl 5251 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5252 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5253 DeclareImplicitCopyConstructor(BaseClassDecl); 5254 5255 if (CXXConstructorDecl *CopyConstructor 5256 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5257 ExceptSpec.CalledDecl(CopyConstructor); 5258 } 5259 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5260 BaseEnd = ClassDecl->vbases_end(); 5261 Base != BaseEnd; 5262 ++Base) { 5263 CXXRecordDecl *BaseClassDecl 5264 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5265 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5266 DeclareImplicitCopyConstructor(BaseClassDecl); 5267 5268 if (CXXConstructorDecl *CopyConstructor 5269 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5270 ExceptSpec.CalledDecl(CopyConstructor); 5271 } 5272 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5273 FieldEnd = ClassDecl->field_end(); 5274 Field != FieldEnd; 5275 ++Field) { 5276 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5277 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5278 CXXRecordDecl *FieldClassDecl 5279 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5280 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5281 DeclareImplicitCopyConstructor(FieldClassDecl); 5282 5283 if (CXXConstructorDecl *CopyConstructor 5284 = FieldClassDecl->getCopyConstructor(Context, Quals)) 5285 ExceptSpec.CalledDecl(CopyConstructor); 5286 } 5287 } 5288 5289 // An implicitly-declared copy constructor is an inline public 5290 // member of its class. 5291 DeclarationName Name 5292 = Context.DeclarationNames.getCXXConstructorName( 5293 Context.getCanonicalType(ClassType)); 5294 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation()); 5295 CXXConstructorDecl *CopyConstructor 5296 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo, 5297 Context.getFunctionType(Context.VoidTy, 5298 &ArgType, 1, 5299 false, 0, 5300 ExceptSpec.hasExceptionSpecification(), 5301 ExceptSpec.hasAnyExceptionSpecification(), 5302 ExceptSpec.size(), 5303 ExceptSpec.data(), 5304 FunctionType::ExtInfo()), 5305 /*TInfo=*/0, 5306 /*isExplicit=*/false, 5307 /*isInline=*/true, 5308 /*isImplicitlyDeclared=*/true); 5309 CopyConstructor->setAccess(AS_public); 5310 CopyConstructor->setImplicit(); 5311 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 5312 5313 // Note that we have declared this constructor. 5314 ++ASTContext::NumImplicitCopyConstructorsDeclared; 5315 5316 // Add the parameter to the constructor. 5317 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 5318 ClassDecl->getLocation(), 5319 /*IdentifierInfo=*/0, 5320 ArgType, /*TInfo=*/0, 5321 SC_None, 5322 SC_None, 0); 5323 CopyConstructor->setParams(&FromParam, 1); 5324 if (Scope *S = getScopeForContext(ClassDecl)) 5325 PushOnScopeChains(CopyConstructor, S, false); 5326 ClassDecl->addDecl(CopyConstructor); 5327 5328 return CopyConstructor; 5329} 5330 5331void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5332 CXXConstructorDecl *CopyConstructor, 5333 unsigned TypeQuals) { 5334 assert((CopyConstructor->isImplicit() && 5335 CopyConstructor->isCopyConstructor(TypeQuals) && 5336 !CopyConstructor->isUsed(false)) && 5337 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 5338 5339 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 5340 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 5341 5342 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 5343 ErrorTrap Trap(*this); 5344 5345 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 5346 Trap.hasErrorOccurred()) { 5347 Diag(CurrentLocation, diag::note_member_synthesized_at) 5348 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 5349 CopyConstructor->setInvalidDecl(); 5350 } else { 5351 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 5352 CopyConstructor->getLocation(), 5353 MultiStmtArg(*this, 0, 0), 5354 /*isStmtExpr=*/false) 5355 .takeAs<Stmt>()); 5356 } 5357 5358 CopyConstructor->setUsed(); 5359} 5360 5361ExprResult 5362Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5363 CXXConstructorDecl *Constructor, 5364 MultiExprArg ExprArgs, 5365 bool RequiresZeroInit, 5366 unsigned ConstructKind, 5367 SourceRange ParenRange) { 5368 bool Elidable = false; 5369 5370 // C++0x [class.copy]p34: 5371 // When certain criteria are met, an implementation is allowed to 5372 // omit the copy/move construction of a class object, even if the 5373 // copy/move constructor and/or destructor for the object have 5374 // side effects. [...] 5375 // - when a temporary class object that has not been bound to a 5376 // reference (12.2) would be copied/moved to a class object 5377 // with the same cv-unqualified type, the copy/move operation 5378 // can be omitted by constructing the temporary object 5379 // directly into the target of the omitted copy/move 5380 if (ConstructKind == CXXConstructExpr::CK_Complete && 5381 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) { 5382 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 5383 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 5384 } 5385 5386 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 5387 Elidable, move(ExprArgs), RequiresZeroInit, 5388 ConstructKind, ParenRange); 5389} 5390 5391/// BuildCXXConstructExpr - Creates a complete call to a constructor, 5392/// including handling of its default argument expressions. 5393ExprResult 5394Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5395 CXXConstructorDecl *Constructor, bool Elidable, 5396 MultiExprArg ExprArgs, 5397 bool RequiresZeroInit, 5398 unsigned ConstructKind, 5399 SourceRange ParenRange) { 5400 unsigned NumExprs = ExprArgs.size(); 5401 Expr **Exprs = (Expr **)ExprArgs.release(); 5402 5403 MarkDeclarationReferenced(ConstructLoc, Constructor); 5404 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 5405 Constructor, Elidable, Exprs, NumExprs, 5406 RequiresZeroInit, 5407 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 5408 ParenRange)); 5409} 5410 5411bool Sema::InitializeVarWithConstructor(VarDecl *VD, 5412 CXXConstructorDecl *Constructor, 5413 MultiExprArg Exprs) { 5414 // FIXME: Provide the correct paren SourceRange when available. 5415 ExprResult TempResult = 5416 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 5417 move(Exprs), false, CXXConstructExpr::CK_Complete, 5418 SourceRange()); 5419 if (TempResult.isInvalid()) 5420 return true; 5421 5422 Expr *Temp = TempResult.takeAs<Expr>(); 5423 CheckImplicitConversions(Temp, VD->getLocation()); 5424 MarkDeclarationReferenced(VD->getLocation(), Constructor); 5425 Temp = MaybeCreateCXXExprWithTemporaries(Temp); 5426 VD->setInit(Temp); 5427 5428 return false; 5429} 5430 5431void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 5432 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 5433 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 5434 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) { 5435 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 5436 MarkDeclarationReferenced(VD->getLocation(), Destructor); 5437 CheckDestructorAccess(VD->getLocation(), Destructor, 5438 PDiag(diag::err_access_dtor_var) 5439 << VD->getDeclName() 5440 << VD->getType()); 5441 5442 // TODO: this should be re-enabled for static locals by !CXAAtExit 5443 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal()) 5444 Diag(VD->getLocation(), diag::warn_global_destructor); 5445 } 5446} 5447 5448/// AddCXXDirectInitializerToDecl - This action is called immediately after 5449/// ActOnDeclarator, when a C++ direct initializer is present. 5450/// e.g: "int x(1);" 5451void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 5452 SourceLocation LParenLoc, 5453 MultiExprArg Exprs, 5454 SourceLocation RParenLoc) { 5455 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 5456 5457 // If there is no declaration, there was an error parsing it. Just ignore 5458 // the initializer. 5459 if (RealDecl == 0) 5460 return; 5461 5462 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5463 if (!VDecl) { 5464 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5465 RealDecl->setInvalidDecl(); 5466 return; 5467 } 5468 5469 // We will represent direct-initialization similarly to copy-initialization: 5470 // int x(1); -as-> int x = 1; 5471 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 5472 // 5473 // Clients that want to distinguish between the two forms, can check for 5474 // direct initializer using VarDecl::hasCXXDirectInitializer(). 5475 // A major benefit is that clients that don't particularly care about which 5476 // exactly form was it (like the CodeGen) can handle both cases without 5477 // special case code. 5478 5479 // C++ 8.5p11: 5480 // The form of initialization (using parentheses or '=') is generally 5481 // insignificant, but does matter when the entity being initialized has a 5482 // class type. 5483 5484 if (!VDecl->getType()->isDependentType() && 5485 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 5486 diag::err_typecheck_decl_incomplete_type)) { 5487 VDecl->setInvalidDecl(); 5488 return; 5489 } 5490 5491 // The variable can not have an abstract class type. 5492 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5493 diag::err_abstract_type_in_decl, 5494 AbstractVariableType)) 5495 VDecl->setInvalidDecl(); 5496 5497 const VarDecl *Def; 5498 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5499 Diag(VDecl->getLocation(), diag::err_redefinition) 5500 << VDecl->getDeclName(); 5501 Diag(Def->getLocation(), diag::note_previous_definition); 5502 VDecl->setInvalidDecl(); 5503 return; 5504 } 5505 5506 // C++ [class.static.data]p4 5507 // If a static data member is of const integral or const 5508 // enumeration type, its declaration in the class definition can 5509 // specify a constant-initializer which shall be an integral 5510 // constant expression (5.19). In that case, the member can appear 5511 // in integral constant expressions. The member shall still be 5512 // defined in a namespace scope if it is used in the program and the 5513 // namespace scope definition shall not contain an initializer. 5514 // 5515 // We already performed a redefinition check above, but for static 5516 // data members we also need to check whether there was an in-class 5517 // declaration with an initializer. 5518 const VarDecl* PrevInit = 0; 5519 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 5520 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 5521 Diag(PrevInit->getLocation(), diag::note_previous_definition); 5522 return; 5523 } 5524 5525 // If either the declaration has a dependent type or if any of the 5526 // expressions is type-dependent, we represent the initialization 5527 // via a ParenListExpr for later use during template instantiation. 5528 if (VDecl->getType()->isDependentType() || 5529 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 5530 // Let clients know that initialization was done with a direct initializer. 5531 VDecl->setCXXDirectInitializer(true); 5532 5533 // Store the initialization expressions as a ParenListExpr. 5534 unsigned NumExprs = Exprs.size(); 5535 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 5536 (Expr **)Exprs.release(), 5537 NumExprs, RParenLoc)); 5538 return; 5539 } 5540 5541 // Capture the variable that is being initialized and the style of 5542 // initialization. 5543 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 5544 5545 // FIXME: Poor source location information. 5546 InitializationKind Kind 5547 = InitializationKind::CreateDirect(VDecl->getLocation(), 5548 LParenLoc, RParenLoc); 5549 5550 InitializationSequence InitSeq(*this, Entity, Kind, 5551 Exprs.get(), Exprs.size()); 5552 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 5553 if (Result.isInvalid()) { 5554 VDecl->setInvalidDecl(); 5555 return; 5556 } 5557 5558 CheckImplicitConversions(Result.get(), LParenLoc); 5559 5560 Result = MaybeCreateCXXExprWithTemporaries(Result.get()); 5561 VDecl->setInit(Result.takeAs<Expr>()); 5562 VDecl->setCXXDirectInitializer(true); 5563 5564 if (!VDecl->isInvalidDecl() && 5565 !VDecl->getDeclContext()->isDependentContext() && 5566 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() && 5567 !VDecl->getInit()->isConstantInitializer(Context, 5568 VDecl->getType()->isReferenceType())) 5569 Diag(VDecl->getLocation(), diag::warn_global_constructor) 5570 << VDecl->getInit()->getSourceRange(); 5571 5572 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 5573 FinalizeVarWithDestructor(VDecl, Record); 5574} 5575 5576/// \brief Given a constructor and the set of arguments provided for the 5577/// constructor, convert the arguments and add any required default arguments 5578/// to form a proper call to this constructor. 5579/// 5580/// \returns true if an error occurred, false otherwise. 5581bool 5582Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 5583 MultiExprArg ArgsPtr, 5584 SourceLocation Loc, 5585 ASTOwningVector<Expr*> &ConvertedArgs) { 5586 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 5587 unsigned NumArgs = ArgsPtr.size(); 5588 Expr **Args = (Expr **)ArgsPtr.get(); 5589 5590 const FunctionProtoType *Proto 5591 = Constructor->getType()->getAs<FunctionProtoType>(); 5592 assert(Proto && "Constructor without a prototype?"); 5593 unsigned NumArgsInProto = Proto->getNumArgs(); 5594 5595 // If too few arguments are available, we'll fill in the rest with defaults. 5596 if (NumArgs < NumArgsInProto) 5597 ConvertedArgs.reserve(NumArgsInProto); 5598 else 5599 ConvertedArgs.reserve(NumArgs); 5600 5601 VariadicCallType CallType = 5602 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5603 llvm::SmallVector<Expr *, 8> AllArgs; 5604 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 5605 Proto, 0, Args, NumArgs, AllArgs, 5606 CallType); 5607 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 5608 ConvertedArgs.push_back(AllArgs[i]); 5609 return Invalid; 5610} 5611 5612static inline bool 5613CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 5614 const FunctionDecl *FnDecl) { 5615 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 5616 if (isa<NamespaceDecl>(DC)) { 5617 return SemaRef.Diag(FnDecl->getLocation(), 5618 diag::err_operator_new_delete_declared_in_namespace) 5619 << FnDecl->getDeclName(); 5620 } 5621 5622 if (isa<TranslationUnitDecl>(DC) && 5623 FnDecl->getStorageClass() == SC_Static) { 5624 return SemaRef.Diag(FnDecl->getLocation(), 5625 diag::err_operator_new_delete_declared_static) 5626 << FnDecl->getDeclName(); 5627 } 5628 5629 return false; 5630} 5631 5632static inline bool 5633CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 5634 CanQualType ExpectedResultType, 5635 CanQualType ExpectedFirstParamType, 5636 unsigned DependentParamTypeDiag, 5637 unsigned InvalidParamTypeDiag) { 5638 QualType ResultType = 5639 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 5640 5641 // Check that the result type is not dependent. 5642 if (ResultType->isDependentType()) 5643 return SemaRef.Diag(FnDecl->getLocation(), 5644 diag::err_operator_new_delete_dependent_result_type) 5645 << FnDecl->getDeclName() << ExpectedResultType; 5646 5647 // Check that the result type is what we expect. 5648 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 5649 return SemaRef.Diag(FnDecl->getLocation(), 5650 diag::err_operator_new_delete_invalid_result_type) 5651 << FnDecl->getDeclName() << ExpectedResultType; 5652 5653 // A function template must have at least 2 parameters. 5654 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 5655 return SemaRef.Diag(FnDecl->getLocation(), 5656 diag::err_operator_new_delete_template_too_few_parameters) 5657 << FnDecl->getDeclName(); 5658 5659 // The function decl must have at least 1 parameter. 5660 if (FnDecl->getNumParams() == 0) 5661 return SemaRef.Diag(FnDecl->getLocation(), 5662 diag::err_operator_new_delete_too_few_parameters) 5663 << FnDecl->getDeclName(); 5664 5665 // Check the the first parameter type is not dependent. 5666 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 5667 if (FirstParamType->isDependentType()) 5668 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 5669 << FnDecl->getDeclName() << ExpectedFirstParamType; 5670 5671 // Check that the first parameter type is what we expect. 5672 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 5673 ExpectedFirstParamType) 5674 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 5675 << FnDecl->getDeclName() << ExpectedFirstParamType; 5676 5677 return false; 5678} 5679 5680static bool 5681CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 5682 // C++ [basic.stc.dynamic.allocation]p1: 5683 // A program is ill-formed if an allocation function is declared in a 5684 // namespace scope other than global scope or declared static in global 5685 // scope. 5686 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 5687 return true; 5688 5689 CanQualType SizeTy = 5690 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 5691 5692 // C++ [basic.stc.dynamic.allocation]p1: 5693 // The return type shall be void*. The first parameter shall have type 5694 // std::size_t. 5695 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 5696 SizeTy, 5697 diag::err_operator_new_dependent_param_type, 5698 diag::err_operator_new_param_type)) 5699 return true; 5700 5701 // C++ [basic.stc.dynamic.allocation]p1: 5702 // The first parameter shall not have an associated default argument. 5703 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 5704 return SemaRef.Diag(FnDecl->getLocation(), 5705 diag::err_operator_new_default_arg) 5706 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 5707 5708 return false; 5709} 5710 5711static bool 5712CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 5713 // C++ [basic.stc.dynamic.deallocation]p1: 5714 // A program is ill-formed if deallocation functions are declared in a 5715 // namespace scope other than global scope or declared static in global 5716 // scope. 5717 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 5718 return true; 5719 5720 // C++ [basic.stc.dynamic.deallocation]p2: 5721 // Each deallocation function shall return void and its first parameter 5722 // shall be void*. 5723 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 5724 SemaRef.Context.VoidPtrTy, 5725 diag::err_operator_delete_dependent_param_type, 5726 diag::err_operator_delete_param_type)) 5727 return true; 5728 5729 return false; 5730} 5731 5732/// CheckOverloadedOperatorDeclaration - Check whether the declaration 5733/// of this overloaded operator is well-formed. If so, returns false; 5734/// otherwise, emits appropriate diagnostics and returns true. 5735bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 5736 assert(FnDecl && FnDecl->isOverloadedOperator() && 5737 "Expected an overloaded operator declaration"); 5738 5739 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 5740 5741 // C++ [over.oper]p5: 5742 // The allocation and deallocation functions, operator new, 5743 // operator new[], operator delete and operator delete[], are 5744 // described completely in 3.7.3. The attributes and restrictions 5745 // found in the rest of this subclause do not apply to them unless 5746 // explicitly stated in 3.7.3. 5747 if (Op == OO_Delete || Op == OO_Array_Delete) 5748 return CheckOperatorDeleteDeclaration(*this, FnDecl); 5749 5750 if (Op == OO_New || Op == OO_Array_New) 5751 return CheckOperatorNewDeclaration(*this, FnDecl); 5752 5753 // C++ [over.oper]p6: 5754 // An operator function shall either be a non-static member 5755 // function or be a non-member function and have at least one 5756 // parameter whose type is a class, a reference to a class, an 5757 // enumeration, or a reference to an enumeration. 5758 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 5759 if (MethodDecl->isStatic()) 5760 return Diag(FnDecl->getLocation(), 5761 diag::err_operator_overload_static) << FnDecl->getDeclName(); 5762 } else { 5763 bool ClassOrEnumParam = false; 5764 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 5765 ParamEnd = FnDecl->param_end(); 5766 Param != ParamEnd; ++Param) { 5767 QualType ParamType = (*Param)->getType().getNonReferenceType(); 5768 if (ParamType->isDependentType() || ParamType->isRecordType() || 5769 ParamType->isEnumeralType()) { 5770 ClassOrEnumParam = true; 5771 break; 5772 } 5773 } 5774 5775 if (!ClassOrEnumParam) 5776 return Diag(FnDecl->getLocation(), 5777 diag::err_operator_overload_needs_class_or_enum) 5778 << FnDecl->getDeclName(); 5779 } 5780 5781 // C++ [over.oper]p8: 5782 // An operator function cannot have default arguments (8.3.6), 5783 // except where explicitly stated below. 5784 // 5785 // Only the function-call operator allows default arguments 5786 // (C++ [over.call]p1). 5787 if (Op != OO_Call) { 5788 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 5789 Param != FnDecl->param_end(); ++Param) { 5790 if ((*Param)->hasDefaultArg()) 5791 return Diag((*Param)->getLocation(), 5792 diag::err_operator_overload_default_arg) 5793 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 5794 } 5795 } 5796 5797 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 5798 { false, false, false } 5799#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 5800 , { Unary, Binary, MemberOnly } 5801#include "clang/Basic/OperatorKinds.def" 5802 }; 5803 5804 bool CanBeUnaryOperator = OperatorUses[Op][0]; 5805 bool CanBeBinaryOperator = OperatorUses[Op][1]; 5806 bool MustBeMemberOperator = OperatorUses[Op][2]; 5807 5808 // C++ [over.oper]p8: 5809 // [...] Operator functions cannot have more or fewer parameters 5810 // than the number required for the corresponding operator, as 5811 // described in the rest of this subclause. 5812 unsigned NumParams = FnDecl->getNumParams() 5813 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 5814 if (Op != OO_Call && 5815 ((NumParams == 1 && !CanBeUnaryOperator) || 5816 (NumParams == 2 && !CanBeBinaryOperator) || 5817 (NumParams < 1) || (NumParams > 2))) { 5818 // We have the wrong number of parameters. 5819 unsigned ErrorKind; 5820 if (CanBeUnaryOperator && CanBeBinaryOperator) { 5821 ErrorKind = 2; // 2 -> unary or binary. 5822 } else if (CanBeUnaryOperator) { 5823 ErrorKind = 0; // 0 -> unary 5824 } else { 5825 assert(CanBeBinaryOperator && 5826 "All non-call overloaded operators are unary or binary!"); 5827 ErrorKind = 1; // 1 -> binary 5828 } 5829 5830 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 5831 << FnDecl->getDeclName() << NumParams << ErrorKind; 5832 } 5833 5834 // Overloaded operators other than operator() cannot be variadic. 5835 if (Op != OO_Call && 5836 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 5837 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 5838 << FnDecl->getDeclName(); 5839 } 5840 5841 // Some operators must be non-static member functions. 5842 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 5843 return Diag(FnDecl->getLocation(), 5844 diag::err_operator_overload_must_be_member) 5845 << FnDecl->getDeclName(); 5846 } 5847 5848 // C++ [over.inc]p1: 5849 // The user-defined function called operator++ implements the 5850 // prefix and postfix ++ operator. If this function is a member 5851 // function with no parameters, or a non-member function with one 5852 // parameter of class or enumeration type, it defines the prefix 5853 // increment operator ++ for objects of that type. If the function 5854 // is a member function with one parameter (which shall be of type 5855 // int) or a non-member function with two parameters (the second 5856 // of which shall be of type int), it defines the postfix 5857 // increment operator ++ for objects of that type. 5858 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 5859 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 5860 bool ParamIsInt = false; 5861 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 5862 ParamIsInt = BT->getKind() == BuiltinType::Int; 5863 5864 if (!ParamIsInt) 5865 return Diag(LastParam->getLocation(), 5866 diag::err_operator_overload_post_incdec_must_be_int) 5867 << LastParam->getType() << (Op == OO_MinusMinus); 5868 } 5869 5870 return false; 5871} 5872 5873/// CheckLiteralOperatorDeclaration - Check whether the declaration 5874/// of this literal operator function is well-formed. If so, returns 5875/// false; otherwise, emits appropriate diagnostics and returns true. 5876bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 5877 DeclContext *DC = FnDecl->getDeclContext(); 5878 Decl::Kind Kind = DC->getDeclKind(); 5879 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 5880 Kind != Decl::LinkageSpec) { 5881 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 5882 << FnDecl->getDeclName(); 5883 return true; 5884 } 5885 5886 bool Valid = false; 5887 5888 // template <char...> type operator "" name() is the only valid template 5889 // signature, and the only valid signature with no parameters. 5890 if (FnDecl->param_size() == 0) { 5891 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 5892 // Must have only one template parameter 5893 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 5894 if (Params->size() == 1) { 5895 NonTypeTemplateParmDecl *PmDecl = 5896 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 5897 5898 // The template parameter must be a char parameter pack. 5899 // FIXME: This test will always fail because non-type parameter packs 5900 // have not been implemented. 5901 if (PmDecl && PmDecl->isTemplateParameterPack() && 5902 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 5903 Valid = true; 5904 } 5905 } 5906 } else { 5907 // Check the first parameter 5908 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 5909 5910 QualType T = (*Param)->getType(); 5911 5912 // unsigned long long int, long double, and any character type are allowed 5913 // as the only parameters. 5914 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 5915 Context.hasSameType(T, Context.LongDoubleTy) || 5916 Context.hasSameType(T, Context.CharTy) || 5917 Context.hasSameType(T, Context.WCharTy) || 5918 Context.hasSameType(T, Context.Char16Ty) || 5919 Context.hasSameType(T, Context.Char32Ty)) { 5920 if (++Param == FnDecl->param_end()) 5921 Valid = true; 5922 goto FinishedParams; 5923 } 5924 5925 // Otherwise it must be a pointer to const; let's strip those qualifiers. 5926 const PointerType *PT = T->getAs<PointerType>(); 5927 if (!PT) 5928 goto FinishedParams; 5929 T = PT->getPointeeType(); 5930 if (!T.isConstQualified()) 5931 goto FinishedParams; 5932 T = T.getUnqualifiedType(); 5933 5934 // Move on to the second parameter; 5935 ++Param; 5936 5937 // If there is no second parameter, the first must be a const char * 5938 if (Param == FnDecl->param_end()) { 5939 if (Context.hasSameType(T, Context.CharTy)) 5940 Valid = true; 5941 goto FinishedParams; 5942 } 5943 5944 // const char *, const wchar_t*, const char16_t*, and const char32_t* 5945 // are allowed as the first parameter to a two-parameter function 5946 if (!(Context.hasSameType(T, Context.CharTy) || 5947 Context.hasSameType(T, Context.WCharTy) || 5948 Context.hasSameType(T, Context.Char16Ty) || 5949 Context.hasSameType(T, Context.Char32Ty))) 5950 goto FinishedParams; 5951 5952 // The second and final parameter must be an std::size_t 5953 T = (*Param)->getType().getUnqualifiedType(); 5954 if (Context.hasSameType(T, Context.getSizeType()) && 5955 ++Param == FnDecl->param_end()) 5956 Valid = true; 5957 } 5958 5959 // FIXME: This diagnostic is absolutely terrible. 5960FinishedParams: 5961 if (!Valid) { 5962 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 5963 << FnDecl->getDeclName(); 5964 return true; 5965 } 5966 5967 return false; 5968} 5969 5970/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 5971/// linkage specification, including the language and (if present) 5972/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 5973/// the location of the language string literal, which is provided 5974/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 5975/// the '{' brace. Otherwise, this linkage specification does not 5976/// have any braces. 5977Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 5978 SourceLocation LangLoc, 5979 llvm::StringRef Lang, 5980 SourceLocation LBraceLoc) { 5981 LinkageSpecDecl::LanguageIDs Language; 5982 if (Lang == "\"C\"") 5983 Language = LinkageSpecDecl::lang_c; 5984 else if (Lang == "\"C++\"") 5985 Language = LinkageSpecDecl::lang_cxx; 5986 else { 5987 Diag(LangLoc, diag::err_bad_language); 5988 return 0; 5989 } 5990 5991 // FIXME: Add all the various semantics of linkage specifications 5992 5993 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 5994 LangLoc, Language, 5995 LBraceLoc.isValid()); 5996 CurContext->addDecl(D); 5997 PushDeclContext(S, D); 5998 return D; 5999} 6000 6001/// ActOnFinishLinkageSpecification - Complete the definition of 6002/// the C++ linkage specification LinkageSpec. If RBraceLoc is 6003/// valid, it's the position of the closing '}' brace in a linkage 6004/// specification that uses braces. 6005Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 6006 Decl *LinkageSpec, 6007 SourceLocation RBraceLoc) { 6008 if (LinkageSpec) 6009 PopDeclContext(); 6010 return LinkageSpec; 6011} 6012 6013/// \brief Perform semantic analysis for the variable declaration that 6014/// occurs within a C++ catch clause, returning the newly-created 6015/// variable. 6016VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 6017 TypeSourceInfo *TInfo, 6018 IdentifierInfo *Name, 6019 SourceLocation Loc) { 6020 bool Invalid = false; 6021 QualType ExDeclType = TInfo->getType(); 6022 6023 // Arrays and functions decay. 6024 if (ExDeclType->isArrayType()) 6025 ExDeclType = Context.getArrayDecayedType(ExDeclType); 6026 else if (ExDeclType->isFunctionType()) 6027 ExDeclType = Context.getPointerType(ExDeclType); 6028 6029 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 6030 // The exception-declaration shall not denote a pointer or reference to an 6031 // incomplete type, other than [cv] void*. 6032 // N2844 forbids rvalue references. 6033 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 6034 Diag(Loc, diag::err_catch_rvalue_ref); 6035 Invalid = true; 6036 } 6037 6038 // GCC allows catching pointers and references to incomplete types 6039 // as an extension; so do we, but we warn by default. 6040 6041 QualType BaseType = ExDeclType; 6042 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 6043 unsigned DK = diag::err_catch_incomplete; 6044 bool IncompleteCatchIsInvalid = true; 6045 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 6046 BaseType = Ptr->getPointeeType(); 6047 Mode = 1; 6048 DK = diag::ext_catch_incomplete_ptr; 6049 IncompleteCatchIsInvalid = false; 6050 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 6051 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 6052 BaseType = Ref->getPointeeType(); 6053 Mode = 2; 6054 DK = diag::ext_catch_incomplete_ref; 6055 IncompleteCatchIsInvalid = false; 6056 } 6057 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 6058 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 6059 IncompleteCatchIsInvalid) 6060 Invalid = true; 6061 6062 if (!Invalid && !ExDeclType->isDependentType() && 6063 RequireNonAbstractType(Loc, ExDeclType, 6064 diag::err_abstract_type_in_decl, 6065 AbstractVariableType)) 6066 Invalid = true; 6067 6068 // Only the non-fragile NeXT runtime currently supports C++ catches 6069 // of ObjC types, and no runtime supports catching ObjC types by value. 6070 if (!Invalid && getLangOptions().ObjC1) { 6071 QualType T = ExDeclType; 6072 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 6073 T = RT->getPointeeType(); 6074 6075 if (T->isObjCObjectType()) { 6076 Diag(Loc, diag::err_objc_object_catch); 6077 Invalid = true; 6078 } else if (T->isObjCObjectPointerType()) { 6079 if (!getLangOptions().NeXTRuntime) { 6080 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu); 6081 Invalid = true; 6082 } else if (!getLangOptions().ObjCNonFragileABI) { 6083 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile); 6084 Invalid = true; 6085 } 6086 } 6087 } 6088 6089 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 6090 Name, ExDeclType, TInfo, SC_None, 6091 SC_None); 6092 ExDecl->setExceptionVariable(true); 6093 6094 if (!Invalid) { 6095 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 6096 // C++ [except.handle]p16: 6097 // The object declared in an exception-declaration or, if the 6098 // exception-declaration does not specify a name, a temporary (12.2) is 6099 // copy-initialized (8.5) from the exception object. [...] 6100 // The object is destroyed when the handler exits, after the destruction 6101 // of any automatic objects initialized within the handler. 6102 // 6103 // We just pretend to initialize the object with itself, then make sure 6104 // it can be destroyed later. 6105 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 6106 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 6107 Loc, ExDeclType, VK_LValue, 0); 6108 InitializationKind Kind = InitializationKind::CreateCopy(Loc, 6109 SourceLocation()); 6110 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 6111 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6112 MultiExprArg(*this, &ExDeclRef, 1)); 6113 if (Result.isInvalid()) 6114 Invalid = true; 6115 else 6116 FinalizeVarWithDestructor(ExDecl, RecordTy); 6117 } 6118 } 6119 6120 if (Invalid) 6121 ExDecl->setInvalidDecl(); 6122 6123 return ExDecl; 6124} 6125 6126/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 6127/// handler. 6128Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 6129 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6130 QualType ExDeclType = TInfo->getType(); 6131 6132 bool Invalid = D.isInvalidType(); 6133 IdentifierInfo *II = D.getIdentifier(); 6134 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 6135 LookupOrdinaryName, 6136 ForRedeclaration)) { 6137 // The scope should be freshly made just for us. There is just no way 6138 // it contains any previous declaration. 6139 assert(!S->isDeclScope(PrevDecl)); 6140 if (PrevDecl->isTemplateParameter()) { 6141 // Maybe we will complain about the shadowed template parameter. 6142 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6143 } 6144 } 6145 6146 if (D.getCXXScopeSpec().isSet() && !Invalid) { 6147 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 6148 << D.getCXXScopeSpec().getRange(); 6149 Invalid = true; 6150 } 6151 6152 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 6153 D.getIdentifier(), 6154 D.getIdentifierLoc()); 6155 6156 if (Invalid) 6157 ExDecl->setInvalidDecl(); 6158 6159 // Add the exception declaration into this scope. 6160 if (II) 6161 PushOnScopeChains(ExDecl, S); 6162 else 6163 CurContext->addDecl(ExDecl); 6164 6165 ProcessDeclAttributes(S, ExDecl, D); 6166 return ExDecl; 6167} 6168 6169Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 6170 Expr *AssertExpr, 6171 Expr *AssertMessageExpr_) { 6172 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 6173 6174 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 6175 llvm::APSInt Value(32); 6176 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 6177 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 6178 AssertExpr->getSourceRange(); 6179 return 0; 6180 } 6181 6182 if (Value == 0) { 6183 Diag(AssertLoc, diag::err_static_assert_failed) 6184 << AssertMessage->getString() << AssertExpr->getSourceRange(); 6185 } 6186 } 6187 6188 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 6189 AssertExpr, AssertMessage); 6190 6191 CurContext->addDecl(Decl); 6192 return Decl; 6193} 6194 6195/// \brief Perform semantic analysis of the given friend type declaration. 6196/// 6197/// \returns A friend declaration that. 6198FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 6199 TypeSourceInfo *TSInfo) { 6200 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 6201 6202 QualType T = TSInfo->getType(); 6203 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 6204 6205 if (!getLangOptions().CPlusPlus0x) { 6206 // C++03 [class.friend]p2: 6207 // An elaborated-type-specifier shall be used in a friend declaration 6208 // for a class.* 6209 // 6210 // * The class-key of the elaborated-type-specifier is required. 6211 if (!ActiveTemplateInstantiations.empty()) { 6212 // Do not complain about the form of friend template types during 6213 // template instantiation; we will already have complained when the 6214 // template was declared. 6215 } else if (!T->isElaboratedTypeSpecifier()) { 6216 // If we evaluated the type to a record type, suggest putting 6217 // a tag in front. 6218 if (const RecordType *RT = T->getAs<RecordType>()) { 6219 RecordDecl *RD = RT->getDecl(); 6220 6221 std::string InsertionText = std::string(" ") + RD->getKindName(); 6222 6223 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 6224 << (unsigned) RD->getTagKind() 6225 << T 6226 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 6227 InsertionText); 6228 } else { 6229 Diag(FriendLoc, diag::ext_nonclass_type_friend) 6230 << T 6231 << SourceRange(FriendLoc, TypeRange.getEnd()); 6232 } 6233 } else if (T->getAs<EnumType>()) { 6234 Diag(FriendLoc, diag::ext_enum_friend) 6235 << T 6236 << SourceRange(FriendLoc, TypeRange.getEnd()); 6237 } 6238 } 6239 6240 // C++0x [class.friend]p3: 6241 // If the type specifier in a friend declaration designates a (possibly 6242 // cv-qualified) class type, that class is declared as a friend; otherwise, 6243 // the friend declaration is ignored. 6244 6245 // FIXME: C++0x has some syntactic restrictions on friend type declarations 6246 // in [class.friend]p3 that we do not implement. 6247 6248 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 6249} 6250 6251/// Handle a friend tag declaration where the scope specifier was 6252/// templated. 6253Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 6254 unsigned TagSpec, SourceLocation TagLoc, 6255 CXXScopeSpec &SS, 6256 IdentifierInfo *Name, SourceLocation NameLoc, 6257 AttributeList *Attr, 6258 MultiTemplateParamsArg TempParamLists) { 6259 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6260 6261 bool isExplicitSpecialization = false; 6262 unsigned NumMatchedTemplateParamLists = TempParamLists.size(); 6263 bool Invalid = false; 6264 6265 if (TemplateParameterList *TemplateParams 6266 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS, 6267 TempParamLists.get(), 6268 TempParamLists.size(), 6269 /*friend*/ true, 6270 isExplicitSpecialization, 6271 Invalid)) { 6272 --NumMatchedTemplateParamLists; 6273 6274 if (TemplateParams->size() > 0) { 6275 // This is a declaration of a class template. 6276 if (Invalid) 6277 return 0; 6278 6279 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 6280 SS, Name, NameLoc, Attr, 6281 TemplateParams, AS_public).take(); 6282 } else { 6283 // The "template<>" header is extraneous. 6284 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 6285 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 6286 isExplicitSpecialization = true; 6287 } 6288 } 6289 6290 if (Invalid) return 0; 6291 6292 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 6293 6294 bool isAllExplicitSpecializations = true; 6295 for (unsigned I = 0; I != NumMatchedTemplateParamLists; ++I) { 6296 if (TempParamLists.get()[I]->size()) { 6297 isAllExplicitSpecializations = false; 6298 break; 6299 } 6300 } 6301 6302 // FIXME: don't ignore attributes. 6303 6304 // If it's explicit specializations all the way down, just forget 6305 // about the template header and build an appropriate non-templated 6306 // friend. TODO: for source fidelity, remember the headers. 6307 if (isAllExplicitSpecializations) { 6308 ElaboratedTypeKeyword Keyword 6309 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 6310 QualType T = CheckTypenameType(Keyword, SS.getScopeRep(), *Name, 6311 TagLoc, SS.getRange(), NameLoc); 6312 if (T.isNull()) 6313 return 0; 6314 6315 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 6316 if (isa<DependentNameType>(T)) { 6317 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 6318 TL.setKeywordLoc(TagLoc); 6319 TL.setQualifierRange(SS.getRange()); 6320 TL.setNameLoc(NameLoc); 6321 } else { 6322 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 6323 TL.setKeywordLoc(TagLoc); 6324 TL.setQualifierRange(SS.getRange()); 6325 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 6326 } 6327 6328 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 6329 TSI, FriendLoc); 6330 Friend->setAccess(AS_public); 6331 CurContext->addDecl(Friend); 6332 return Friend; 6333 } 6334 6335 // Handle the case of a templated-scope friend class. e.g. 6336 // template <class T> class A<T>::B; 6337 // FIXME: we don't support these right now. 6338 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 6339 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 6340 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 6341 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 6342 TL.setKeywordLoc(TagLoc); 6343 TL.setQualifierRange(SS.getRange()); 6344 TL.setNameLoc(NameLoc); 6345 6346 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 6347 TSI, FriendLoc); 6348 Friend->setAccess(AS_public); 6349 Friend->setUnsupportedFriend(true); 6350 CurContext->addDecl(Friend); 6351 return Friend; 6352} 6353 6354 6355/// Handle a friend type declaration. This works in tandem with 6356/// ActOnTag. 6357/// 6358/// Notes on friend class templates: 6359/// 6360/// We generally treat friend class declarations as if they were 6361/// declaring a class. So, for example, the elaborated type specifier 6362/// in a friend declaration is required to obey the restrictions of a 6363/// class-head (i.e. no typedefs in the scope chain), template 6364/// parameters are required to match up with simple template-ids, &c. 6365/// However, unlike when declaring a template specialization, it's 6366/// okay to refer to a template specialization without an empty 6367/// template parameter declaration, e.g. 6368/// friend class A<T>::B<unsigned>; 6369/// We permit this as a special case; if there are any template 6370/// parameters present at all, require proper matching, i.e. 6371/// template <> template <class T> friend class A<int>::B; 6372Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 6373 MultiTemplateParamsArg TempParams) { 6374 SourceLocation Loc = DS.getSourceRange().getBegin(); 6375 6376 assert(DS.isFriendSpecified()); 6377 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 6378 6379 // Try to convert the decl specifier to a type. This works for 6380 // friend templates because ActOnTag never produces a ClassTemplateDecl 6381 // for a TUK_Friend. 6382 Declarator TheDeclarator(DS, Declarator::MemberContext); 6383 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 6384 QualType T = TSI->getType(); 6385 if (TheDeclarator.isInvalidType()) 6386 return 0; 6387 6388 // This is definitely an error in C++98. It's probably meant to 6389 // be forbidden in C++0x, too, but the specification is just 6390 // poorly written. 6391 // 6392 // The problem is with declarations like the following: 6393 // template <T> friend A<T>::foo; 6394 // where deciding whether a class C is a friend or not now hinges 6395 // on whether there exists an instantiation of A that causes 6396 // 'foo' to equal C. There are restrictions on class-heads 6397 // (which we declare (by fiat) elaborated friend declarations to 6398 // be) that makes this tractable. 6399 // 6400 // FIXME: handle "template <> friend class A<T>;", which 6401 // is possibly well-formed? Who even knows? 6402 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 6403 Diag(Loc, diag::err_tagless_friend_type_template) 6404 << DS.getSourceRange(); 6405 return 0; 6406 } 6407 6408 // C++98 [class.friend]p1: A friend of a class is a function 6409 // or class that is not a member of the class . . . 6410 // This is fixed in DR77, which just barely didn't make the C++03 6411 // deadline. It's also a very silly restriction that seriously 6412 // affects inner classes and which nobody else seems to implement; 6413 // thus we never diagnose it, not even in -pedantic. 6414 // 6415 // But note that we could warn about it: it's always useless to 6416 // friend one of your own members (it's not, however, worthless to 6417 // friend a member of an arbitrary specialization of your template). 6418 6419 Decl *D; 6420 if (unsigned NumTempParamLists = TempParams.size()) 6421 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 6422 NumTempParamLists, 6423 TempParams.release(), 6424 TSI, 6425 DS.getFriendSpecLoc()); 6426 else 6427 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 6428 6429 if (!D) 6430 return 0; 6431 6432 D->setAccess(AS_public); 6433 CurContext->addDecl(D); 6434 6435 return D; 6436} 6437 6438Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 6439 MultiTemplateParamsArg TemplateParams) { 6440 const DeclSpec &DS = D.getDeclSpec(); 6441 6442 assert(DS.isFriendSpecified()); 6443 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 6444 6445 SourceLocation Loc = D.getIdentifierLoc(); 6446 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6447 QualType T = TInfo->getType(); 6448 6449 // C++ [class.friend]p1 6450 // A friend of a class is a function or class.... 6451 // Note that this sees through typedefs, which is intended. 6452 // It *doesn't* see through dependent types, which is correct 6453 // according to [temp.arg.type]p3: 6454 // If a declaration acquires a function type through a 6455 // type dependent on a template-parameter and this causes 6456 // a declaration that does not use the syntactic form of a 6457 // function declarator to have a function type, the program 6458 // is ill-formed. 6459 if (!T->isFunctionType()) { 6460 Diag(Loc, diag::err_unexpected_friend); 6461 6462 // It might be worthwhile to try to recover by creating an 6463 // appropriate declaration. 6464 return 0; 6465 } 6466 6467 // C++ [namespace.memdef]p3 6468 // - If a friend declaration in a non-local class first declares a 6469 // class or function, the friend class or function is a member 6470 // of the innermost enclosing namespace. 6471 // - The name of the friend is not found by simple name lookup 6472 // until a matching declaration is provided in that namespace 6473 // scope (either before or after the class declaration granting 6474 // friendship). 6475 // - If a friend function is called, its name may be found by the 6476 // name lookup that considers functions from namespaces and 6477 // classes associated with the types of the function arguments. 6478 // - When looking for a prior declaration of a class or a function 6479 // declared as a friend, scopes outside the innermost enclosing 6480 // namespace scope are not considered. 6481 6482 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6483 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6484 DeclarationName Name = NameInfo.getName(); 6485 assert(Name); 6486 6487 // The context we found the declaration in, or in which we should 6488 // create the declaration. 6489 DeclContext *DC; 6490 Scope *DCScope = S; 6491 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6492 ForRedeclaration); 6493 6494 // FIXME: there are different rules in local classes 6495 6496 // There are four cases here. 6497 // - There's no scope specifier, in which case we just go to the 6498 // appropriate scope and look for a function or function template 6499 // there as appropriate. 6500 // Recover from invalid scope qualifiers as if they just weren't there. 6501 if (SS.isInvalid() || !SS.isSet()) { 6502 // C++0x [namespace.memdef]p3: 6503 // If the name in a friend declaration is neither qualified nor 6504 // a template-id and the declaration is a function or an 6505 // elaborated-type-specifier, the lookup to determine whether 6506 // the entity has been previously declared shall not consider 6507 // any scopes outside the innermost enclosing namespace. 6508 // C++0x [class.friend]p11: 6509 // If a friend declaration appears in a local class and the name 6510 // specified is an unqualified name, a prior declaration is 6511 // looked up without considering scopes that are outside the 6512 // innermost enclosing non-class scope. For a friend function 6513 // declaration, if there is no prior declaration, the program is 6514 // ill-formed. 6515 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 6516 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 6517 6518 // Find the appropriate context according to the above. 6519 DC = CurContext; 6520 while (true) { 6521 // Skip class contexts. If someone can cite chapter and verse 6522 // for this behavior, that would be nice --- it's what GCC and 6523 // EDG do, and it seems like a reasonable intent, but the spec 6524 // really only says that checks for unqualified existing 6525 // declarations should stop at the nearest enclosing namespace, 6526 // not that they should only consider the nearest enclosing 6527 // namespace. 6528 while (DC->isRecord()) 6529 DC = DC->getParent(); 6530 6531 LookupQualifiedName(Previous, DC); 6532 6533 // TODO: decide what we think about using declarations. 6534 if (isLocal || !Previous.empty()) 6535 break; 6536 6537 if (isTemplateId) { 6538 if (isa<TranslationUnitDecl>(DC)) break; 6539 } else { 6540 if (DC->isFileContext()) break; 6541 } 6542 DC = DC->getParent(); 6543 } 6544 6545 // C++ [class.friend]p1: A friend of a class is a function or 6546 // class that is not a member of the class . . . 6547 // C++0x changes this for both friend types and functions. 6548 // Most C++ 98 compilers do seem to give an error here, so 6549 // we do, too. 6550 if (!Previous.empty() && DC->Equals(CurContext) 6551 && !getLangOptions().CPlusPlus0x) 6552 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 6553 6554 DCScope = getScopeForDeclContext(S, DC); 6555 6556 // - There's a non-dependent scope specifier, in which case we 6557 // compute it and do a previous lookup there for a function 6558 // or function template. 6559 } else if (!SS.getScopeRep()->isDependent()) { 6560 DC = computeDeclContext(SS); 6561 if (!DC) return 0; 6562 6563 if (RequireCompleteDeclContext(SS, DC)) return 0; 6564 6565 LookupQualifiedName(Previous, DC); 6566 6567 // Ignore things found implicitly in the wrong scope. 6568 // TODO: better diagnostics for this case. Suggesting the right 6569 // qualified scope would be nice... 6570 LookupResult::Filter F = Previous.makeFilter(); 6571 while (F.hasNext()) { 6572 NamedDecl *D = F.next(); 6573 if (!DC->InEnclosingNamespaceSetOf( 6574 D->getDeclContext()->getRedeclContext())) 6575 F.erase(); 6576 } 6577 F.done(); 6578 6579 if (Previous.empty()) { 6580 D.setInvalidType(); 6581 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 6582 return 0; 6583 } 6584 6585 // C++ [class.friend]p1: A friend of a class is a function or 6586 // class that is not a member of the class . . . 6587 if (DC->Equals(CurContext)) 6588 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 6589 6590 // - There's a scope specifier that does not match any template 6591 // parameter lists, in which case we use some arbitrary context, 6592 // create a method or method template, and wait for instantiation. 6593 // - There's a scope specifier that does match some template 6594 // parameter lists, which we don't handle right now. 6595 } else { 6596 DC = CurContext; 6597 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 6598 } 6599 6600 if (!DC->isRecord()) { 6601 // This implies that it has to be an operator or function. 6602 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 6603 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 6604 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 6605 Diag(Loc, diag::err_introducing_special_friend) << 6606 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 6607 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 6608 return 0; 6609 } 6610 } 6611 6612 bool Redeclaration = false; 6613 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 6614 move(TemplateParams), 6615 IsDefinition, 6616 Redeclaration); 6617 if (!ND) return 0; 6618 6619 assert(ND->getDeclContext() == DC); 6620 assert(ND->getLexicalDeclContext() == CurContext); 6621 6622 // Add the function declaration to the appropriate lookup tables, 6623 // adjusting the redeclarations list as necessary. We don't 6624 // want to do this yet if the friending class is dependent. 6625 // 6626 // Also update the scope-based lookup if the target context's 6627 // lookup context is in lexical scope. 6628 if (!CurContext->isDependentContext()) { 6629 DC = DC->getRedeclContext(); 6630 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 6631 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 6632 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 6633 } 6634 6635 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 6636 D.getIdentifierLoc(), ND, 6637 DS.getFriendSpecLoc()); 6638 FrD->setAccess(AS_public); 6639 CurContext->addDecl(FrD); 6640 6641 if (ND->isInvalidDecl()) 6642 FrD->setInvalidDecl(); 6643 else { 6644 FunctionDecl *FD; 6645 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 6646 FD = FTD->getTemplatedDecl(); 6647 else 6648 FD = cast<FunctionDecl>(ND); 6649 6650 // Mark templated-scope function declarations as unsupported. 6651 if (FD->getNumTemplateParameterLists()) 6652 FrD->setUnsupportedFriend(true); 6653 } 6654 6655 return ND; 6656} 6657 6658void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 6659 AdjustDeclIfTemplate(Dcl); 6660 6661 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 6662 if (!Fn) { 6663 Diag(DelLoc, diag::err_deleted_non_function); 6664 return; 6665 } 6666 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 6667 Diag(DelLoc, diag::err_deleted_decl_not_first); 6668 Diag(Prev->getLocation(), diag::note_previous_declaration); 6669 // If the declaration wasn't the first, we delete the function anyway for 6670 // recovery. 6671 } 6672 Fn->setDeleted(); 6673} 6674 6675static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 6676 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 6677 ++CI) { 6678 Stmt *SubStmt = *CI; 6679 if (!SubStmt) 6680 continue; 6681 if (isa<ReturnStmt>(SubStmt)) 6682 Self.Diag(SubStmt->getSourceRange().getBegin(), 6683 diag::err_return_in_constructor_handler); 6684 if (!isa<Expr>(SubStmt)) 6685 SearchForReturnInStmt(Self, SubStmt); 6686 } 6687} 6688 6689void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 6690 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 6691 CXXCatchStmt *Handler = TryBlock->getHandler(I); 6692 SearchForReturnInStmt(*this, Handler); 6693 } 6694} 6695 6696bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 6697 const CXXMethodDecl *Old) { 6698 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 6699 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 6700 6701 if (Context.hasSameType(NewTy, OldTy) || 6702 NewTy->isDependentType() || OldTy->isDependentType()) 6703 return false; 6704 6705 // Check if the return types are covariant 6706 QualType NewClassTy, OldClassTy; 6707 6708 /// Both types must be pointers or references to classes. 6709 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 6710 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 6711 NewClassTy = NewPT->getPointeeType(); 6712 OldClassTy = OldPT->getPointeeType(); 6713 } 6714 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 6715 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 6716 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 6717 NewClassTy = NewRT->getPointeeType(); 6718 OldClassTy = OldRT->getPointeeType(); 6719 } 6720 } 6721 } 6722 6723 // The return types aren't either both pointers or references to a class type. 6724 if (NewClassTy.isNull()) { 6725 Diag(New->getLocation(), 6726 diag::err_different_return_type_for_overriding_virtual_function) 6727 << New->getDeclName() << NewTy << OldTy; 6728 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6729 6730 return true; 6731 } 6732 6733 // C++ [class.virtual]p6: 6734 // If the return type of D::f differs from the return type of B::f, the 6735 // class type in the return type of D::f shall be complete at the point of 6736 // declaration of D::f or shall be the class type D. 6737 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 6738 if (!RT->isBeingDefined() && 6739 RequireCompleteType(New->getLocation(), NewClassTy, 6740 PDiag(diag::err_covariant_return_incomplete) 6741 << New->getDeclName())) 6742 return true; 6743 } 6744 6745 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 6746 // Check if the new class derives from the old class. 6747 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 6748 Diag(New->getLocation(), 6749 diag::err_covariant_return_not_derived) 6750 << New->getDeclName() << NewTy << OldTy; 6751 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6752 return true; 6753 } 6754 6755 // Check if we the conversion from derived to base is valid. 6756 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 6757 diag::err_covariant_return_inaccessible_base, 6758 diag::err_covariant_return_ambiguous_derived_to_base_conv, 6759 // FIXME: Should this point to the return type? 6760 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 6761 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6762 return true; 6763 } 6764 } 6765 6766 // The qualifiers of the return types must be the same. 6767 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 6768 Diag(New->getLocation(), 6769 diag::err_covariant_return_type_different_qualifications) 6770 << New->getDeclName() << NewTy << OldTy; 6771 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6772 return true; 6773 }; 6774 6775 6776 // The new class type must have the same or less qualifiers as the old type. 6777 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 6778 Diag(New->getLocation(), 6779 diag::err_covariant_return_type_class_type_more_qualified) 6780 << New->getDeclName() << NewTy << OldTy; 6781 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6782 return true; 6783 }; 6784 6785 return false; 6786} 6787 6788bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 6789 const CXXMethodDecl *Old) 6790{ 6791 if (Old->hasAttr<FinalAttr>()) { 6792 Diag(New->getLocation(), diag::err_final_function_overridden) 6793 << New->getDeclName(); 6794 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 6795 return true; 6796 } 6797 6798 return false; 6799} 6800 6801/// \brief Mark the given method pure. 6802/// 6803/// \param Method the method to be marked pure. 6804/// 6805/// \param InitRange the source range that covers the "0" initializer. 6806bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 6807 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 6808 Method->setPure(); 6809 return false; 6810 } 6811 6812 if (!Method->isInvalidDecl()) 6813 Diag(Method->getLocation(), diag::err_non_virtual_pure) 6814 << Method->getDeclName() << InitRange; 6815 return true; 6816} 6817 6818/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 6819/// an initializer for the out-of-line declaration 'Dcl'. The scope 6820/// is a fresh scope pushed for just this purpose. 6821/// 6822/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6823/// static data member of class X, names should be looked up in the scope of 6824/// class X. 6825void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 6826 // If there is no declaration, there was an error parsing it. 6827 if (D == 0) return; 6828 6829 // We should only get called for declarations with scope specifiers, like: 6830 // int foo::bar; 6831 assert(D->isOutOfLine()); 6832 EnterDeclaratorContext(S, D->getDeclContext()); 6833} 6834 6835/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6836/// initializer for the out-of-line declaration 'D'. 6837void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 6838 // If there is no declaration, there was an error parsing it. 6839 if (D == 0) return; 6840 6841 assert(D->isOutOfLine()); 6842 ExitDeclaratorContext(S); 6843} 6844 6845/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 6846/// C++ if/switch/while/for statement. 6847/// e.g: "if (int x = f()) {...}" 6848DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 6849 // C++ 6.4p2: 6850 // The declarator shall not specify a function or an array. 6851 // The type-specifier-seq shall not contain typedef and shall not declare a 6852 // new class or enumeration. 6853 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6854 "Parser allowed 'typedef' as storage class of condition decl."); 6855 6856 TagDecl *OwnedTag = 0; 6857 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 6858 QualType Ty = TInfo->getType(); 6859 6860 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 6861 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 6862 // would be created and CXXConditionDeclExpr wants a VarDecl. 6863 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 6864 << D.getSourceRange(); 6865 return DeclResult(); 6866 } else if (OwnedTag && OwnedTag->isDefinition()) { 6867 // The type-specifier-seq shall not declare a new class or enumeration. 6868 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 6869 } 6870 6871 Decl *Dcl = ActOnDeclarator(S, D); 6872 if (!Dcl) 6873 return DeclResult(); 6874 6875 return Dcl; 6876} 6877 6878void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 6879 bool DefinitionRequired) { 6880 // Ignore any vtable uses in unevaluated operands or for classes that do 6881 // not have a vtable. 6882 if (!Class->isDynamicClass() || Class->isDependentContext() || 6883 CurContext->isDependentContext() || 6884 ExprEvalContexts.back().Context == Unevaluated) 6885 return; 6886 6887 // Try to insert this class into the map. 6888 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 6889 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 6890 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 6891 if (!Pos.second) { 6892 // If we already had an entry, check to see if we are promoting this vtable 6893 // to required a definition. If so, we need to reappend to the VTableUses 6894 // list, since we may have already processed the first entry. 6895 if (DefinitionRequired && !Pos.first->second) { 6896 Pos.first->second = true; 6897 } else { 6898 // Otherwise, we can early exit. 6899 return; 6900 } 6901 } 6902 6903 // Local classes need to have their virtual members marked 6904 // immediately. For all other classes, we mark their virtual members 6905 // at the end of the translation unit. 6906 if (Class->isLocalClass()) 6907 MarkVirtualMembersReferenced(Loc, Class); 6908 else 6909 VTableUses.push_back(std::make_pair(Class, Loc)); 6910} 6911 6912bool Sema::DefineUsedVTables() { 6913 // If any dynamic classes have their key function defined within 6914 // this translation unit, then those vtables are considered "used" and must 6915 // be emitted. 6916 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) { 6917 if (const CXXMethodDecl *KeyFunction 6918 = Context.getKeyFunction(DynamicClasses[I])) { 6919 const FunctionDecl *Definition = 0; 6920 if (KeyFunction->hasBody(Definition)) 6921 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true); 6922 } 6923 } 6924 6925 if (VTableUses.empty()) 6926 return false; 6927 6928 // Note: The VTableUses vector could grow as a result of marking 6929 // the members of a class as "used", so we check the size each 6930 // time through the loop and prefer indices (with are stable) to 6931 // iterators (which are not). 6932 for (unsigned I = 0; I != VTableUses.size(); ++I) { 6933 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 6934 if (!Class) 6935 continue; 6936 6937 SourceLocation Loc = VTableUses[I].second; 6938 6939 // If this class has a key function, but that key function is 6940 // defined in another translation unit, we don't need to emit the 6941 // vtable even though we're using it. 6942 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 6943 if (KeyFunction && !KeyFunction->hasBody()) { 6944 switch (KeyFunction->getTemplateSpecializationKind()) { 6945 case TSK_Undeclared: 6946 case TSK_ExplicitSpecialization: 6947 case TSK_ExplicitInstantiationDeclaration: 6948 // The key function is in another translation unit. 6949 continue; 6950 6951 case TSK_ExplicitInstantiationDefinition: 6952 case TSK_ImplicitInstantiation: 6953 // We will be instantiating the key function. 6954 break; 6955 } 6956 } else if (!KeyFunction) { 6957 // If we have a class with no key function that is the subject 6958 // of an explicit instantiation declaration, suppress the 6959 // vtable; it will live with the explicit instantiation 6960 // definition. 6961 bool IsExplicitInstantiationDeclaration 6962 = Class->getTemplateSpecializationKind() 6963 == TSK_ExplicitInstantiationDeclaration; 6964 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 6965 REnd = Class->redecls_end(); 6966 R != REnd; ++R) { 6967 TemplateSpecializationKind TSK 6968 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 6969 if (TSK == TSK_ExplicitInstantiationDeclaration) 6970 IsExplicitInstantiationDeclaration = true; 6971 else if (TSK == TSK_ExplicitInstantiationDefinition) { 6972 IsExplicitInstantiationDeclaration = false; 6973 break; 6974 } 6975 } 6976 6977 if (IsExplicitInstantiationDeclaration) 6978 continue; 6979 } 6980 6981 // Mark all of the virtual members of this class as referenced, so 6982 // that we can build a vtable. Then, tell the AST consumer that a 6983 // vtable for this class is required. 6984 MarkVirtualMembersReferenced(Loc, Class); 6985 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 6986 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 6987 6988 // Optionally warn if we're emitting a weak vtable. 6989 if (Class->getLinkage() == ExternalLinkage && 6990 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 6991 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 6992 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 6993 } 6994 } 6995 VTableUses.clear(); 6996 6997 return true; 6998} 6999 7000void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 7001 const CXXRecordDecl *RD) { 7002 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 7003 e = RD->method_end(); i != e; ++i) { 7004 CXXMethodDecl *MD = *i; 7005 7006 // C++ [basic.def.odr]p2: 7007 // [...] A virtual member function is used if it is not pure. [...] 7008 if (MD->isVirtual() && !MD->isPure()) 7009 MarkDeclarationReferenced(Loc, MD); 7010 } 7011 7012 // Only classes that have virtual bases need a VTT. 7013 if (RD->getNumVBases() == 0) 7014 return; 7015 7016 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 7017 e = RD->bases_end(); i != e; ++i) { 7018 const CXXRecordDecl *Base = 7019 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 7020 if (Base->getNumVBases() == 0) 7021 continue; 7022 MarkVirtualMembersReferenced(Loc, Base); 7023 } 7024} 7025 7026/// SetIvarInitializers - This routine builds initialization ASTs for the 7027/// Objective-C implementation whose ivars need be initialized. 7028void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 7029 if (!getLangOptions().CPlusPlus) 7030 return; 7031 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 7032 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 7033 CollectIvarsToConstructOrDestruct(OID, ivars); 7034 if (ivars.empty()) 7035 return; 7036 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 7037 for (unsigned i = 0; i < ivars.size(); i++) { 7038 FieldDecl *Field = ivars[i]; 7039 if (Field->isInvalidDecl()) 7040 continue; 7041 7042 CXXBaseOrMemberInitializer *Member; 7043 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 7044 InitializationKind InitKind = 7045 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 7046 7047 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 7048 ExprResult MemberInit = 7049 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 7050 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get()); 7051 // Note, MemberInit could actually come back empty if no initialization 7052 // is required (e.g., because it would call a trivial default constructor) 7053 if (!MemberInit.get() || MemberInit.isInvalid()) 7054 continue; 7055 7056 Member = 7057 new (Context) CXXBaseOrMemberInitializer(Context, 7058 Field, SourceLocation(), 7059 SourceLocation(), 7060 MemberInit.takeAs<Expr>(), 7061 SourceLocation()); 7062 AllToInit.push_back(Member); 7063 7064 // Be sure that the destructor is accessible and is marked as referenced. 7065 if (const RecordType *RecordTy 7066 = Context.getBaseElementType(Field->getType()) 7067 ->getAs<RecordType>()) { 7068 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 7069 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 7070 MarkDeclarationReferenced(Field->getLocation(), Destructor); 7071 CheckDestructorAccess(Field->getLocation(), Destructor, 7072 PDiag(diag::err_access_dtor_ivar) 7073 << Context.getBaseElementType(Field->getType())); 7074 } 7075 } 7076 } 7077 ObjCImplementation->setIvarInitializers(Context, 7078 AllToInit.data(), AllToInit.size()); 7079 } 7080} 7081