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