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