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