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