SemaDecl.cpp revision 6f072329e9c9b7d44f0fa2a34528193a6f478414
1//===--- SemaDecl.cpp - Semantic Analysis for 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 declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/Sema.h" 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/CXXFieldCollector.h" 18#include "clang/Sema/Scope.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/AST/APValue.h" 21#include "clang/AST/ASTConsumer.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/DeclCXX.h" 25#include "clang/AST/DeclObjC.h" 26#include "clang/AST/DeclTemplate.h" 27#include "clang/AST/ExprCXX.h" 28#include "clang/AST/StmtCXX.h" 29#include "clang/Sema/DeclSpec.h" 30#include "clang/Sema/ParsedTemplate.h" 31#include "clang/Parse/ParseDiagnostic.h" 32#include "clang/Basic/PartialDiagnostic.h" 33#include "clang/Basic/SourceManager.h" 34#include "clang/Basic/TargetInfo.h" 35// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 36#include "clang/Lex/Preprocessor.h" 37#include "clang/Lex/HeaderSearch.h" 38#include "llvm/ADT/Triple.h" 39#include <algorithm> 40#include <cstring> 41#include <functional> 42using namespace clang; 43using namespace sema; 44 45/// getDeclName - Return a pretty name for the specified decl if possible, or 46/// an empty string if not. This is used for pretty crash reporting. 47std::string Sema::getDeclName(Decl *D) { 48 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D)) 49 return DN->getQualifiedNameAsString(); 50 return ""; 51} 52 53Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr) { 54 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 55} 56 57/// \brief If the identifier refers to a type name within this scope, 58/// return the declaration of that type. 59/// 60/// This routine performs ordinary name lookup of the identifier II 61/// within the given scope, with optional C++ scope specifier SS, to 62/// determine whether the name refers to a type. If so, returns an 63/// opaque pointer (actually a QualType) corresponding to that 64/// type. Otherwise, returns NULL. 65/// 66/// If name lookup results in an ambiguity, this routine will complain 67/// and then return NULL. 68ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 69 Scope *S, CXXScopeSpec *SS, 70 bool isClassName, 71 ParsedType ObjectTypePtr) { 72 // Determine where we will perform name lookup. 73 DeclContext *LookupCtx = 0; 74 if (ObjectTypePtr) { 75 QualType ObjectType = ObjectTypePtr.get(); 76 if (ObjectType->isRecordType()) 77 LookupCtx = computeDeclContext(ObjectType); 78 } else if (SS && SS->isNotEmpty()) { 79 LookupCtx = computeDeclContext(*SS, false); 80 81 if (!LookupCtx) { 82 if (isDependentScopeSpecifier(*SS)) { 83 // C++ [temp.res]p3: 84 // A qualified-id that refers to a type and in which the 85 // nested-name-specifier depends on a template-parameter (14.6.2) 86 // shall be prefixed by the keyword typename to indicate that the 87 // qualified-id denotes a type, forming an 88 // elaborated-type-specifier (7.1.5.3). 89 // 90 // We therefore do not perform any name lookup if the result would 91 // refer to a member of an unknown specialization. 92 if (!isClassName) 93 return ParsedType(); 94 95 // We know from the grammar that this name refers to a type, 96 // so build a dependent node to describe the type. 97 QualType T = 98 CheckTypenameType(ETK_None, SS->getScopeRep(), II, 99 SourceLocation(), SS->getRange(), NameLoc); 100 return ParsedType::make(T); 101 } 102 103 return ParsedType(); 104 } 105 106 if (!LookupCtx->isDependentContext() && 107 RequireCompleteDeclContext(*SS, LookupCtx)) 108 return ParsedType(); 109 } 110 111 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 112 // lookup for class-names. 113 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 114 LookupOrdinaryName; 115 LookupResult Result(*this, &II, NameLoc, Kind); 116 if (LookupCtx) { 117 // Perform "qualified" name lookup into the declaration context we 118 // computed, which is either the type of the base of a member access 119 // expression or the declaration context associated with a prior 120 // nested-name-specifier. 121 LookupQualifiedName(Result, LookupCtx); 122 123 if (ObjectTypePtr && Result.empty()) { 124 // C++ [basic.lookup.classref]p3: 125 // If the unqualified-id is ~type-name, the type-name is looked up 126 // in the context of the entire postfix-expression. If the type T of 127 // the object expression is of a class type C, the type-name is also 128 // looked up in the scope of class C. At least one of the lookups shall 129 // find a name that refers to (possibly cv-qualified) T. 130 LookupName(Result, S); 131 } 132 } else { 133 // Perform unqualified name lookup. 134 LookupName(Result, S); 135 } 136 137 NamedDecl *IIDecl = 0; 138 switch (Result.getResultKind()) { 139 case LookupResult::NotFound: 140 case LookupResult::NotFoundInCurrentInstantiation: 141 case LookupResult::FoundOverloaded: 142 case LookupResult::FoundUnresolvedValue: 143 Result.suppressDiagnostics(); 144 return ParsedType(); 145 146 case LookupResult::Ambiguous: 147 // Recover from type-hiding ambiguities by hiding the type. We'll 148 // do the lookup again when looking for an object, and we can 149 // diagnose the error then. If we don't do this, then the error 150 // about hiding the type will be immediately followed by an error 151 // that only makes sense if the identifier was treated like a type. 152 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 153 Result.suppressDiagnostics(); 154 return ParsedType(); 155 } 156 157 // Look to see if we have a type anywhere in the list of results. 158 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 159 Res != ResEnd; ++Res) { 160 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 161 if (!IIDecl || 162 (*Res)->getLocation().getRawEncoding() < 163 IIDecl->getLocation().getRawEncoding()) 164 IIDecl = *Res; 165 } 166 } 167 168 if (!IIDecl) { 169 // None of the entities we found is a type, so there is no way 170 // to even assume that the result is a type. In this case, don't 171 // complain about the ambiguity. The parser will either try to 172 // perform this lookup again (e.g., as an object name), which 173 // will produce the ambiguity, or will complain that it expected 174 // a type name. 175 Result.suppressDiagnostics(); 176 return ParsedType(); 177 } 178 179 // We found a type within the ambiguous lookup; diagnose the 180 // ambiguity and then return that type. This might be the right 181 // answer, or it might not be, but it suppresses any attempt to 182 // perform the name lookup again. 183 break; 184 185 case LookupResult::Found: 186 IIDecl = Result.getFoundDecl(); 187 break; 188 } 189 190 assert(IIDecl && "Didn't find decl"); 191 192 QualType T; 193 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 194 DiagnoseUseOfDecl(IIDecl, NameLoc); 195 196 if (T.isNull()) 197 T = Context.getTypeDeclType(TD); 198 199 if (SS) 200 T = getElaboratedType(ETK_None, *SS, T); 201 202 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 203 T = Context.getObjCInterfaceType(IDecl); 204 } else { 205 // If it's not plausibly a type, suppress diagnostics. 206 Result.suppressDiagnostics(); 207 return ParsedType(); 208 } 209 210 return ParsedType::make(T); 211} 212 213/// isTagName() - This method is called *for error recovery purposes only* 214/// to determine if the specified name is a valid tag name ("struct foo"). If 215/// so, this returns the TST for the tag corresponding to it (TST_enum, 216/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 217/// where the user forgot to specify the tag. 218DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 219 // Do a tag name lookup in this scope. 220 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 221 LookupName(R, S, false); 222 R.suppressDiagnostics(); 223 if (R.getResultKind() == LookupResult::Found) 224 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 225 switch (TD->getTagKind()) { 226 default: return DeclSpec::TST_unspecified; 227 case TTK_Struct: return DeclSpec::TST_struct; 228 case TTK_Union: return DeclSpec::TST_union; 229 case TTK_Class: return DeclSpec::TST_class; 230 case TTK_Enum: return DeclSpec::TST_enum; 231 } 232 } 233 234 return DeclSpec::TST_unspecified; 235} 236 237bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 238 SourceLocation IILoc, 239 Scope *S, 240 CXXScopeSpec *SS, 241 ParsedType &SuggestedType) { 242 // We don't have anything to suggest (yet). 243 SuggestedType = ParsedType(); 244 245 // There may have been a typo in the name of the type. Look up typo 246 // results, in case we have something that we can suggest. 247 LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName, 248 NotForRedeclaration); 249 250 if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) { 251 if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) { 252 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 253 !Result->isInvalidDecl()) { 254 // We found a similarly-named type or interface; suggest that. 255 if (!SS || !SS->isSet()) 256 Diag(IILoc, diag::err_unknown_typename_suggest) 257 << &II << Lookup.getLookupName() 258 << FixItHint::CreateReplacement(SourceRange(IILoc), 259 Result->getNameAsString()); 260 else if (DeclContext *DC = computeDeclContext(*SS, false)) 261 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 262 << &II << DC << Lookup.getLookupName() << SS->getRange() 263 << FixItHint::CreateReplacement(SourceRange(IILoc), 264 Result->getNameAsString()); 265 else 266 llvm_unreachable("could not have corrected a typo here"); 267 268 Diag(Result->getLocation(), diag::note_previous_decl) 269 << Result->getDeclName(); 270 271 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS); 272 return true; 273 } 274 } else if (Lookup.empty()) { 275 // We corrected to a keyword. 276 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 277 Diag(IILoc, diag::err_unknown_typename_suggest) 278 << &II << Corrected; 279 return true; 280 } 281 } 282 283 if (getLangOptions().CPlusPlus) { 284 // See if II is a class template that the user forgot to pass arguments to. 285 UnqualifiedId Name; 286 Name.setIdentifier(&II, IILoc); 287 CXXScopeSpec EmptySS; 288 TemplateTy TemplateResult; 289 bool MemberOfUnknownSpecialization; 290 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 291 Name, ParsedType(), true, TemplateResult, 292 MemberOfUnknownSpecialization) == TNK_Type_template) { 293 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 294 Diag(IILoc, diag::err_template_missing_args) << TplName; 295 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 296 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 297 << TplDecl->getTemplateParameters()->getSourceRange(); 298 } 299 return true; 300 } 301 } 302 303 // FIXME: Should we move the logic that tries to recover from a missing tag 304 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 305 306 if (!SS || (!SS->isSet() && !SS->isInvalid())) 307 Diag(IILoc, diag::err_unknown_typename) << &II; 308 else if (DeclContext *DC = computeDeclContext(*SS, false)) 309 Diag(IILoc, diag::err_typename_nested_not_found) 310 << &II << DC << SS->getRange(); 311 else if (isDependentScopeSpecifier(*SS)) { 312 Diag(SS->getRange().getBegin(), diag::err_typename_missing) 313 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 314 << SourceRange(SS->getRange().getBegin(), IILoc) 315 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 316 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get(); 317 } else { 318 assert(SS && SS->isInvalid() && 319 "Invalid scope specifier has already been diagnosed"); 320 } 321 322 return true; 323} 324 325// Determines the context to return to after temporarily entering a 326// context. This depends in an unnecessarily complicated way on the 327// exact ordering of callbacks from the parser. 328DeclContext *Sema::getContainingDC(DeclContext *DC) { 329 330 // Functions defined inline within classes aren't parsed until we've 331 // finished parsing the top-level class, so the top-level class is 332 // the context we'll need to return to. 333 if (isa<FunctionDecl>(DC)) { 334 DC = DC->getLexicalParent(); 335 336 // A function not defined within a class will always return to its 337 // lexical context. 338 if (!isa<CXXRecordDecl>(DC)) 339 return DC; 340 341 // A C++ inline method/friend is parsed *after* the topmost class 342 // it was declared in is fully parsed ("complete"); the topmost 343 // class is the context we need to return to. 344 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 345 DC = RD; 346 347 // Return the declaration context of the topmost class the inline method is 348 // declared in. 349 return DC; 350 } 351 352 // ObjCMethodDecls are parsed (for some reason) outside the context 353 // of the class. 354 if (isa<ObjCMethodDecl>(DC)) 355 return DC->getLexicalParent()->getLexicalParent(); 356 357 return DC->getLexicalParent(); 358} 359 360void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 361 assert(getContainingDC(DC) == CurContext && 362 "The next DeclContext should be lexically contained in the current one."); 363 CurContext = DC; 364 S->setEntity(DC); 365} 366 367void Sema::PopDeclContext() { 368 assert(CurContext && "DeclContext imbalance!"); 369 370 CurContext = getContainingDC(CurContext); 371 assert(CurContext && "Popped translation unit!"); 372} 373 374/// EnterDeclaratorContext - Used when we must lookup names in the context 375/// of a declarator's nested name specifier. 376/// 377void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 378 // C++0x [basic.lookup.unqual]p13: 379 // A name used in the definition of a static data member of class 380 // X (after the qualified-id of the static member) is looked up as 381 // if the name was used in a member function of X. 382 // C++0x [basic.lookup.unqual]p14: 383 // If a variable member of a namespace is defined outside of the 384 // scope of its namespace then any name used in the definition of 385 // the variable member (after the declarator-id) is looked up as 386 // if the definition of the variable member occurred in its 387 // namespace. 388 // Both of these imply that we should push a scope whose context 389 // is the semantic context of the declaration. We can't use 390 // PushDeclContext here because that context is not necessarily 391 // lexically contained in the current context. Fortunately, 392 // the containing scope should have the appropriate information. 393 394 assert(!S->getEntity() && "scope already has entity"); 395 396#ifndef NDEBUG 397 Scope *Ancestor = S->getParent(); 398 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 399 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 400#endif 401 402 CurContext = DC; 403 S->setEntity(DC); 404} 405 406void Sema::ExitDeclaratorContext(Scope *S) { 407 assert(S->getEntity() == CurContext && "Context imbalance!"); 408 409 // Switch back to the lexical context. The safety of this is 410 // enforced by an assert in EnterDeclaratorContext. 411 Scope *Ancestor = S->getParent(); 412 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 413 CurContext = (DeclContext*) Ancestor->getEntity(); 414 415 // We don't need to do anything with the scope, which is going to 416 // disappear. 417} 418 419/// \brief Determine whether we allow overloading of the function 420/// PrevDecl with another declaration. 421/// 422/// This routine determines whether overloading is possible, not 423/// whether some new function is actually an overload. It will return 424/// true in C++ (where we can always provide overloads) or, as an 425/// extension, in C when the previous function is already an 426/// overloaded function declaration or has the "overloadable" 427/// attribute. 428static bool AllowOverloadingOfFunction(LookupResult &Previous, 429 ASTContext &Context) { 430 if (Context.getLangOptions().CPlusPlus) 431 return true; 432 433 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 434 return true; 435 436 return (Previous.getResultKind() == LookupResult::Found 437 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 438} 439 440/// Add this decl to the scope shadowed decl chains. 441void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 442 // Move up the scope chain until we find the nearest enclosing 443 // non-transparent context. The declaration will be introduced into this 444 // scope. 445 while (S->getEntity() && 446 ((DeclContext *)S->getEntity())->isTransparentContext()) 447 S = S->getParent(); 448 449 // Add scoped declarations into their context, so that they can be 450 // found later. Declarations without a context won't be inserted 451 // into any context. 452 if (AddToContext) 453 CurContext->addDecl(D); 454 455 // Out-of-line definitions shouldn't be pushed into scope in C++. 456 // Out-of-line variable and function definitions shouldn't even in C. 457 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 458 D->isOutOfLine()) 459 return; 460 461 // Template instantiations should also not be pushed into scope. 462 if (isa<FunctionDecl>(D) && 463 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 464 return; 465 466 // If this replaces anything in the current scope, 467 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 468 IEnd = IdResolver.end(); 469 for (; I != IEnd; ++I) { 470 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 471 S->RemoveDecl(*I); 472 IdResolver.RemoveDecl(*I); 473 474 // Should only need to replace one decl. 475 break; 476 } 477 } 478 479 S->AddDecl(D); 480 IdResolver.AddDecl(D); 481} 482 483bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) { 484 return IdResolver.isDeclInScope(D, Ctx, Context, S); 485} 486 487Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 488 DeclContext *TargetDC = DC->getPrimaryContext(); 489 do { 490 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 491 if (ScopeDC->getPrimaryContext() == TargetDC) 492 return S; 493 } while ((S = S->getParent())); 494 495 return 0; 496} 497 498static bool isOutOfScopePreviousDeclaration(NamedDecl *, 499 DeclContext*, 500 ASTContext&); 501 502/// Filters out lookup results that don't fall within the given scope 503/// as determined by isDeclInScope. 504static void FilterLookupForScope(Sema &SemaRef, LookupResult &R, 505 DeclContext *Ctx, Scope *S, 506 bool ConsiderLinkage) { 507 LookupResult::Filter F = R.makeFilter(); 508 while (F.hasNext()) { 509 NamedDecl *D = F.next(); 510 511 if (SemaRef.isDeclInScope(D, Ctx, S)) 512 continue; 513 514 if (ConsiderLinkage && 515 isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context)) 516 continue; 517 518 F.erase(); 519 } 520 521 F.done(); 522} 523 524static bool isUsingDecl(NamedDecl *D) { 525 return isa<UsingShadowDecl>(D) || 526 isa<UnresolvedUsingTypenameDecl>(D) || 527 isa<UnresolvedUsingValueDecl>(D); 528} 529 530/// Removes using shadow declarations from the lookup results. 531static void RemoveUsingDecls(LookupResult &R) { 532 LookupResult::Filter F = R.makeFilter(); 533 while (F.hasNext()) 534 if (isUsingDecl(F.next())) 535 F.erase(); 536 537 F.done(); 538} 539 540/// \brief Check for this common pattern: 541/// @code 542/// class S { 543/// S(const S&); // DO NOT IMPLEMENT 544/// void operator=(const S&); // DO NOT IMPLEMENT 545/// }; 546/// @endcode 547static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 548 // FIXME: Should check for private access too but access is set after we get 549 // the decl here. 550 if (D->isThisDeclarationADefinition()) 551 return false; 552 553 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 554 return CD->isCopyConstructor(); 555 return D->isCopyAssignment(); 556} 557 558bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 559 assert(D); 560 561 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 562 return false; 563 564 // Ignore class templates. 565 if (D->getDeclContext()->isDependentContext()) 566 return false; 567 568 // We warn for unused decls internal to the translation unit. 569 if (D->getLinkage() == ExternalLinkage) 570 return false; 571 572 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 573 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 574 return false; 575 576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 577 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 578 return false; 579 } else { 580 // 'static inline' functions are used in headers; don't warn. 581 if (FD->getStorageClass() == FunctionDecl::Static && 582 FD->isInlineSpecified()) 583 return false; 584 } 585 586 if (FD->isThisDeclarationADefinition()) 587 return !Context.DeclMustBeEmitted(FD); 588 return true; 589 } 590 591 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 592 if (VD->isStaticDataMember() && 593 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 594 return false; 595 596 if ( VD->isFileVarDecl() && 597 !VD->getType().isConstant(Context)) 598 return !Context.DeclMustBeEmitted(VD); 599 } 600 601 return false; 602 } 603 604 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 605 if (!D) 606 return; 607 608 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 609 const FunctionDecl *First = FD->getFirstDeclaration(); 610 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 611 return; // First should already be in the vector. 612 } 613 614 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 615 const VarDecl *First = VD->getFirstDeclaration(); 616 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 617 return; // First should already be in the vector. 618 } 619 620 if (ShouldWarnIfUnusedFileScopedDecl(D)) 621 UnusedFileScopedDecls.push_back(D); 622 } 623 624static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 625 if (D->isInvalidDecl()) 626 return false; 627 628 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 629 return false; 630 631 // White-list anything that isn't a local variable. 632 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 633 !D->getDeclContext()->isFunctionOrMethod()) 634 return false; 635 636 // Types of valid local variables should be complete, so this should succeed. 637 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 638 639 // White-list anything with an __attribute__((unused)) type. 640 QualType Ty = VD->getType(); 641 642 // Only look at the outermost level of typedef. 643 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 644 if (TT->getDecl()->hasAttr<UnusedAttr>()) 645 return false; 646 } 647 648 // If we failed to complete the type for some reason, or if the type is 649 // dependent, don't diagnose the variable. 650 if (Ty->isIncompleteType() || Ty->isDependentType()) 651 return false; 652 653 if (const TagType *TT = Ty->getAs<TagType>()) { 654 const TagDecl *Tag = TT->getDecl(); 655 if (Tag->hasAttr<UnusedAttr>()) 656 return false; 657 658 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 659 // FIXME: Checking for the presence of a user-declared constructor 660 // isn't completely accurate; we'd prefer to check that the initializer 661 // has no side effects. 662 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor()) 663 return false; 664 } 665 } 666 667 // TODO: __attribute__((unused)) templates? 668 } 669 670 return true; 671} 672 673void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 674 if (!ShouldDiagnoseUnusedDecl(D)) 675 return; 676 677 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 678 Diag(D->getLocation(), diag::warn_unused_exception_param) 679 << D->getDeclName(); 680 else 681 Diag(D->getLocation(), diag::warn_unused_variable) 682 << D->getDeclName(); 683} 684 685void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 686 if (S->decl_empty()) return; 687 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 688 "Scope shouldn't contain decls!"); 689 690 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 691 I != E; ++I) { 692 Decl *TmpD = (*I); 693 assert(TmpD && "This decl didn't get pushed??"); 694 695 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 696 NamedDecl *D = cast<NamedDecl>(TmpD); 697 698 if (!D->getDeclName()) continue; 699 700 // Diagnose unused variables in this scope. 701 if (S->getNumErrorsAtStart() == getDiagnostics().getNumErrors()) 702 DiagnoseUnusedDecl(D); 703 704 // Remove this name from our lexical scope. 705 IdResolver.RemoveDecl(D); 706 } 707} 708 709/// \brief Look for an Objective-C class in the translation unit. 710/// 711/// \param Id The name of the Objective-C class we're looking for. If 712/// typo-correction fixes this name, the Id will be updated 713/// to the fixed name. 714/// 715/// \param IdLoc The location of the name in the translation unit. 716/// 717/// \param TypoCorrection If true, this routine will attempt typo correction 718/// if there is no class with the given name. 719/// 720/// \returns The declaration of the named Objective-C class, or NULL if the 721/// class could not be found. 722ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 723 SourceLocation IdLoc, 724 bool TypoCorrection) { 725 // The third "scope" argument is 0 since we aren't enabling lazy built-in 726 // creation from this context. 727 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 728 729 if (!IDecl && TypoCorrection) { 730 // Perform typo correction at the given location, but only if we 731 // find an Objective-C class name. 732 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName); 733 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) && 734 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) { 735 Diag(IdLoc, diag::err_undef_interface_suggest) 736 << Id << IDecl->getDeclName() 737 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 738 Diag(IDecl->getLocation(), diag::note_previous_decl) 739 << IDecl->getDeclName(); 740 741 Id = IDecl->getIdentifier(); 742 } 743 } 744 745 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 746} 747 748/// getNonFieldDeclScope - Retrieves the innermost scope, starting 749/// from S, where a non-field would be declared. This routine copes 750/// with the difference between C and C++ scoping rules in structs and 751/// unions. For example, the following code is well-formed in C but 752/// ill-formed in C++: 753/// @code 754/// struct S6 { 755/// enum { BAR } e; 756/// }; 757/// 758/// void test_S6() { 759/// struct S6 a; 760/// a.e = BAR; 761/// } 762/// @endcode 763/// For the declaration of BAR, this routine will return a different 764/// scope. The scope S will be the scope of the unnamed enumeration 765/// within S6. In C++, this routine will return the scope associated 766/// with S6, because the enumeration's scope is a transparent 767/// context but structures can contain non-field names. In C, this 768/// routine will return the translation unit scope, since the 769/// enumeration's scope is a transparent context and structures cannot 770/// contain non-field names. 771Scope *Sema::getNonFieldDeclScope(Scope *S) { 772 while (((S->getFlags() & Scope::DeclScope) == 0) || 773 (S->getEntity() && 774 ((DeclContext *)S->getEntity())->isTransparentContext()) || 775 (S->isClassScope() && !getLangOptions().CPlusPlus)) 776 S = S->getParent(); 777 return S; 778} 779 780void Sema::InitBuiltinVaListType() { 781 if (!Context.getBuiltinVaListType().isNull()) 782 return; 783 784 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 785 NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(), 786 LookupOrdinaryName, ForRedeclaration); 787 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 788 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 789} 790 791/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 792/// file scope. lazily create a decl for it. ForRedeclaration is true 793/// if we're creating this built-in in anticipation of redeclaring the 794/// built-in. 795NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 796 Scope *S, bool ForRedeclaration, 797 SourceLocation Loc) { 798 Builtin::ID BID = (Builtin::ID)bid; 799 800 if (Context.BuiltinInfo.hasVAListUse(BID)) 801 InitBuiltinVaListType(); 802 803 ASTContext::GetBuiltinTypeError Error; 804 QualType R = Context.GetBuiltinType(BID, Error); 805 switch (Error) { 806 case ASTContext::GE_None: 807 // Okay 808 break; 809 810 case ASTContext::GE_Missing_stdio: 811 if (ForRedeclaration) 812 Diag(Loc, diag::err_implicit_decl_requires_stdio) 813 << Context.BuiltinInfo.GetName(BID); 814 return 0; 815 816 case ASTContext::GE_Missing_setjmp: 817 if (ForRedeclaration) 818 Diag(Loc, diag::err_implicit_decl_requires_setjmp) 819 << Context.BuiltinInfo.GetName(BID); 820 return 0; 821 } 822 823 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 824 Diag(Loc, diag::ext_implicit_lib_function_decl) 825 << Context.BuiltinInfo.GetName(BID) 826 << R; 827 if (Context.BuiltinInfo.getHeaderName(BID) && 828 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl) 829 != Diagnostic::Ignored) 830 Diag(Loc, diag::note_please_include_header) 831 << Context.BuiltinInfo.getHeaderName(BID) 832 << Context.BuiltinInfo.GetName(BID); 833 } 834 835 FunctionDecl *New = FunctionDecl::Create(Context, 836 Context.getTranslationUnitDecl(), 837 Loc, II, R, /*TInfo=*/0, 838 FunctionDecl::Extern, 839 FunctionDecl::None, false, 840 /*hasPrototype=*/true); 841 New->setImplicit(); 842 843 // Create Decl objects for each parameter, adding them to the 844 // FunctionDecl. 845 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 846 llvm::SmallVector<ParmVarDecl*, 16> Params; 847 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 848 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 849 FT->getArgType(i), /*TInfo=*/0, 850 VarDecl::None, VarDecl::None, 0)); 851 New->setParams(Params.data(), Params.size()); 852 } 853 854 AddKnownFunctionAttributes(New); 855 856 // TUScope is the translation-unit scope to insert this function into. 857 // FIXME: This is hideous. We need to teach PushOnScopeChains to 858 // relate Scopes to DeclContexts, and probably eliminate CurContext 859 // entirely, but we're not there yet. 860 DeclContext *SavedContext = CurContext; 861 CurContext = Context.getTranslationUnitDecl(); 862 PushOnScopeChains(New, TUScope); 863 CurContext = SavedContext; 864 return New; 865} 866 867/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the 868/// same name and scope as a previous declaration 'Old'. Figure out 869/// how to resolve this situation, merging decls or emitting 870/// diagnostics as appropriate. If there was an error, set New to be invalid. 871/// 872void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) { 873 // If the new decl is known invalid already, don't bother doing any 874 // merging checks. 875 if (New->isInvalidDecl()) return; 876 877 // Allow multiple definitions for ObjC built-in typedefs. 878 // FIXME: Verify the underlying types are equivalent! 879 if (getLangOptions().ObjC1) { 880 const IdentifierInfo *TypeID = New->getIdentifier(); 881 switch (TypeID->getLength()) { 882 default: break; 883 case 2: 884 if (!TypeID->isStr("id")) 885 break; 886 Context.ObjCIdRedefinitionType = New->getUnderlyingType(); 887 // Install the built-in type for 'id', ignoring the current definition. 888 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 889 return; 890 case 5: 891 if (!TypeID->isStr("Class")) 892 break; 893 Context.ObjCClassRedefinitionType = New->getUnderlyingType(); 894 // Install the built-in type for 'Class', ignoring the current definition. 895 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 896 return; 897 case 3: 898 if (!TypeID->isStr("SEL")) 899 break; 900 Context.ObjCSelRedefinitionType = New->getUnderlyingType(); 901 // Install the built-in type for 'SEL', ignoring the current definition. 902 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 903 return; 904 case 8: 905 if (!TypeID->isStr("Protocol")) 906 break; 907 Context.setObjCProtoType(New->getUnderlyingType()); 908 return; 909 } 910 // Fall through - the typedef name was not a builtin type. 911 } 912 913 // Verify the old decl was also a type. 914 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 915 if (!Old) { 916 Diag(New->getLocation(), diag::err_redefinition_different_kind) 917 << New->getDeclName(); 918 919 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 920 if (OldD->getLocation().isValid()) 921 Diag(OldD->getLocation(), diag::note_previous_definition); 922 923 return New->setInvalidDecl(); 924 } 925 926 // If the old declaration is invalid, just give up here. 927 if (Old->isInvalidDecl()) 928 return New->setInvalidDecl(); 929 930 // Determine the "old" type we'll use for checking and diagnostics. 931 QualType OldType; 932 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 933 OldType = OldTypedef->getUnderlyingType(); 934 else 935 OldType = Context.getTypeDeclType(Old); 936 937 // If the typedef types are not identical, reject them in all languages and 938 // with any extensions enabled. 939 940 if (OldType != New->getUnderlyingType() && 941 Context.getCanonicalType(OldType) != 942 Context.getCanonicalType(New->getUnderlyingType())) { 943 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 944 << New->getUnderlyingType() << OldType; 945 if (Old->getLocation().isValid()) 946 Diag(Old->getLocation(), diag::note_previous_definition); 947 return New->setInvalidDecl(); 948 } 949 950 // The types match. Link up the redeclaration chain if the old 951 // declaration was a typedef. 952 // FIXME: this is a potential source of wierdness if the type 953 // spellings don't match exactly. 954 if (isa<TypedefDecl>(Old)) 955 New->setPreviousDeclaration(cast<TypedefDecl>(Old)); 956 957 if (getLangOptions().Microsoft) 958 return; 959 960 if (getLangOptions().CPlusPlus) { 961 // C++ [dcl.typedef]p2: 962 // In a given non-class scope, a typedef specifier can be used to 963 // redefine the name of any type declared in that scope to refer 964 // to the type to which it already refers. 965 if (!isa<CXXRecordDecl>(CurContext)) 966 return; 967 968 // C++0x [dcl.typedef]p4: 969 // In a given class scope, a typedef specifier can be used to redefine 970 // any class-name declared in that scope that is not also a typedef-name 971 // to refer to the type to which it already refers. 972 // 973 // This wording came in via DR424, which was a correction to the 974 // wording in DR56, which accidentally banned code like: 975 // 976 // struct S { 977 // typedef struct A { } A; 978 // }; 979 // 980 // in the C++03 standard. We implement the C++0x semantics, which 981 // allow the above but disallow 982 // 983 // struct S { 984 // typedef int I; 985 // typedef int I; 986 // }; 987 // 988 // since that was the intent of DR56. 989 if (!isa<TypedefDecl >(Old)) 990 return; 991 992 Diag(New->getLocation(), diag::err_redefinition) 993 << New->getDeclName(); 994 Diag(Old->getLocation(), diag::note_previous_definition); 995 return New->setInvalidDecl(); 996 } 997 998 // If we have a redefinition of a typedef in C, emit a warning. This warning 999 // is normally mapped to an error, but can be controlled with 1000 // -Wtypedef-redefinition. If either the original or the redefinition is 1001 // in a system header, don't emit this for compatibility with GCC. 1002 if (getDiagnostics().getSuppressSystemWarnings() && 1003 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1004 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1005 return; 1006 1007 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1008 << New->getDeclName(); 1009 Diag(Old->getLocation(), diag::note_previous_definition); 1010 return; 1011} 1012 1013/// DeclhasAttr - returns true if decl Declaration already has the target 1014/// attribute. 1015static bool 1016DeclHasAttr(const Decl *D, const Attr *A) { 1017 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1018 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1019 if ((*i)->getKind() == A->getKind()) { 1020 // FIXME: Don't hardcode this check 1021 if (OA && isa<OwnershipAttr>(*i)) 1022 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1023 return true; 1024 } 1025 1026 return false; 1027} 1028 1029/// MergeDeclAttributes - append attributes from the Old decl to the New one. 1030static void MergeDeclAttributes(Decl *New, Decl *Old, ASTContext &C) { 1031 if (!Old->hasAttrs()) 1032 return; 1033 // Ensure that any moving of objects within the allocated map is done before 1034 // we process them. 1035 if (!New->hasAttrs()) 1036 New->setAttrs(AttrVec()); 1037 for (Decl::attr_iterator i = Old->attr_begin(), e = Old->attr_end(); i != e; 1038 ++i) { 1039 // FIXME: Make this more general than just checking for Overloadable. 1040 if (!DeclHasAttr(New, *i) && (*i)->getKind() != attr::Overloadable) { 1041 Attr *NewAttr = (*i)->clone(C); 1042 NewAttr->setInherited(true); 1043 New->addAttr(NewAttr); 1044 } 1045 } 1046} 1047 1048namespace { 1049 1050/// Used in MergeFunctionDecl to keep track of function parameters in 1051/// C. 1052struct GNUCompatibleParamWarning { 1053 ParmVarDecl *OldParm; 1054 ParmVarDecl *NewParm; 1055 QualType PromotedType; 1056}; 1057 1058} 1059 1060/// getSpecialMember - get the special member enum for a method. 1061Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1062 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1063 if (Ctor->isCopyConstructor()) 1064 return Sema::CXXCopyConstructor; 1065 1066 return Sema::CXXConstructor; 1067 } 1068 1069 if (isa<CXXDestructorDecl>(MD)) 1070 return Sema::CXXDestructor; 1071 1072 assert(MD->isCopyAssignment() && "Must have copy assignment operator"); 1073 return Sema::CXXCopyAssignment; 1074} 1075 1076/// canRedefineFunction - checks if a function can be redefined. Currently, 1077/// only extern inline functions can be redefined, and even then only in 1078/// GNU89 mode. 1079static bool canRedefineFunction(const FunctionDecl *FD, 1080 const LangOptions& LangOpts) { 1081 return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus && 1082 FD->isInlineSpecified() && 1083 FD->getStorageClass() == FunctionDecl::Extern); 1084} 1085 1086/// MergeFunctionDecl - We just parsed a function 'New' from 1087/// declarator D which has the same name and scope as a previous 1088/// declaration 'Old'. Figure out how to resolve this situation, 1089/// merging decls or emitting diagnostics as appropriate. 1090/// 1091/// In C++, New and Old must be declarations that are not 1092/// overloaded. Use IsOverload to determine whether New and Old are 1093/// overloaded, and to select the Old declaration that New should be 1094/// merged with. 1095/// 1096/// Returns true if there was an error, false otherwise. 1097bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 1098 // Verify the old decl was also a function. 1099 FunctionDecl *Old = 0; 1100 if (FunctionTemplateDecl *OldFunctionTemplate 1101 = dyn_cast<FunctionTemplateDecl>(OldD)) 1102 Old = OldFunctionTemplate->getTemplatedDecl(); 1103 else 1104 Old = dyn_cast<FunctionDecl>(OldD); 1105 if (!Old) { 1106 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1107 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1108 Diag(Shadow->getTargetDecl()->getLocation(), 1109 diag::note_using_decl_target); 1110 Diag(Shadow->getUsingDecl()->getLocation(), 1111 diag::note_using_decl) << 0; 1112 return true; 1113 } 1114 1115 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1116 << New->getDeclName(); 1117 Diag(OldD->getLocation(), diag::note_previous_definition); 1118 return true; 1119 } 1120 1121 // Determine whether the previous declaration was a definition, 1122 // implicit declaration, or a declaration. 1123 diag::kind PrevDiag; 1124 if (Old->isThisDeclarationADefinition()) 1125 PrevDiag = diag::note_previous_definition; 1126 else if (Old->isImplicit()) 1127 PrevDiag = diag::note_previous_implicit_declaration; 1128 else 1129 PrevDiag = diag::note_previous_declaration; 1130 1131 QualType OldQType = Context.getCanonicalType(Old->getType()); 1132 QualType NewQType = Context.getCanonicalType(New->getType()); 1133 1134 // Don't complain about this if we're in GNU89 mode and the old function 1135 // is an extern inline function. 1136 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1137 New->getStorageClass() == FunctionDecl::Static && 1138 Old->getStorageClass() != FunctionDecl::Static && 1139 !canRedefineFunction(Old, getLangOptions())) { 1140 Diag(New->getLocation(), diag::err_static_non_static) 1141 << New; 1142 Diag(Old->getLocation(), PrevDiag); 1143 return true; 1144 } 1145 1146 // If a function is first declared with a calling convention, but is 1147 // later declared or defined without one, the second decl assumes the 1148 // calling convention of the first. 1149 // 1150 // For the new decl, we have to look at the NON-canonical type to tell the 1151 // difference between a function that really doesn't have a calling 1152 // convention and one that is declared cdecl. That's because in 1153 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1154 // because it is the default calling convention. 1155 // 1156 // Note also that we DO NOT return at this point, because we still have 1157 // other tests to run. 1158 const FunctionType *OldType = OldQType->getAs<FunctionType>(); 1159 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 1160 const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 1161 const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 1162 if (OldTypeInfo.getCC() != CC_Default && 1163 NewTypeInfo.getCC() == CC_Default) { 1164 NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC()); 1165 New->setType(NewQType); 1166 NewQType = Context.getCanonicalType(NewQType); 1167 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 1168 NewTypeInfo.getCC())) { 1169 // Calling conventions really aren't compatible, so complain. 1170 Diag(New->getLocation(), diag::err_cconv_change) 1171 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 1172 << (OldTypeInfo.getCC() == CC_Default) 1173 << (OldTypeInfo.getCC() == CC_Default ? "" : 1174 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 1175 Diag(Old->getLocation(), diag::note_previous_declaration); 1176 return true; 1177 } 1178 1179 // FIXME: diagnose the other way around? 1180 if (OldType->getNoReturnAttr() && !NewType->getNoReturnAttr()) { 1181 NewQType = Context.getNoReturnType(NewQType); 1182 New->setType(NewQType); 1183 assert(NewQType.isCanonical()); 1184 } 1185 1186 // Merge regparm attribute. 1187 if (OldType->getRegParmType() != NewType->getRegParmType()) { 1188 if (NewType->getRegParmType()) { 1189 Diag(New->getLocation(), diag::err_regparm_mismatch) 1190 << NewType->getRegParmType() 1191 << OldType->getRegParmType(); 1192 Diag(Old->getLocation(), diag::note_previous_declaration); 1193 return true; 1194 } 1195 1196 NewQType = Context.getRegParmType(NewQType, OldType->getRegParmType()); 1197 New->setType(NewQType); 1198 assert(NewQType.isCanonical()); 1199 } 1200 1201 if (getLangOptions().CPlusPlus) { 1202 // (C++98 13.1p2): 1203 // Certain function declarations cannot be overloaded: 1204 // -- Function declarations that differ only in the return type 1205 // cannot be overloaded. 1206 QualType OldReturnType 1207 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 1208 QualType NewReturnType 1209 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 1210 QualType ResQT; 1211 if (OldReturnType != NewReturnType) { 1212 if (NewReturnType->isObjCObjectPointerType() 1213 && OldReturnType->isObjCObjectPointerType()) 1214 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 1215 if (ResQT.isNull()) { 1216 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 1217 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1218 return true; 1219 } 1220 else 1221 NewQType = ResQT; 1222 } 1223 1224 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1225 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1226 if (OldMethod && NewMethod) { 1227 // Preserve triviality. 1228 NewMethod->setTrivial(OldMethod->isTrivial()); 1229 1230 bool isFriend = NewMethod->getFriendObjectKind(); 1231 1232 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) { 1233 // -- Member function declarations with the same name and the 1234 // same parameter types cannot be overloaded if any of them 1235 // is a static member function declaration. 1236 if (OldMethod->isStatic() || NewMethod->isStatic()) { 1237 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 1238 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1239 return true; 1240 } 1241 1242 // C++ [class.mem]p1: 1243 // [...] A member shall not be declared twice in the 1244 // member-specification, except that a nested class or member 1245 // class template can be declared and then later defined. 1246 unsigned NewDiag; 1247 if (isa<CXXConstructorDecl>(OldMethod)) 1248 NewDiag = diag::err_constructor_redeclared; 1249 else if (isa<CXXDestructorDecl>(NewMethod)) 1250 NewDiag = diag::err_destructor_redeclared; 1251 else if (isa<CXXConversionDecl>(NewMethod)) 1252 NewDiag = diag::err_conv_function_redeclared; 1253 else 1254 NewDiag = diag::err_member_redeclared; 1255 1256 Diag(New->getLocation(), NewDiag); 1257 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1258 1259 // Complain if this is an explicit declaration of a special 1260 // member that was initially declared implicitly. 1261 // 1262 // As an exception, it's okay to befriend such methods in order 1263 // to permit the implicit constructor/destructor/operator calls. 1264 } else if (OldMethod->isImplicit()) { 1265 if (isFriend) { 1266 NewMethod->setImplicit(); 1267 } else { 1268 Diag(NewMethod->getLocation(), 1269 diag::err_definition_of_implicitly_declared_member) 1270 << New << getSpecialMember(OldMethod); 1271 return true; 1272 } 1273 } 1274 } 1275 1276 // (C++98 8.3.5p3): 1277 // All declarations for a function shall agree exactly in both the 1278 // return type and the parameter-type-list. 1279 // attributes should be ignored when comparing. 1280 if (Context.getNoReturnType(OldQType, false) == 1281 Context.getNoReturnType(NewQType, false)) 1282 return MergeCompatibleFunctionDecls(New, Old); 1283 1284 // Fall through for conflicting redeclarations and redefinitions. 1285 } 1286 1287 // C: Function types need to be compatible, not identical. This handles 1288 // duplicate function decls like "void f(int); void f(enum X);" properly. 1289 if (!getLangOptions().CPlusPlus && 1290 Context.typesAreCompatible(OldQType, NewQType)) { 1291 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 1292 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 1293 const FunctionProtoType *OldProto = 0; 1294 if (isa<FunctionNoProtoType>(NewFuncType) && 1295 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 1296 // The old declaration provided a function prototype, but the 1297 // new declaration does not. Merge in the prototype. 1298 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 1299 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 1300 OldProto->arg_type_end()); 1301 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 1302 ParamTypes.data(), ParamTypes.size(), 1303 OldProto->isVariadic(), 1304 OldProto->getTypeQuals(), 1305 false, false, 0, 0, 1306 OldProto->getExtInfo()); 1307 New->setType(NewQType); 1308 New->setHasInheritedPrototype(); 1309 1310 // Synthesize a parameter for each argument type. 1311 llvm::SmallVector<ParmVarDecl*, 16> Params; 1312 for (FunctionProtoType::arg_type_iterator 1313 ParamType = OldProto->arg_type_begin(), 1314 ParamEnd = OldProto->arg_type_end(); 1315 ParamType != ParamEnd; ++ParamType) { 1316 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 1317 SourceLocation(), 0, 1318 *ParamType, /*TInfo=*/0, 1319 VarDecl::None, VarDecl::None, 1320 0); 1321 Param->setImplicit(); 1322 Params.push_back(Param); 1323 } 1324 1325 New->setParams(Params.data(), Params.size()); 1326 } 1327 1328 return MergeCompatibleFunctionDecls(New, Old); 1329 } 1330 1331 // GNU C permits a K&R definition to follow a prototype declaration 1332 // if the declared types of the parameters in the K&R definition 1333 // match the types in the prototype declaration, even when the 1334 // promoted types of the parameters from the K&R definition differ 1335 // from the types in the prototype. GCC then keeps the types from 1336 // the prototype. 1337 // 1338 // If a variadic prototype is followed by a non-variadic K&R definition, 1339 // the K&R definition becomes variadic. This is sort of an edge case, but 1340 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 1341 // C99 6.9.1p8. 1342 if (!getLangOptions().CPlusPlus && 1343 Old->hasPrototype() && !New->hasPrototype() && 1344 New->getType()->getAs<FunctionProtoType>() && 1345 Old->getNumParams() == New->getNumParams()) { 1346 llvm::SmallVector<QualType, 16> ArgTypes; 1347 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 1348 const FunctionProtoType *OldProto 1349 = Old->getType()->getAs<FunctionProtoType>(); 1350 const FunctionProtoType *NewProto 1351 = New->getType()->getAs<FunctionProtoType>(); 1352 1353 // Determine whether this is the GNU C extension. 1354 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 1355 NewProto->getResultType()); 1356 bool LooseCompatible = !MergedReturn.isNull(); 1357 for (unsigned Idx = 0, End = Old->getNumParams(); 1358 LooseCompatible && Idx != End; ++Idx) { 1359 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 1360 ParmVarDecl *NewParm = New->getParamDecl(Idx); 1361 if (Context.typesAreCompatible(OldParm->getType(), 1362 NewProto->getArgType(Idx))) { 1363 ArgTypes.push_back(NewParm->getType()); 1364 } else if (Context.typesAreCompatible(OldParm->getType(), 1365 NewParm->getType(), 1366 /*CompareUnqualified=*/true)) { 1367 GNUCompatibleParamWarning Warn 1368 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 1369 Warnings.push_back(Warn); 1370 ArgTypes.push_back(NewParm->getType()); 1371 } else 1372 LooseCompatible = false; 1373 } 1374 1375 if (LooseCompatible) { 1376 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 1377 Diag(Warnings[Warn].NewParm->getLocation(), 1378 diag::ext_param_promoted_not_compatible_with_prototype) 1379 << Warnings[Warn].PromotedType 1380 << Warnings[Warn].OldParm->getType(); 1381 if (Warnings[Warn].OldParm->getLocation().isValid()) 1382 Diag(Warnings[Warn].OldParm->getLocation(), 1383 diag::note_previous_declaration); 1384 } 1385 1386 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 1387 ArgTypes.size(), 1388 OldProto->isVariadic(), 0, 1389 false, false, 0, 0, 1390 OldProto->getExtInfo())); 1391 return MergeCompatibleFunctionDecls(New, Old); 1392 } 1393 1394 // Fall through to diagnose conflicting types. 1395 } 1396 1397 // A function that has already been declared has been redeclared or defined 1398 // with a different type- show appropriate diagnostic 1399 if (unsigned BuiltinID = Old->getBuiltinID()) { 1400 // The user has declared a builtin function with an incompatible 1401 // signature. 1402 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 1403 // The function the user is redeclaring is a library-defined 1404 // function like 'malloc' or 'printf'. Warn about the 1405 // redeclaration, then pretend that we don't know about this 1406 // library built-in. 1407 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 1408 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 1409 << Old << Old->getType(); 1410 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 1411 Old->setInvalidDecl(); 1412 return false; 1413 } 1414 1415 PrevDiag = diag::note_previous_builtin_declaration; 1416 } 1417 1418 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 1419 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1420 return true; 1421} 1422 1423/// \brief Completes the merge of two function declarations that are 1424/// known to be compatible. 1425/// 1426/// This routine handles the merging of attributes and other 1427/// properties of function declarations form the old declaration to 1428/// the new declaration, once we know that New is in fact a 1429/// redeclaration of Old. 1430/// 1431/// \returns false 1432bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 1433 // Merge the attributes 1434 MergeDeclAttributes(New, Old, Context); 1435 1436 // Merge the storage class. 1437 if (Old->getStorageClass() != FunctionDecl::Extern && 1438 Old->getStorageClass() != FunctionDecl::None) 1439 New->setStorageClass(Old->getStorageClass()); 1440 1441 // Merge "pure" flag. 1442 if (Old->isPure()) 1443 New->setPure(); 1444 1445 // Merge the "deleted" flag. 1446 if (Old->isDeleted()) 1447 New->setDeleted(); 1448 1449 if (getLangOptions().CPlusPlus) 1450 return MergeCXXFunctionDecl(New, Old); 1451 1452 return false; 1453} 1454 1455/// MergeVarDecl - We just parsed a variable 'New' which has the same name 1456/// and scope as a previous declaration 'Old'. Figure out how to resolve this 1457/// situation, merging decls or emitting diagnostics as appropriate. 1458/// 1459/// Tentative definition rules (C99 6.9.2p2) are checked by 1460/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 1461/// definitions here, since the initializer hasn't been attached. 1462/// 1463void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 1464 // If the new decl is already invalid, don't do any other checking. 1465 if (New->isInvalidDecl()) 1466 return; 1467 1468 // Verify the old decl was also a variable. 1469 VarDecl *Old = 0; 1470 if (!Previous.isSingleResult() || 1471 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 1472 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1473 << New->getDeclName(); 1474 Diag(Previous.getRepresentativeDecl()->getLocation(), 1475 diag::note_previous_definition); 1476 return New->setInvalidDecl(); 1477 } 1478 1479 MergeDeclAttributes(New, Old, Context); 1480 1481 // Merge the types 1482 QualType MergedT; 1483 if (getLangOptions().CPlusPlus) { 1484 if (Context.hasSameType(New->getType(), Old->getType())) 1485 MergedT = New->getType(); 1486 // C++ [basic.link]p10: 1487 // [...] the types specified by all declarations referring to a given 1488 // object or function shall be identical, except that declarations for an 1489 // array object can specify array types that differ by the presence or 1490 // absence of a major array bound (8.3.4). 1491 else if (Old->getType()->isIncompleteArrayType() && 1492 New->getType()->isArrayType()) { 1493 CanQual<ArrayType> OldArray 1494 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 1495 CanQual<ArrayType> NewArray 1496 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 1497 if (OldArray->getElementType() == NewArray->getElementType()) 1498 MergedT = New->getType(); 1499 } else if (Old->getType()->isArrayType() && 1500 New->getType()->isIncompleteArrayType()) { 1501 CanQual<ArrayType> OldArray 1502 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 1503 CanQual<ArrayType> NewArray 1504 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 1505 if (OldArray->getElementType() == NewArray->getElementType()) 1506 MergedT = Old->getType(); 1507 } else if (New->getType()->isObjCObjectPointerType() 1508 && Old->getType()->isObjCObjectPointerType()) { 1509 MergedT = Context.mergeObjCGCQualifiers(New->getType(), Old->getType()); 1510 } 1511 } else { 1512 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 1513 } 1514 if (MergedT.isNull()) { 1515 Diag(New->getLocation(), diag::err_redefinition_different_type) 1516 << New->getDeclName(); 1517 Diag(Old->getLocation(), diag::note_previous_definition); 1518 return New->setInvalidDecl(); 1519 } 1520 New->setType(MergedT); 1521 1522 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 1523 if (New->getStorageClass() == VarDecl::Static && 1524 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) { 1525 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 1526 Diag(Old->getLocation(), diag::note_previous_definition); 1527 return New->setInvalidDecl(); 1528 } 1529 // C99 6.2.2p4: 1530 // For an identifier declared with the storage-class specifier 1531 // extern in a scope in which a prior declaration of that 1532 // identifier is visible,23) if the prior declaration specifies 1533 // internal or external linkage, the linkage of the identifier at 1534 // the later declaration is the same as the linkage specified at 1535 // the prior declaration. If no prior declaration is visible, or 1536 // if the prior declaration specifies no linkage, then the 1537 // identifier has external linkage. 1538 if (New->hasExternalStorage() && Old->hasLinkage()) 1539 /* Okay */; 1540 else if (New->getStorageClass() != VarDecl::Static && 1541 Old->getStorageClass() == VarDecl::Static) { 1542 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 1543 Diag(Old->getLocation(), diag::note_previous_definition); 1544 return New->setInvalidDecl(); 1545 } 1546 1547 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 1548 1549 // FIXME: The test for external storage here seems wrong? We still 1550 // need to check for mismatches. 1551 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 1552 // Don't complain about out-of-line definitions of static members. 1553 !(Old->getLexicalDeclContext()->isRecord() && 1554 !New->getLexicalDeclContext()->isRecord())) { 1555 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 1556 Diag(Old->getLocation(), diag::note_previous_definition); 1557 return New->setInvalidDecl(); 1558 } 1559 1560 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 1561 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 1562 Diag(Old->getLocation(), diag::note_previous_definition); 1563 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 1564 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 1565 Diag(Old->getLocation(), diag::note_previous_definition); 1566 } 1567 1568 // C++ doesn't have tentative definitions, so go right ahead and check here. 1569 const VarDecl *Def; 1570 if (getLangOptions().CPlusPlus && 1571 New->isThisDeclarationADefinition() == VarDecl::Definition && 1572 (Def = Old->getDefinition())) { 1573 Diag(New->getLocation(), diag::err_redefinition) 1574 << New->getDeclName(); 1575 Diag(Def->getLocation(), diag::note_previous_definition); 1576 New->setInvalidDecl(); 1577 return; 1578 } 1579 // c99 6.2.2 P4. 1580 // For an identifier declared with the storage-class specifier extern in a 1581 // scope in which a prior declaration of that identifier is visible, if 1582 // the prior declaration specifies internal or external linkage, the linkage 1583 // of the identifier at the later declaration is the same as the linkage 1584 // specified at the prior declaration. 1585 // FIXME. revisit this code. 1586 if (New->hasExternalStorage() && 1587 Old->getLinkage() == InternalLinkage && 1588 New->getDeclContext() == Old->getDeclContext()) 1589 New->setStorageClass(Old->getStorageClass()); 1590 1591 // Keep a chain of previous declarations. 1592 New->setPreviousDeclaration(Old); 1593 1594 // Inherit access appropriately. 1595 New->setAccess(Old->getAccess()); 1596} 1597 1598/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 1599/// no declarator (e.g. "struct foo;") is parsed. 1600Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1601 DeclSpec &DS) { 1602 // FIXME: Error on auto/register at file scope 1603 // FIXME: Error on inline/virtual/explicit 1604 // FIXME: Warn on useless __thread 1605 // FIXME: Warn on useless const/volatile 1606 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable 1607 // FIXME: Warn on useless attributes 1608 Decl *TagD = 0; 1609 TagDecl *Tag = 0; 1610 if (DS.getTypeSpecType() == DeclSpec::TST_class || 1611 DS.getTypeSpecType() == DeclSpec::TST_struct || 1612 DS.getTypeSpecType() == DeclSpec::TST_union || 1613 DS.getTypeSpecType() == DeclSpec::TST_enum) { 1614 TagD = DS.getRepAsDecl(); 1615 1616 if (!TagD) // We probably had an error 1617 return 0; 1618 1619 // Note that the above type specs guarantee that the 1620 // type rep is a Decl, whereas in many of the others 1621 // it's a Type. 1622 Tag = dyn_cast<TagDecl>(TagD); 1623 } 1624 1625 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 1626 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 1627 // or incomplete types shall not be restrict-qualified." 1628 if (TypeQuals & DeclSpec::TQ_restrict) 1629 Diag(DS.getRestrictSpecLoc(), 1630 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 1631 << DS.getSourceRange(); 1632 } 1633 1634 if (DS.isFriendSpecified()) { 1635 // If we're dealing with a class template decl, assume that the 1636 // template routines are handling it. 1637 if (TagD && isa<ClassTemplateDecl>(TagD)) 1638 return 0; 1639 return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0)); 1640 } 1641 1642 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 1643 ProcessDeclAttributeList(S, Record, DS.getAttributes()); 1644 1645 if (!Record->getDeclName() && Record->isDefinition() && 1646 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 1647 if (getLangOptions().CPlusPlus || 1648 Record->getDeclContext()->isRecord()) 1649 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 1650 1651 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 1652 << DS.getSourceRange(); 1653 } 1654 1655 // Microsoft allows unnamed struct/union fields. Don't complain 1656 // about them. 1657 // FIXME: Should we support Microsoft's extensions in this area? 1658 if (Record->getDeclName() && getLangOptions().Microsoft) 1659 return Tag; 1660 } 1661 1662 if (getLangOptions().CPlusPlus && 1663 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 1664 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 1665 if (Enum->enumerator_begin() == Enum->enumerator_end() && 1666 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 1667 Diag(Enum->getLocation(), diag::ext_no_declarators) 1668 << DS.getSourceRange(); 1669 1670 if (!DS.isMissingDeclaratorOk() && 1671 DS.getTypeSpecType() != DeclSpec::TST_error) { 1672 // Warn about typedefs of enums without names, since this is an 1673 // extension in both Microsoft and GNU. 1674 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 1675 Tag && isa<EnumDecl>(Tag)) { 1676 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 1677 << DS.getSourceRange(); 1678 return Tag; 1679 } 1680 1681 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 1682 << DS.getSourceRange(); 1683 } 1684 1685 return TagD; 1686} 1687 1688/// We are trying to inject an anonymous member into the given scope; 1689/// check if there's an existing declaration that can't be overloaded. 1690/// 1691/// \return true if this is a forbidden redeclaration 1692static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 1693 Scope *S, 1694 DeclContext *Owner, 1695 DeclarationName Name, 1696 SourceLocation NameLoc, 1697 unsigned diagnostic) { 1698 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 1699 Sema::ForRedeclaration); 1700 if (!SemaRef.LookupName(R, S)) return false; 1701 1702 if (R.getAsSingle<TagDecl>()) 1703 return false; 1704 1705 // Pick a representative declaration. 1706 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 1707 if (PrevDecl && Owner->isRecord()) { 1708 RecordDecl *Record = cast<RecordDecl>(Owner); 1709 if (!SemaRef.isDeclInScope(PrevDecl, Record, S)) 1710 return false; 1711 } 1712 1713 SemaRef.Diag(NameLoc, diagnostic) << Name; 1714 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 1715 1716 return true; 1717} 1718 1719/// InjectAnonymousStructOrUnionMembers - Inject the members of the 1720/// anonymous struct or union AnonRecord into the owning context Owner 1721/// and scope S. This routine will be invoked just after we realize 1722/// that an unnamed union or struct is actually an anonymous union or 1723/// struct, e.g., 1724/// 1725/// @code 1726/// union { 1727/// int i; 1728/// float f; 1729/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 1730/// // f into the surrounding scope.x 1731/// @endcode 1732/// 1733/// This routine is recursive, injecting the names of nested anonymous 1734/// structs/unions into the owning context and scope as well. 1735static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 1736 DeclContext *Owner, 1737 RecordDecl *AnonRecord, 1738 AccessSpecifier AS) { 1739 unsigned diagKind 1740 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 1741 : diag::err_anonymous_struct_member_redecl; 1742 1743 bool Invalid = false; 1744 for (RecordDecl::field_iterator F = AnonRecord->field_begin(), 1745 FEnd = AnonRecord->field_end(); 1746 F != FEnd; ++F) { 1747 if ((*F)->getDeclName()) { 1748 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, (*F)->getDeclName(), 1749 (*F)->getLocation(), diagKind)) { 1750 // C++ [class.union]p2: 1751 // The names of the members of an anonymous union shall be 1752 // distinct from the names of any other entity in the 1753 // scope in which the anonymous union is declared. 1754 Invalid = true; 1755 } else { 1756 // C++ [class.union]p2: 1757 // For the purpose of name lookup, after the anonymous union 1758 // definition, the members of the anonymous union are 1759 // considered to have been defined in the scope in which the 1760 // anonymous union is declared. 1761 Owner->makeDeclVisibleInContext(*F); 1762 S->AddDecl(*F); 1763 SemaRef.IdResolver.AddDecl(*F); 1764 1765 // That includes picking up the appropriate access specifier. 1766 if (AS != AS_none) (*F)->setAccess(AS); 1767 } 1768 } else if (const RecordType *InnerRecordType 1769 = (*F)->getType()->getAs<RecordType>()) { 1770 RecordDecl *InnerRecord = InnerRecordType->getDecl(); 1771 if (InnerRecord->isAnonymousStructOrUnion()) 1772 Invalid = Invalid || 1773 InjectAnonymousStructOrUnionMembers(SemaRef, S, Owner, 1774 InnerRecord, AS); 1775 } 1776 } 1777 1778 return Invalid; 1779} 1780 1781/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 1782/// a VarDecl::StorageClass. Any error reporting is up to the caller: 1783/// illegal input values are mapped to VarDecl::None. 1784static VarDecl::StorageClass 1785StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 1786 switch (StorageClassSpec) { 1787 case DeclSpec::SCS_unspecified: return VarDecl::None; 1788 case DeclSpec::SCS_extern: return VarDecl::Extern; 1789 case DeclSpec::SCS_static: return VarDecl::Static; 1790 case DeclSpec::SCS_auto: return VarDecl::Auto; 1791 case DeclSpec::SCS_register: return VarDecl::Register; 1792 case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern; 1793 // Illegal SCSs map to None: error reporting is up to the caller. 1794 case DeclSpec::SCS_mutable: // Fall through. 1795 case DeclSpec::SCS_typedef: return VarDecl::None; 1796 } 1797 llvm_unreachable("unknown storage class specifier"); 1798} 1799 1800/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 1801/// a FunctionDecl::StorageClass. Any error reporting is up to the caller: 1802/// illegal input values are mapped to FunctionDecl::None. 1803static FunctionDecl::StorageClass 1804StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 1805 switch (StorageClassSpec) { 1806 case DeclSpec::SCS_unspecified: return FunctionDecl::None; 1807 case DeclSpec::SCS_extern: return FunctionDecl::Extern; 1808 case DeclSpec::SCS_static: return FunctionDecl::Static; 1809 case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern; 1810 // Illegal SCSs map to None: error reporting is up to the caller. 1811 case DeclSpec::SCS_auto: // Fall through. 1812 case DeclSpec::SCS_mutable: // Fall through. 1813 case DeclSpec::SCS_register: // Fall through. 1814 case DeclSpec::SCS_typedef: return FunctionDecl::None; 1815 } 1816 llvm_unreachable("unknown storage class specifier"); 1817} 1818 1819/// ActOnAnonymousStructOrUnion - Handle the declaration of an 1820/// anonymous structure or union. Anonymous unions are a C++ feature 1821/// (C++ [class.union]) and a GNU C extension; anonymous structures 1822/// are a GNU C and GNU C++ extension. 1823Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1824 AccessSpecifier AS, 1825 RecordDecl *Record) { 1826 DeclContext *Owner = Record->getDeclContext(); 1827 1828 // Diagnose whether this anonymous struct/union is an extension. 1829 if (Record->isUnion() && !getLangOptions().CPlusPlus) 1830 Diag(Record->getLocation(), diag::ext_anonymous_union); 1831 else if (!Record->isUnion()) 1832 Diag(Record->getLocation(), diag::ext_anonymous_struct); 1833 1834 // C and C++ require different kinds of checks for anonymous 1835 // structs/unions. 1836 bool Invalid = false; 1837 if (getLangOptions().CPlusPlus) { 1838 const char* PrevSpec = 0; 1839 unsigned DiagID; 1840 // C++ [class.union]p3: 1841 // Anonymous unions declared in a named namespace or in the 1842 // global namespace shall be declared static. 1843 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 1844 (isa<TranslationUnitDecl>(Owner) || 1845 (isa<NamespaceDecl>(Owner) && 1846 cast<NamespaceDecl>(Owner)->getDeclName()))) { 1847 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 1848 Invalid = true; 1849 1850 // Recover by adding 'static'. 1851 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 1852 PrevSpec, DiagID); 1853 } 1854 // C++ [class.union]p3: 1855 // A storage class is not allowed in a declaration of an 1856 // anonymous union in a class scope. 1857 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1858 isa<RecordDecl>(Owner)) { 1859 Diag(DS.getStorageClassSpecLoc(), 1860 diag::err_anonymous_union_with_storage_spec); 1861 Invalid = true; 1862 1863 // Recover by removing the storage specifier. 1864 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 1865 PrevSpec, DiagID); 1866 } 1867 1868 // C++ [class.union]p2: 1869 // The member-specification of an anonymous union shall only 1870 // define non-static data members. [Note: nested types and 1871 // functions cannot be declared within an anonymous union. ] 1872 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 1873 MemEnd = Record->decls_end(); 1874 Mem != MemEnd; ++Mem) { 1875 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 1876 // C++ [class.union]p3: 1877 // An anonymous union shall not have private or protected 1878 // members (clause 11). 1879 assert(FD->getAccess() != AS_none); 1880 if (FD->getAccess() != AS_public) { 1881 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 1882 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 1883 Invalid = true; 1884 } 1885 1886 if (CheckNontrivialField(FD)) 1887 Invalid = true; 1888 } else if ((*Mem)->isImplicit()) { 1889 // Any implicit members are fine. 1890 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 1891 // This is a type that showed up in an 1892 // elaborated-type-specifier inside the anonymous struct or 1893 // union, but which actually declares a type outside of the 1894 // anonymous struct or union. It's okay. 1895 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 1896 if (!MemRecord->isAnonymousStructOrUnion() && 1897 MemRecord->getDeclName()) { 1898 // This is a nested type declaration. 1899 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 1900 << (int)Record->isUnion(); 1901 Invalid = true; 1902 } 1903 } else if (isa<AccessSpecDecl>(*Mem)) { 1904 // Any access specifier is fine. 1905 } else { 1906 // We have something that isn't a non-static data 1907 // member. Complain about it. 1908 unsigned DK = diag::err_anonymous_record_bad_member; 1909 if (isa<TypeDecl>(*Mem)) 1910 DK = diag::err_anonymous_record_with_type; 1911 else if (isa<FunctionDecl>(*Mem)) 1912 DK = diag::err_anonymous_record_with_function; 1913 else if (isa<VarDecl>(*Mem)) 1914 DK = diag::err_anonymous_record_with_static; 1915 Diag((*Mem)->getLocation(), DK) 1916 << (int)Record->isUnion(); 1917 Invalid = true; 1918 } 1919 } 1920 } 1921 1922 if (!Record->isUnion() && !Owner->isRecord()) { 1923 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 1924 << (int)getLangOptions().CPlusPlus; 1925 Invalid = true; 1926 } 1927 1928 // Mock up a declarator. 1929 Declarator Dc(DS, Declarator::TypeNameContext); 1930 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 1931 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 1932 1933 // Create a declaration for this anonymous struct/union. 1934 NamedDecl *Anon = 0; 1935 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 1936 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 1937 /*IdentifierInfo=*/0, 1938 Context.getTypeDeclType(Record), 1939 TInfo, 1940 /*BitWidth=*/0, /*Mutable=*/false); 1941 Anon->setAccess(AS); 1942 if (getLangOptions().CPlusPlus) { 1943 FieldCollector->Add(cast<FieldDecl>(Anon)); 1944 if (!cast<CXXRecordDecl>(Record)->isEmpty()) 1945 cast<CXXRecordDecl>(OwningClass)->setEmpty(false); 1946 } 1947 } else { 1948 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 1949 assert(SCSpec != DeclSpec::SCS_typedef && 1950 "Parser allowed 'typedef' as storage class VarDecl."); 1951 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 1952 if (SCSpec == DeclSpec::SCS_mutable) { 1953 // mutable can only appear on non-static class members, so it's always 1954 // an error here 1955 Diag(Record->getLocation(), diag::err_mutable_nonmember); 1956 Invalid = true; 1957 SC = VarDecl::None; 1958 } 1959 SCSpec = DS.getStorageClassSpecAsWritten(); 1960 VarDecl::StorageClass SCAsWritten 1961 = StorageClassSpecToVarDeclStorageClass(SCSpec); 1962 1963 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 1964 /*IdentifierInfo=*/0, 1965 Context.getTypeDeclType(Record), 1966 TInfo, SC, SCAsWritten); 1967 } 1968 Anon->setImplicit(); 1969 1970 // Add the anonymous struct/union object to the current 1971 // context. We'll be referencing this object when we refer to one of 1972 // its members. 1973 Owner->addDecl(Anon); 1974 1975 // Inject the members of the anonymous struct/union into the owning 1976 // context and into the identifier resolver chain for name lookup 1977 // purposes. 1978 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS)) 1979 Invalid = true; 1980 1981 // Mark this as an anonymous struct/union type. Note that we do not 1982 // do this until after we have already checked and injected the 1983 // members of this anonymous struct/union type, because otherwise 1984 // the members could be injected twice: once by DeclContext when it 1985 // builds its lookup table, and once by 1986 // InjectAnonymousStructOrUnionMembers. 1987 Record->setAnonymousStructOrUnion(true); 1988 1989 if (Invalid) 1990 Anon->setInvalidDecl(); 1991 1992 return Anon; 1993} 1994 1995 1996/// GetNameForDeclarator - Determine the full declaration name for the 1997/// given Declarator. 1998DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 1999 return GetNameFromUnqualifiedId(D.getName()); 2000} 2001 2002/// \brief Retrieves the declaration name from a parsed unqualified-id. 2003DeclarationNameInfo 2004Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 2005 DeclarationNameInfo NameInfo; 2006 NameInfo.setLoc(Name.StartLocation); 2007 2008 switch (Name.getKind()) { 2009 2010 case UnqualifiedId::IK_Identifier: 2011 NameInfo.setName(Name.Identifier); 2012 NameInfo.setLoc(Name.StartLocation); 2013 return NameInfo; 2014 2015 case UnqualifiedId::IK_OperatorFunctionId: 2016 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 2017 Name.OperatorFunctionId.Operator)); 2018 NameInfo.setLoc(Name.StartLocation); 2019 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 2020 = Name.OperatorFunctionId.SymbolLocations[0]; 2021 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 2022 = Name.EndLocation.getRawEncoding(); 2023 return NameInfo; 2024 2025 case UnqualifiedId::IK_LiteralOperatorId: 2026 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 2027 Name.Identifier)); 2028 NameInfo.setLoc(Name.StartLocation); 2029 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 2030 return NameInfo; 2031 2032 case UnqualifiedId::IK_ConversionFunctionId: { 2033 TypeSourceInfo *TInfo; 2034 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 2035 if (Ty.isNull()) 2036 return DeclarationNameInfo(); 2037 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 2038 Context.getCanonicalType(Ty))); 2039 NameInfo.setLoc(Name.StartLocation); 2040 NameInfo.setNamedTypeInfo(TInfo); 2041 return NameInfo; 2042 } 2043 2044 case UnqualifiedId::IK_ConstructorName: { 2045 TypeSourceInfo *TInfo; 2046 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 2047 if (Ty.isNull()) 2048 return DeclarationNameInfo(); 2049 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2050 Context.getCanonicalType(Ty))); 2051 NameInfo.setLoc(Name.StartLocation); 2052 NameInfo.setNamedTypeInfo(TInfo); 2053 return NameInfo; 2054 } 2055 2056 case UnqualifiedId::IK_ConstructorTemplateId: { 2057 // In well-formed code, we can only have a constructor 2058 // template-id that refers to the current context, so go there 2059 // to find the actual type being constructed. 2060 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 2061 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 2062 return DeclarationNameInfo(); 2063 2064 // Determine the type of the class being constructed. 2065 QualType CurClassType = Context.getTypeDeclType(CurClass); 2066 2067 // FIXME: Check two things: that the template-id names the same type as 2068 // CurClassType, and that the template-id does not occur when the name 2069 // was qualified. 2070 2071 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2072 Context.getCanonicalType(CurClassType))); 2073 NameInfo.setLoc(Name.StartLocation); 2074 // FIXME: should we retrieve TypeSourceInfo? 2075 NameInfo.setNamedTypeInfo(0); 2076 return NameInfo; 2077 } 2078 2079 case UnqualifiedId::IK_DestructorName: { 2080 TypeSourceInfo *TInfo; 2081 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 2082 if (Ty.isNull()) 2083 return DeclarationNameInfo(); 2084 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 2085 Context.getCanonicalType(Ty))); 2086 NameInfo.setLoc(Name.StartLocation); 2087 NameInfo.setNamedTypeInfo(TInfo); 2088 return NameInfo; 2089 } 2090 2091 case UnqualifiedId::IK_TemplateId: { 2092 TemplateName TName = Name.TemplateId->Template.get(); 2093 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 2094 return Context.getNameForTemplate(TName, TNameLoc); 2095 } 2096 2097 } // switch (Name.getKind()) 2098 2099 assert(false && "Unknown name kind"); 2100 return DeclarationNameInfo(); 2101} 2102 2103/// isNearlyMatchingFunction - Determine whether the C++ functions 2104/// Declaration and Definition are "nearly" matching. This heuristic 2105/// is used to improve diagnostics in the case where an out-of-line 2106/// function definition doesn't match any declaration within 2107/// the class or namespace. 2108static bool isNearlyMatchingFunction(ASTContext &Context, 2109 FunctionDecl *Declaration, 2110 FunctionDecl *Definition) { 2111 if (Declaration->param_size() != Definition->param_size()) 2112 return false; 2113 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 2114 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 2115 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 2116 2117 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(), 2118 DefParamTy.getNonReferenceType())) 2119 return false; 2120 } 2121 2122 return true; 2123} 2124 2125/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 2126/// declarator needs to be rebuilt in the current instantiation. 2127/// Any bits of declarator which appear before the name are valid for 2128/// consideration here. That's specifically the type in the decl spec 2129/// and the base type in any member-pointer chunks. 2130static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 2131 DeclarationName Name) { 2132 // The types we specifically need to rebuild are: 2133 // - typenames, typeofs, and decltypes 2134 // - types which will become injected class names 2135 // Of course, we also need to rebuild any type referencing such a 2136 // type. It's safest to just say "dependent", but we call out a 2137 // few cases here. 2138 2139 DeclSpec &DS = D.getMutableDeclSpec(); 2140 switch (DS.getTypeSpecType()) { 2141 case DeclSpec::TST_typename: 2142 case DeclSpec::TST_typeofType: 2143 case DeclSpec::TST_decltype: { 2144 // Grab the type from the parser. 2145 TypeSourceInfo *TSI = 0; 2146 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 2147 if (T.isNull() || !T->isDependentType()) break; 2148 2149 // Make sure there's a type source info. This isn't really much 2150 // of a waste; most dependent types should have type source info 2151 // attached already. 2152 if (!TSI) 2153 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 2154 2155 // Rebuild the type in the current instantiation. 2156 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 2157 if (!TSI) return true; 2158 2159 // Store the new type back in the decl spec. 2160 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 2161 DS.UpdateTypeRep(LocType); 2162 break; 2163 } 2164 2165 case DeclSpec::TST_typeofExpr: { 2166 Expr *E = DS.getRepAsExpr(); 2167 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 2168 if (Result.isInvalid()) return true; 2169 DS.UpdateExprRep(Result.get()); 2170 break; 2171 } 2172 2173 default: 2174 // Nothing to do for these decl specs. 2175 break; 2176 } 2177 2178 // It doesn't matter what order we do this in. 2179 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 2180 DeclaratorChunk &Chunk = D.getTypeObject(I); 2181 2182 // The only type information in the declarator which can come 2183 // before the declaration name is the base type of a member 2184 // pointer. 2185 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 2186 continue; 2187 2188 // Rebuild the scope specifier in-place. 2189 CXXScopeSpec &SS = Chunk.Mem.Scope(); 2190 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 2191 return true; 2192 } 2193 2194 return false; 2195} 2196 2197Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 2198 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), false); 2199} 2200 2201Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 2202 MultiTemplateParamsArg TemplateParamLists, 2203 bool IsFunctionDefinition) { 2204 // TODO: consider using NameInfo for diagnostic. 2205 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2206 DeclarationName Name = NameInfo.getName(); 2207 2208 // All of these full declarators require an identifier. If it doesn't have 2209 // one, the ParsedFreeStandingDeclSpec action should be used. 2210 if (!Name) { 2211 if (!D.isInvalidType()) // Reject this if we think it is valid. 2212 Diag(D.getDeclSpec().getSourceRange().getBegin(), 2213 diag::err_declarator_need_ident) 2214 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 2215 return 0; 2216 } 2217 2218 // The scope passed in may not be a decl scope. Zip up the scope tree until 2219 // we find one that is. 2220 while ((S->getFlags() & Scope::DeclScope) == 0 || 2221 (S->getFlags() & Scope::TemplateParamScope) != 0) 2222 S = S->getParent(); 2223 2224 DeclContext *DC = CurContext; 2225 if (D.getCXXScopeSpec().isInvalid()) 2226 D.setInvalidType(); 2227 else if (D.getCXXScopeSpec().isSet()) { 2228 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 2229 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 2230 if (!DC) { 2231 // If we could not compute the declaration context, it's because the 2232 // declaration context is dependent but does not refer to a class, 2233 // class template, or class template partial specialization. Complain 2234 // and return early, to avoid the coming semantic disaster. 2235 Diag(D.getIdentifierLoc(), 2236 diag::err_template_qualified_declarator_no_match) 2237 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 2238 << D.getCXXScopeSpec().getRange(); 2239 return 0; 2240 } 2241 2242 bool IsDependentContext = DC->isDependentContext(); 2243 2244 if (!IsDependentContext && 2245 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 2246 return 0; 2247 2248 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 2249 Diag(D.getIdentifierLoc(), 2250 diag::err_member_def_undefined_record) 2251 << Name << DC << D.getCXXScopeSpec().getRange(); 2252 D.setInvalidType(); 2253 } 2254 2255 // Check whether we need to rebuild the type of the given 2256 // declaration in the current instantiation. 2257 if (EnteringContext && IsDependentContext && 2258 TemplateParamLists.size() != 0) { 2259 ContextRAII SavedContext(*this, DC); 2260 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 2261 D.setInvalidType(); 2262 } 2263 } 2264 2265 NamedDecl *New; 2266 2267 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 2268 QualType R = TInfo->getType(); 2269 2270 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 2271 ForRedeclaration); 2272 2273 // See if this is a redefinition of a variable in the same scope. 2274 if (!D.getCXXScopeSpec().isSet()) { 2275 bool IsLinkageLookup = false; 2276 2277 // If the declaration we're planning to build will be a function 2278 // or object with linkage, then look for another declaration with 2279 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 2280 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 2281 /* Do nothing*/; 2282 else if (R->isFunctionType()) { 2283 if (CurContext->isFunctionOrMethod() || 2284 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 2285 IsLinkageLookup = true; 2286 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 2287 IsLinkageLookup = true; 2288 else if (CurContext->getLookupContext()->isTranslationUnit() && 2289 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 2290 IsLinkageLookup = true; 2291 2292 if (IsLinkageLookup) 2293 Previous.clear(LookupRedeclarationWithLinkage); 2294 2295 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 2296 } else { // Something like "int foo::x;" 2297 LookupQualifiedName(Previous, DC); 2298 2299 // Don't consider using declarations as previous declarations for 2300 // out-of-line members. 2301 RemoveUsingDecls(Previous); 2302 2303 // C++ 7.3.1.2p2: 2304 // Members (including explicit specializations of templates) of a named 2305 // namespace can also be defined outside that namespace by explicit 2306 // qualification of the name being defined, provided that the entity being 2307 // defined was already declared in the namespace and the definition appears 2308 // after the point of declaration in a namespace that encloses the 2309 // declarations namespace. 2310 // 2311 // Note that we only check the context at this point. We don't yet 2312 // have enough information to make sure that PrevDecl is actually 2313 // the declaration we want to match. For example, given: 2314 // 2315 // class X { 2316 // void f(); 2317 // void f(float); 2318 // }; 2319 // 2320 // void X::f(int) { } // ill-formed 2321 // 2322 // In this case, PrevDecl will point to the overload set 2323 // containing the two f's declared in X, but neither of them 2324 // matches. 2325 2326 // First check whether we named the global scope. 2327 if (isa<TranslationUnitDecl>(DC)) { 2328 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 2329 << Name << D.getCXXScopeSpec().getRange(); 2330 } else { 2331 DeclContext *Cur = CurContext; 2332 while (isa<LinkageSpecDecl>(Cur)) 2333 Cur = Cur->getParent(); 2334 if (!Cur->Encloses(DC)) { 2335 // The qualifying scope doesn't enclose the original declaration. 2336 // Emit diagnostic based on current scope. 2337 SourceLocation L = D.getIdentifierLoc(); 2338 SourceRange R = D.getCXXScopeSpec().getRange(); 2339 if (isa<FunctionDecl>(Cur)) 2340 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 2341 else 2342 Diag(L, diag::err_invalid_declarator_scope) 2343 << Name << cast<NamedDecl>(DC) << R; 2344 D.setInvalidType(); 2345 } 2346 } 2347 } 2348 2349 if (Previous.isSingleResult() && 2350 Previous.getFoundDecl()->isTemplateParameter()) { 2351 // Maybe we will complain about the shadowed template parameter. 2352 if (!D.isInvalidType()) 2353 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 2354 Previous.getFoundDecl())) 2355 D.setInvalidType(); 2356 2357 // Just pretend that we didn't see the previous declaration. 2358 Previous.clear(); 2359 } 2360 2361 // In C++, the previous declaration we find might be a tag type 2362 // (class or enum). In this case, the new declaration will hide the 2363 // tag type. Note that this does does not apply if we're declaring a 2364 // typedef (C++ [dcl.typedef]p4). 2365 if (Previous.isSingleTagDecl() && 2366 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 2367 Previous.clear(); 2368 2369 bool Redeclaration = false; 2370 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 2371 if (TemplateParamLists.size()) { 2372 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 2373 return 0; 2374 } 2375 2376 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration); 2377 } else if (R->isFunctionType()) { 2378 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous, 2379 move(TemplateParamLists), 2380 IsFunctionDefinition, Redeclaration); 2381 } else { 2382 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous, 2383 move(TemplateParamLists), 2384 Redeclaration); 2385 } 2386 2387 if (New == 0) 2388 return 0; 2389 2390 // If this has an identifier and is not an invalid redeclaration or 2391 // function template specialization, add it to the scope stack. 2392 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl())) 2393 PushOnScopeChains(New, S); 2394 2395 return New; 2396} 2397 2398/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 2399/// types into constant array types in certain situations which would otherwise 2400/// be errors (for GCC compatibility). 2401static QualType TryToFixInvalidVariablyModifiedType(QualType T, 2402 ASTContext &Context, 2403 bool &SizeIsNegative, 2404 llvm::APSInt &Oversized) { 2405 // This method tries to turn a variable array into a constant 2406 // array even when the size isn't an ICE. This is necessary 2407 // for compatibility with code that depends on gcc's buggy 2408 // constant expression folding, like struct {char x[(int)(char*)2];} 2409 SizeIsNegative = false; 2410 Oversized = 0; 2411 2412 if (T->isDependentType()) 2413 return QualType(); 2414 2415 QualifierCollector Qs; 2416 const Type *Ty = Qs.strip(T); 2417 2418 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 2419 QualType Pointee = PTy->getPointeeType(); 2420 QualType FixedType = 2421 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 2422 Oversized); 2423 if (FixedType.isNull()) return FixedType; 2424 FixedType = Context.getPointerType(FixedType); 2425 return Qs.apply(FixedType); 2426 } 2427 2428 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 2429 if (!VLATy) 2430 return QualType(); 2431 // FIXME: We should probably handle this case 2432 if (VLATy->getElementType()->isVariablyModifiedType()) 2433 return QualType(); 2434 2435 Expr::EvalResult EvalResult; 2436 if (!VLATy->getSizeExpr() || 2437 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 2438 !EvalResult.Val.isInt()) 2439 return QualType(); 2440 2441 // Check whether the array size is negative. 2442 llvm::APSInt &Res = EvalResult.Val.getInt(); 2443 if (Res.isSigned() && Res.isNegative()) { 2444 SizeIsNegative = true; 2445 return QualType(); 2446 } 2447 2448 // Check whether the array is too large to be addressed. 2449 unsigned ActiveSizeBits 2450 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 2451 Res); 2452 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 2453 Oversized = Res; 2454 return QualType(); 2455 } 2456 2457 return Context.getConstantArrayType(VLATy->getElementType(), 2458 Res, ArrayType::Normal, 0); 2459} 2460 2461/// \brief Register the given locally-scoped external C declaration so 2462/// that it can be found later for redeclarations 2463void 2464Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 2465 const LookupResult &Previous, 2466 Scope *S) { 2467 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 2468 "Decl is not a locally-scoped decl!"); 2469 // Note that we have a locally-scoped external with this name. 2470 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 2471 2472 if (!Previous.isSingleResult()) 2473 return; 2474 2475 NamedDecl *PrevDecl = Previous.getFoundDecl(); 2476 2477 // If there was a previous declaration of this variable, it may be 2478 // in our identifier chain. Update the identifier chain with the new 2479 // declaration. 2480 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 2481 // The previous declaration was found on the identifer resolver 2482 // chain, so remove it from its scope. 2483 while (S && !S->isDeclScope(PrevDecl)) 2484 S = S->getParent(); 2485 2486 if (S) 2487 S->RemoveDecl(PrevDecl); 2488 } 2489} 2490 2491/// \brief Diagnose function specifiers on a declaration of an identifier that 2492/// does not identify a function. 2493void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 2494 // FIXME: We should probably indicate the identifier in question to avoid 2495 // confusion for constructs like "inline int a(), b;" 2496 if (D.getDeclSpec().isInlineSpecified()) 2497 Diag(D.getDeclSpec().getInlineSpecLoc(), 2498 diag::err_inline_non_function); 2499 2500 if (D.getDeclSpec().isVirtualSpecified()) 2501 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2502 diag::err_virtual_non_function); 2503 2504 if (D.getDeclSpec().isExplicitSpecified()) 2505 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2506 diag::err_explicit_non_function); 2507} 2508 2509NamedDecl* 2510Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2511 QualType R, TypeSourceInfo *TInfo, 2512 LookupResult &Previous, bool &Redeclaration) { 2513 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 2514 if (D.getCXXScopeSpec().isSet()) { 2515 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 2516 << D.getCXXScopeSpec().getRange(); 2517 D.setInvalidType(); 2518 // Pretend we didn't see the scope specifier. 2519 DC = CurContext; 2520 Previous.clear(); 2521 } 2522 2523 if (getLangOptions().CPlusPlus) { 2524 // Check that there are no default arguments (C++ only). 2525 CheckExtraCXXDefaultArguments(D); 2526 } 2527 2528 DiagnoseFunctionSpecifiers(D); 2529 2530 if (D.getDeclSpec().isThreadSpecified()) 2531 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2532 2533 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 2534 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 2535 << D.getName().getSourceRange(); 2536 return 0; 2537 } 2538 2539 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo); 2540 if (!NewTD) return 0; 2541 2542 // Handle attributes prior to checking for duplicates in MergeVarDecl 2543 ProcessDeclAttributes(S, NewTD, D); 2544 2545 // C99 6.7.7p2: If a typedef name specifies a variably modified type 2546 // then it shall have block scope. 2547 // Note that variably modified types must be fixed before merging the decl so 2548 // that redeclarations will match. 2549 QualType T = NewTD->getUnderlyingType(); 2550 if (T->isVariablyModifiedType()) { 2551 getCurFunction()->setHasBranchProtectedScope(); 2552 2553 if (S->getFnParent() == 0) { 2554 bool SizeIsNegative; 2555 llvm::APSInt Oversized; 2556 QualType FixedTy = 2557 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 2558 Oversized); 2559 if (!FixedTy.isNull()) { 2560 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size); 2561 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 2562 } else { 2563 if (SizeIsNegative) 2564 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size); 2565 else if (T->isVariableArrayType()) 2566 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 2567 else if (Oversized.getBoolValue()) 2568 Diag(D.getIdentifierLoc(), diag::err_array_too_large) 2569 << Oversized.toString(10); 2570 else 2571 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 2572 NewTD->setInvalidDecl(); 2573 } 2574 } 2575 } 2576 2577 // Merge the decl with the existing one if appropriate. If the decl is 2578 // in an outer scope, it isn't the same thing. 2579 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false); 2580 if (!Previous.empty()) { 2581 Redeclaration = true; 2582 MergeTypeDefDecl(NewTD, Previous); 2583 } 2584 2585 // If this is the C FILE type, notify the AST context. 2586 if (IdentifierInfo *II = NewTD->getIdentifier()) 2587 if (!NewTD->isInvalidDecl() && 2588 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) { 2589 if (II->isStr("FILE")) 2590 Context.setFILEDecl(NewTD); 2591 else if (II->isStr("jmp_buf")) 2592 Context.setjmp_bufDecl(NewTD); 2593 else if (II->isStr("sigjmp_buf")) 2594 Context.setsigjmp_bufDecl(NewTD); 2595 } 2596 2597 return NewTD; 2598} 2599 2600/// \brief Determines whether the given declaration is an out-of-scope 2601/// previous declaration. 2602/// 2603/// This routine should be invoked when name lookup has found a 2604/// previous declaration (PrevDecl) that is not in the scope where a 2605/// new declaration by the same name is being introduced. If the new 2606/// declaration occurs in a local scope, previous declarations with 2607/// linkage may still be considered previous declarations (C99 2608/// 6.2.2p4-5, C++ [basic.link]p6). 2609/// 2610/// \param PrevDecl the previous declaration found by name 2611/// lookup 2612/// 2613/// \param DC the context in which the new declaration is being 2614/// declared. 2615/// 2616/// \returns true if PrevDecl is an out-of-scope previous declaration 2617/// for a new delcaration with the same name. 2618static bool 2619isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 2620 ASTContext &Context) { 2621 if (!PrevDecl) 2622 return 0; 2623 2624 if (!PrevDecl->hasLinkage()) 2625 return false; 2626 2627 if (Context.getLangOptions().CPlusPlus) { 2628 // C++ [basic.link]p6: 2629 // If there is a visible declaration of an entity with linkage 2630 // having the same name and type, ignoring entities declared 2631 // outside the innermost enclosing namespace scope, the block 2632 // scope declaration declares that same entity and receives the 2633 // linkage of the previous declaration. 2634 DeclContext *OuterContext = DC->getLookupContext(); 2635 if (!OuterContext->isFunctionOrMethod()) 2636 // This rule only applies to block-scope declarations. 2637 return false; 2638 else { 2639 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 2640 if (PrevOuterContext->isRecord()) 2641 // We found a member function: ignore it. 2642 return false; 2643 else { 2644 // Find the innermost enclosing namespace for the new and 2645 // previous declarations. 2646 while (!OuterContext->isFileContext()) 2647 OuterContext = OuterContext->getParent(); 2648 while (!PrevOuterContext->isFileContext()) 2649 PrevOuterContext = PrevOuterContext->getParent(); 2650 2651 // The previous declaration is in a different namespace, so it 2652 // isn't the same function. 2653 if (OuterContext->getPrimaryContext() != 2654 PrevOuterContext->getPrimaryContext()) 2655 return false; 2656 } 2657 } 2658 } 2659 2660 return true; 2661} 2662 2663static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 2664 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2665 if (!SS.isSet()) return; 2666 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 2667 SS.getRange()); 2668} 2669 2670NamedDecl* 2671Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2672 QualType R, TypeSourceInfo *TInfo, 2673 LookupResult &Previous, 2674 MultiTemplateParamsArg TemplateParamLists, 2675 bool &Redeclaration) { 2676 DeclarationName Name = GetNameForDeclarator(D).getName(); 2677 2678 // Check that there are no default arguments (C++ only). 2679 if (getLangOptions().CPlusPlus) 2680 CheckExtraCXXDefaultArguments(D); 2681 2682 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 2683 assert(SCSpec != DeclSpec::SCS_typedef && 2684 "Parser allowed 'typedef' as storage class VarDecl."); 2685 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2686 if (SCSpec == DeclSpec::SCS_mutable) { 2687 // mutable can only appear on non-static class members, so it's always 2688 // an error here 2689 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 2690 D.setInvalidType(); 2691 SC = VarDecl::None; 2692 } 2693 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 2694 VarDecl::StorageClass SCAsWritten 2695 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2696 2697 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2698 if (!II) { 2699 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 2700 << Name.getAsString(); 2701 return 0; 2702 } 2703 2704 DiagnoseFunctionSpecifiers(D); 2705 2706 if (!DC->isRecord() && S->getFnParent() == 0) { 2707 // C99 6.9p2: The storage-class specifiers auto and register shall not 2708 // appear in the declaration specifiers in an external declaration. 2709 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 2710 2711 // If this is a register variable with an asm label specified, then this 2712 // is a GNU extension. 2713 if (SC == VarDecl::Register && D.getAsmLabel()) 2714 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 2715 else 2716 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 2717 D.setInvalidType(); 2718 } 2719 } 2720 if (DC->isRecord() && !CurContext->isRecord()) { 2721 // This is an out-of-line definition of a static data member. 2722 if (SC == VarDecl::Static) { 2723 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2724 diag::err_static_out_of_line) 2725 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 2726 } else if (SC == VarDecl::None) 2727 SC = VarDecl::Static; 2728 } 2729 if (SC == VarDecl::Static) { 2730 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2731 if (RD->isLocalClass()) 2732 Diag(D.getIdentifierLoc(), 2733 diag::err_static_data_member_not_allowed_in_local_class) 2734 << Name << RD->getDeclName(); 2735 } 2736 } 2737 2738 // Match up the template parameter lists with the scope specifier, then 2739 // determine whether we have a template or a template specialization. 2740 bool isExplicitSpecialization = false; 2741 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size(); 2742 bool Invalid = false; 2743 if (TemplateParameterList *TemplateParams 2744 = MatchTemplateParametersToScopeSpecifier( 2745 D.getDeclSpec().getSourceRange().getBegin(), 2746 D.getCXXScopeSpec(), 2747 (TemplateParameterList**)TemplateParamLists.get(), 2748 TemplateParamLists.size(), 2749 /*never a friend*/ false, 2750 isExplicitSpecialization, 2751 Invalid)) { 2752 // All but one template parameter lists have been matching. 2753 --NumMatchedTemplateParamLists; 2754 2755 if (TemplateParams->size() > 0) { 2756 // There is no such thing as a variable template. 2757 Diag(D.getIdentifierLoc(), diag::err_template_variable) 2758 << II 2759 << SourceRange(TemplateParams->getTemplateLoc(), 2760 TemplateParams->getRAngleLoc()); 2761 return 0; 2762 } else { 2763 // There is an extraneous 'template<>' for this variable. Complain 2764 // about it, but allow the declaration of the variable. 2765 Diag(TemplateParams->getTemplateLoc(), 2766 diag::err_template_variable_noparams) 2767 << II 2768 << SourceRange(TemplateParams->getTemplateLoc(), 2769 TemplateParams->getRAngleLoc()); 2770 2771 isExplicitSpecialization = true; 2772 } 2773 } 2774 2775 VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 2776 II, R, TInfo, SC, SCAsWritten); 2777 2778 if (D.isInvalidType() || Invalid) 2779 NewVD->setInvalidDecl(); 2780 2781 SetNestedNameSpecifier(NewVD, D); 2782 2783 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) { 2784 NewVD->setTemplateParameterListsInfo(Context, 2785 NumMatchedTemplateParamLists, 2786 (TemplateParameterList**)TemplateParamLists.release()); 2787 } 2788 2789 if (D.getDeclSpec().isThreadSpecified()) { 2790 if (NewVD->hasLocalStorage()) 2791 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 2792 else if (!Context.Target.isTLSSupported()) 2793 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 2794 else 2795 NewVD->setThreadSpecified(true); 2796 } 2797 2798 // Set the lexical context. If the declarator has a C++ scope specifier, the 2799 // lexical context will be different from the semantic context. 2800 NewVD->setLexicalDeclContext(CurContext); 2801 2802 // Handle attributes prior to checking for duplicates in MergeVarDecl 2803 ProcessDeclAttributes(S, NewVD, D); 2804 2805 // Handle GNU asm-label extension (encoded as an attribute). 2806 if (Expr *E = (Expr*) D.getAsmLabel()) { 2807 // The parser guarantees this is a string. 2808 StringLiteral *SE = cast<StringLiteral>(E); 2809 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 2810 Context, SE->getString())); 2811 } 2812 2813 // Diagnose shadowed variables before filtering for scope. 2814 if (!D.getCXXScopeSpec().isSet()) 2815 CheckShadow(S, NewVD, Previous); 2816 2817 // Don't consider existing declarations that are in a different 2818 // scope and are out-of-semantic-context declarations (if the new 2819 // declaration has linkage). 2820 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage()); 2821 2822 // Merge the decl with the existing one if appropriate. 2823 if (!Previous.empty()) { 2824 if (Previous.isSingleResult() && 2825 isa<FieldDecl>(Previous.getFoundDecl()) && 2826 D.getCXXScopeSpec().isSet()) { 2827 // The user tried to define a non-static data member 2828 // out-of-line (C++ [dcl.meaning]p1). 2829 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 2830 << D.getCXXScopeSpec().getRange(); 2831 Previous.clear(); 2832 NewVD->setInvalidDecl(); 2833 } 2834 } else if (D.getCXXScopeSpec().isSet()) { 2835 // No previous declaration in the qualifying scope. 2836 Diag(D.getIdentifierLoc(), diag::err_no_member) 2837 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 2838 << D.getCXXScopeSpec().getRange(); 2839 NewVD->setInvalidDecl(); 2840 } 2841 2842 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 2843 2844 // This is an explicit specialization of a static data member. Check it. 2845 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 2846 CheckMemberSpecialization(NewVD, Previous)) 2847 NewVD->setInvalidDecl(); 2848 2849 // attributes declared post-definition are currently ignored 2850 // FIXME: This should be handled in attribute merging, not 2851 // here. 2852 if (Previous.isSingleResult()) { 2853 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2854 if (Def && (Def = Def->getDefinition()) && 2855 Def != NewVD && D.hasAttributes()) { 2856 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 2857 Diag(Def->getLocation(), diag::note_previous_definition); 2858 } 2859 } 2860 2861 // If this is a locally-scoped extern C variable, update the map of 2862 // such variables. 2863 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 2864 !NewVD->isInvalidDecl()) 2865 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 2866 2867 // If there's a #pragma GCC visibility in scope, and this isn't a class 2868 // member, set the visibility of this variable. 2869 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 2870 AddPushedVisibilityAttribute(NewVD); 2871 2872 MarkUnusedFileScopedDecl(NewVD); 2873 2874 return NewVD; 2875} 2876 2877/// \brief Diagnose variable or built-in function shadowing. Implements 2878/// -Wshadow. 2879/// 2880/// This method is called whenever a VarDecl is added to a "useful" 2881/// scope. 2882/// 2883/// \param S the scope in which the shadowing name is being declared 2884/// \param R the lookup of the name 2885/// 2886void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 2887 // Return if warning is ignored. 2888 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored) 2889 return; 2890 2891 // Don't diagnose declarations at file scope. The scope might not 2892 // have a DeclContext if (e.g.) we're parsing a function prototype. 2893 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity()); 2894 if (NewDC && NewDC->isFileContext()) 2895 return; 2896 2897 // Only diagnose if we're shadowing an unambiguous field or variable. 2898 if (R.getResultKind() != LookupResult::Found) 2899 return; 2900 2901 NamedDecl* ShadowedDecl = R.getFoundDecl(); 2902 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 2903 return; 2904 2905 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 2906 2907 // Only warn about certain kinds of shadowing for class members. 2908 if (NewDC && NewDC->isRecord()) { 2909 // In particular, don't warn about shadowing non-class members. 2910 if (!OldDC->isRecord()) 2911 return; 2912 2913 // TODO: should we warn about static data members shadowing 2914 // static data members from base classes? 2915 2916 // TODO: don't diagnose for inaccessible shadowed members. 2917 // This is hard to do perfectly because we might friend the 2918 // shadowing context, but that's just a false negative. 2919 } 2920 2921 // Determine what kind of declaration we're shadowing. 2922 unsigned Kind; 2923 if (isa<RecordDecl>(OldDC)) { 2924 if (isa<FieldDecl>(ShadowedDecl)) 2925 Kind = 3; // field 2926 else 2927 Kind = 2; // static data member 2928 } else if (OldDC->isFileContext()) 2929 Kind = 1; // global 2930 else 2931 Kind = 0; // local 2932 2933 DeclarationName Name = R.getLookupName(); 2934 2935 // Emit warning and note. 2936 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 2937 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 2938} 2939 2940/// \brief Check -Wshadow without the advantage of a previous lookup. 2941void Sema::CheckShadow(Scope *S, VarDecl *D) { 2942 LookupResult R(*this, D->getDeclName(), D->getLocation(), 2943 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 2944 LookupName(R, S); 2945 CheckShadow(S, D, R); 2946} 2947 2948/// \brief Perform semantic checking on a newly-created variable 2949/// declaration. 2950/// 2951/// This routine performs all of the type-checking required for a 2952/// variable declaration once it has been built. It is used both to 2953/// check variables after they have been parsed and their declarators 2954/// have been translated into a declaration, and to check variables 2955/// that have been instantiated from a template. 2956/// 2957/// Sets NewVD->isInvalidDecl() if an error was encountered. 2958void Sema::CheckVariableDeclaration(VarDecl *NewVD, 2959 LookupResult &Previous, 2960 bool &Redeclaration) { 2961 // If the decl is already known invalid, don't check it. 2962 if (NewVD->isInvalidDecl()) 2963 return; 2964 2965 QualType T = NewVD->getType(); 2966 2967 if (T->isObjCObjectType()) { 2968 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 2969 return NewVD->setInvalidDecl(); 2970 } 2971 2972 // Emit an error if an address space was applied to decl with local storage. 2973 // This includes arrays of objects with address space qualifiers, but not 2974 // automatic variables that point to other address spaces. 2975 // ISO/IEC TR 18037 S5.1.2 2976 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) { 2977 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 2978 return NewVD->setInvalidDecl(); 2979 } 2980 2981 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 2982 && !NewVD->hasAttr<BlocksAttr>()) 2983 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 2984 2985 bool isVM = T->isVariablyModifiedType(); 2986 if (isVM || NewVD->hasAttr<CleanupAttr>() || 2987 NewVD->hasAttr<BlocksAttr>()) 2988 getCurFunction()->setHasBranchProtectedScope(); 2989 2990 if ((isVM && NewVD->hasLinkage()) || 2991 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 2992 bool SizeIsNegative; 2993 llvm::APSInt Oversized; 2994 QualType FixedTy = 2995 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 2996 Oversized); 2997 2998 if (FixedTy.isNull() && T->isVariableArrayType()) { 2999 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 3000 // FIXME: This won't give the correct result for 3001 // int a[10][n]; 3002 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 3003 3004 if (NewVD->isFileVarDecl()) 3005 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 3006 << SizeRange; 3007 else if (NewVD->getStorageClass() == VarDecl::Static) 3008 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 3009 << SizeRange; 3010 else 3011 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 3012 << SizeRange; 3013 return NewVD->setInvalidDecl(); 3014 } 3015 3016 if (FixedTy.isNull()) { 3017 if (NewVD->isFileVarDecl()) 3018 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 3019 else 3020 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 3021 return NewVD->setInvalidDecl(); 3022 } 3023 3024 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 3025 NewVD->setType(FixedTy); 3026 } 3027 3028 if (Previous.empty() && NewVD->isExternC()) { 3029 // Since we did not find anything by this name and we're declaring 3030 // an extern "C" variable, look for a non-visible extern "C" 3031 // declaration with the same name. 3032 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3033 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 3034 if (Pos != LocallyScopedExternalDecls.end()) 3035 Previous.addDecl(Pos->second); 3036 } 3037 3038 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 3039 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 3040 << T; 3041 return NewVD->setInvalidDecl(); 3042 } 3043 3044 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 3045 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 3046 return NewVD->setInvalidDecl(); 3047 } 3048 3049 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 3050 Diag(NewVD->getLocation(), diag::err_block_on_vm); 3051 return NewVD->setInvalidDecl(); 3052 } 3053 3054 // Function pointers and references cannot have qualified function type, only 3055 // function pointer-to-members can do that. 3056 QualType Pointee; 3057 unsigned PtrOrRef = 0; 3058 if (const PointerType *Ptr = T->getAs<PointerType>()) 3059 Pointee = Ptr->getPointeeType(); 3060 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 3061 Pointee = Ref->getPointeeType(); 3062 PtrOrRef = 1; 3063 } 3064 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 3065 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 3066 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 3067 << PtrOrRef; 3068 return NewVD->setInvalidDecl(); 3069 } 3070 3071 if (!Previous.empty()) { 3072 Redeclaration = true; 3073 MergeVarDecl(NewVD, Previous); 3074 } 3075} 3076 3077/// \brief Data used with FindOverriddenMethod 3078struct FindOverriddenMethodData { 3079 Sema *S; 3080 CXXMethodDecl *Method; 3081}; 3082 3083/// \brief Member lookup function that determines whether a given C++ 3084/// method overrides a method in a base class, to be used with 3085/// CXXRecordDecl::lookupInBases(). 3086static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 3087 CXXBasePath &Path, 3088 void *UserData) { 3089 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 3090 3091 FindOverriddenMethodData *Data 3092 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 3093 3094 DeclarationName Name = Data->Method->getDeclName(); 3095 3096 // FIXME: Do we care about other names here too? 3097 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 3098 // We really want to find the base class destructor here. 3099 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 3100 CanQualType CT = Data->S->Context.getCanonicalType(T); 3101 3102 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 3103 } 3104 3105 for (Path.Decls = BaseRecord->lookup(Name); 3106 Path.Decls.first != Path.Decls.second; 3107 ++Path.Decls.first) { 3108 NamedDecl *D = *Path.Decls.first; 3109 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 3110 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 3111 return true; 3112 } 3113 } 3114 3115 return false; 3116} 3117 3118/// AddOverriddenMethods - See if a method overrides any in the base classes, 3119/// and if so, check that it's a valid override and remember it. 3120void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 3121 // Look for virtual methods in base classes that this method might override. 3122 CXXBasePaths Paths; 3123 FindOverriddenMethodData Data; 3124 Data.Method = MD; 3125 Data.S = this; 3126 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 3127 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 3128 E = Paths.found_decls_end(); I != E; ++I) { 3129 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 3130 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 3131 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 3132 !CheckOverridingFunctionAttributes(MD, OldMD)) 3133 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 3134 } 3135 } 3136 } 3137} 3138 3139NamedDecl* 3140Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3141 QualType R, TypeSourceInfo *TInfo, 3142 LookupResult &Previous, 3143 MultiTemplateParamsArg TemplateParamLists, 3144 bool IsFunctionDefinition, bool &Redeclaration) { 3145 assert(R.getTypePtr()->isFunctionType()); 3146 3147 // TODO: consider using NameInfo for diagnostic. 3148 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3149 DeclarationName Name = NameInfo.getName(); 3150 FunctionDecl::StorageClass SC = FunctionDecl::None; 3151 switch (D.getDeclSpec().getStorageClassSpec()) { 3152 default: assert(0 && "Unknown storage class!"); 3153 case DeclSpec::SCS_auto: 3154 case DeclSpec::SCS_register: 3155 case DeclSpec::SCS_mutable: 3156 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3157 diag::err_typecheck_sclass_func); 3158 D.setInvalidType(); 3159 break; 3160 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 3161 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 3162 case DeclSpec::SCS_static: { 3163 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 3164 // C99 6.7.1p5: 3165 // The declaration of an identifier for a function that has 3166 // block scope shall have no explicit storage-class specifier 3167 // other than extern 3168 // See also (C++ [dcl.stc]p4). 3169 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3170 diag::err_static_block_func); 3171 SC = FunctionDecl::None; 3172 } else 3173 SC = FunctionDecl::Static; 3174 break; 3175 } 3176 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 3177 } 3178 3179 if (D.getDeclSpec().isThreadSpecified()) 3180 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3181 3182 bool isFriend = D.getDeclSpec().isFriendSpecified(); 3183 bool isInline = D.getDeclSpec().isInlineSpecified(); 3184 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 3185 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 3186 3187 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3188 FunctionDecl::StorageClass SCAsWritten 3189 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 3190 3191 // Check that the return type is not an abstract class type. 3192 // For record types, this is done by the AbstractClassUsageDiagnoser once 3193 // the class has been completely parsed. 3194 if (!DC->isRecord() && 3195 RequireNonAbstractType(D.getIdentifierLoc(), 3196 R->getAs<FunctionType>()->getResultType(), 3197 diag::err_abstract_type_in_decl, 3198 AbstractReturnType)) 3199 D.setInvalidType(); 3200 3201 // Do not allow returning a objc interface by-value. 3202 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 3203 Diag(D.getIdentifierLoc(), 3204 diag::err_object_cannot_be_passed_returned_by_value) << 0 3205 << R->getAs<FunctionType>()->getResultType(); 3206 D.setInvalidType(); 3207 } 3208 3209 bool isVirtualOkay = false; 3210 FunctionDecl *NewFD; 3211 3212 if (isFriend) { 3213 // C++ [class.friend]p5 3214 // A function can be defined in a friend declaration of a 3215 // class . . . . Such a function is implicitly inline. 3216 isInline |= IsFunctionDefinition; 3217 } 3218 3219 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 3220 // This is a C++ constructor declaration. 3221 assert(DC->isRecord() && 3222 "Constructors can only be declared in a member context"); 3223 3224 R = CheckConstructorDeclarator(D, R, SC); 3225 3226 // Create the new declaration 3227 NewFD = CXXConstructorDecl::Create(Context, 3228 cast<CXXRecordDecl>(DC), 3229 NameInfo, R, TInfo, 3230 isExplicit, isInline, 3231 /*isImplicitlyDeclared=*/false); 3232 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 3233 // This is a C++ destructor declaration. 3234 if (DC->isRecord()) { 3235 R = CheckDestructorDeclarator(D, R, SC); 3236 3237 NewFD = CXXDestructorDecl::Create(Context, 3238 cast<CXXRecordDecl>(DC), 3239 NameInfo, R, 3240 isInline, 3241 /*isImplicitlyDeclared=*/false); 3242 NewFD->setTypeSourceInfo(TInfo); 3243 3244 isVirtualOkay = true; 3245 } else { 3246 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 3247 3248 // Create a FunctionDecl to satisfy the function definition parsing 3249 // code path. 3250 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 3251 Name, R, TInfo, SC, SCAsWritten, isInline, 3252 /*hasPrototype=*/true); 3253 D.setInvalidType(); 3254 } 3255 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 3256 if (!DC->isRecord()) { 3257 Diag(D.getIdentifierLoc(), 3258 diag::err_conv_function_not_member); 3259 return 0; 3260 } 3261 3262 CheckConversionDeclarator(D, R, SC); 3263 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 3264 NameInfo, R, TInfo, 3265 isInline, isExplicit); 3266 3267 isVirtualOkay = true; 3268 } else if (DC->isRecord()) { 3269 // If the of the function is the same as the name of the record, then this 3270 // must be an invalid constructor that has a return type. 3271 // (The parser checks for a return type and makes the declarator a 3272 // constructor if it has no return type). 3273 // must have an invalid constructor that has a return type 3274 if (Name.getAsIdentifierInfo() && 3275 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 3276 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 3277 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3278 << SourceRange(D.getIdentifierLoc()); 3279 return 0; 3280 } 3281 3282 bool isStatic = SC == FunctionDecl::Static; 3283 3284 // [class.free]p1: 3285 // Any allocation function for a class T is a static member 3286 // (even if not explicitly declared static). 3287 if (Name.getCXXOverloadedOperator() == OO_New || 3288 Name.getCXXOverloadedOperator() == OO_Array_New) 3289 isStatic = true; 3290 3291 // [class.free]p6 Any deallocation function for a class X is a static member 3292 // (even if not explicitly declared static). 3293 if (Name.getCXXOverloadedOperator() == OO_Delete || 3294 Name.getCXXOverloadedOperator() == OO_Array_Delete) 3295 isStatic = true; 3296 3297 // This is a C++ method declaration. 3298 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 3299 NameInfo, R, TInfo, 3300 isStatic, SCAsWritten, isInline); 3301 3302 isVirtualOkay = !isStatic; 3303 } else { 3304 // Determine whether the function was written with a 3305 // prototype. This true when: 3306 // - we're in C++ (where every function has a prototype), 3307 // - there is a prototype in the declarator, or 3308 // - the type R of the function is some kind of typedef or other reference 3309 // to a type name (which eventually refers to a function type). 3310 bool HasPrototype = 3311 getLangOptions().CPlusPlus || 3312 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) || 3313 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 3314 3315 NewFD = FunctionDecl::Create(Context, DC, 3316 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 3317 HasPrototype); 3318 } 3319 3320 if (D.isInvalidType()) 3321 NewFD->setInvalidDecl(); 3322 3323 SetNestedNameSpecifier(NewFD, D); 3324 3325 // Set the lexical context. If the declarator has a C++ 3326 // scope specifier, or is the object of a friend declaration, the 3327 // lexical context will be different from the semantic context. 3328 NewFD->setLexicalDeclContext(CurContext); 3329 3330 // Match up the template parameter lists with the scope specifier, then 3331 // determine whether we have a template or a template specialization. 3332 FunctionTemplateDecl *FunctionTemplate = 0; 3333 bool isExplicitSpecialization = false; 3334 bool isFunctionTemplateSpecialization = false; 3335 unsigned NumMatchedTemplateParamLists = TemplateParamLists.size(); 3336 bool Invalid = false; 3337 if (TemplateParameterList *TemplateParams 3338 = MatchTemplateParametersToScopeSpecifier( 3339 D.getDeclSpec().getSourceRange().getBegin(), 3340 D.getCXXScopeSpec(), 3341 (TemplateParameterList**)TemplateParamLists.get(), 3342 TemplateParamLists.size(), 3343 isFriend, 3344 isExplicitSpecialization, 3345 Invalid)) { 3346 // All but one template parameter lists have been matching. 3347 --NumMatchedTemplateParamLists; 3348 3349 if (TemplateParams->size() > 0) { 3350 // This is a function template 3351 3352 // Check that we can declare a template here. 3353 if (CheckTemplateDeclScope(S, TemplateParams)) 3354 return 0; 3355 3356 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 3357 NewFD->getLocation(), 3358 Name, TemplateParams, 3359 NewFD); 3360 FunctionTemplate->setLexicalDeclContext(CurContext); 3361 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 3362 } else { 3363 // This is a function template specialization. 3364 isFunctionTemplateSpecialization = true; 3365 3366 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 3367 if (isFriend && isFunctionTemplateSpecialization) { 3368 // We want to remove the "template<>", found here. 3369 SourceRange RemoveRange = TemplateParams->getSourceRange(); 3370 3371 // If we remove the template<> and the name is not a 3372 // template-id, we're actually silently creating a problem: 3373 // the friend declaration will refer to an untemplated decl, 3374 // and clearly the user wants a template specialization. So 3375 // we need to insert '<>' after the name. 3376 SourceLocation InsertLoc; 3377 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 3378 InsertLoc = D.getName().getSourceRange().getEnd(); 3379 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 3380 } 3381 3382 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 3383 << Name << RemoveRange 3384 << FixItHint::CreateRemoval(RemoveRange) 3385 << FixItHint::CreateInsertion(InsertLoc, "<>"); 3386 } 3387 } 3388 } 3389 3390 if (NumMatchedTemplateParamLists > 0 && D.getCXXScopeSpec().isSet()) { 3391 NewFD->setTemplateParameterListsInfo(Context, 3392 NumMatchedTemplateParamLists, 3393 (TemplateParameterList**)TemplateParamLists.release()); 3394 } 3395 3396 if (Invalid) { 3397 NewFD->setInvalidDecl(); 3398 if (FunctionTemplate) 3399 FunctionTemplate->setInvalidDecl(); 3400 } 3401 3402 // C++ [dcl.fct.spec]p5: 3403 // The virtual specifier shall only be used in declarations of 3404 // nonstatic class member functions that appear within a 3405 // member-specification of a class declaration; see 10.3. 3406 // 3407 if (isVirtual && !NewFD->isInvalidDecl()) { 3408 if (!isVirtualOkay) { 3409 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3410 diag::err_virtual_non_function); 3411 } else if (!CurContext->isRecord()) { 3412 // 'virtual' was specified outside of the class. 3413 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) 3414 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 3415 } else { 3416 // Okay: Add virtual to the method. 3417 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC); 3418 CurClass->setMethodAsVirtual(NewFD); 3419 } 3420 } 3421 3422 // C++ [dcl.fct.spec]p3: 3423 // The inline specifier shall not appear on a block scope function declaration. 3424 if (isInline && !NewFD->isInvalidDecl() && getLangOptions().CPlusPlus) { 3425 if (CurContext->isFunctionOrMethod()) { 3426 // 'inline' is not allowed on block scope function declaration. 3427 Diag(D.getDeclSpec().getInlineSpecLoc(), 3428 diag::err_inline_declaration_block_scope) << Name 3429 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 3430 } 3431 } 3432 3433 // C++ [dcl.fct.spec]p6: 3434 // The explicit specifier shall be used only in the declaration of a 3435 // constructor or conversion function within its class definition; see 12.3.1 3436 // and 12.3.2. 3437 if (isExplicit && !NewFD->isInvalidDecl()) { 3438 if (!CurContext->isRecord()) { 3439 // 'explicit' was specified outside of the class. 3440 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3441 diag::err_explicit_out_of_class) 3442 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 3443 } else if (!isa<CXXConstructorDecl>(NewFD) && 3444 !isa<CXXConversionDecl>(NewFD)) { 3445 // 'explicit' was specified on a function that wasn't a constructor 3446 // or conversion function. 3447 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3448 diag::err_explicit_non_ctor_or_conv_function) 3449 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 3450 } 3451 } 3452 3453 // Filter out previous declarations that don't match the scope. 3454 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage()); 3455 3456 if (isFriend) { 3457 // DC is the namespace in which the function is being declared. 3458 assert((DC->isFileContext() || !Previous.empty()) && 3459 "previously-undeclared friend function being created " 3460 "in a non-namespace context"); 3461 3462 // For now, claim that the objects have no previous declaration. 3463 if (FunctionTemplate) { 3464 FunctionTemplate->setObjectOfFriendDecl(false); 3465 FunctionTemplate->setAccess(AS_public); 3466 } 3467 NewFD->setObjectOfFriendDecl(false); 3468 NewFD->setAccess(AS_public); 3469 } 3470 3471 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) && 3472 !CurContext->isRecord()) { 3473 // C++ [class.static]p1: 3474 // A data or function member of a class may be declared static 3475 // in a class definition, in which case it is a static member of 3476 // the class. 3477 3478 // Complain about the 'static' specifier if it's on an out-of-line 3479 // member function definition. 3480 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3481 diag::err_static_out_of_line) 3482 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3483 } 3484 3485 // Handle GNU asm-label extension (encoded as an attribute). 3486 if (Expr *E = (Expr*) D.getAsmLabel()) { 3487 // The parser guarantees this is a string. 3488 StringLiteral *SE = cast<StringLiteral>(E); 3489 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 3490 SE->getString())); 3491 } 3492 3493 // Copy the parameter declarations from the declarator D to the function 3494 // declaration NewFD, if they are available. First scavenge them into Params. 3495 llvm::SmallVector<ParmVarDecl*, 16> Params; 3496 if (D.getNumTypeObjects() > 0) { 3497 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3498 3499 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 3500 // function that takes no arguments, not a function that takes a 3501 // single void argument. 3502 // We let through "const void" here because Sema::GetTypeForDeclarator 3503 // already checks for that case. 3504 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3505 FTI.ArgInfo[0].Param && 3506 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 3507 // Empty arg list, don't push any params. 3508 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 3509 3510 // In C++, the empty parameter-type-list must be spelled "void"; a 3511 // typedef of void is not permitted. 3512 if (getLangOptions().CPlusPlus && 3513 Param->getType().getUnqualifiedType() != Context.VoidTy) 3514 Diag(Param->getLocation(), diag::err_param_typedef_of_void); 3515 // FIXME: Leaks decl? 3516 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 3517 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 3518 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 3519 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 3520 Param->setDeclContext(NewFD); 3521 Params.push_back(Param); 3522 3523 if (Param->isInvalidDecl()) 3524 NewFD->setInvalidDecl(); 3525 } 3526 } 3527 3528 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 3529 // When we're declaring a function with a typedef, typeof, etc as in the 3530 // following example, we'll need to synthesize (unnamed) 3531 // parameters for use in the declaration. 3532 // 3533 // @code 3534 // typedef void fn(int); 3535 // fn f; 3536 // @endcode 3537 3538 // Synthesize a parameter for each argument type. 3539 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 3540 AE = FT->arg_type_end(); AI != AE; ++AI) { 3541 ParmVarDecl *Param = 3542 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 3543 Params.push_back(Param); 3544 } 3545 } else { 3546 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 3547 "Should not need args for typedef of non-prototype fn"); 3548 } 3549 // Finally, we know we have the right number of parameters, install them. 3550 NewFD->setParams(Params.data(), Params.size()); 3551 3552 // If the declarator is a template-id, translate the parser's template 3553 // argument list into our AST format. 3554 bool HasExplicitTemplateArgs = false; 3555 TemplateArgumentListInfo TemplateArgs; 3556 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 3557 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 3558 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 3559 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 3560 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3561 TemplateId->getTemplateArgs(), 3562 TemplateId->NumArgs); 3563 translateTemplateArguments(TemplateArgsPtr, 3564 TemplateArgs); 3565 TemplateArgsPtr.release(); 3566 3567 HasExplicitTemplateArgs = true; 3568 3569 if (FunctionTemplate) { 3570 // FIXME: Diagnose function template with explicit template 3571 // arguments. 3572 HasExplicitTemplateArgs = false; 3573 } else if (!isFunctionTemplateSpecialization && 3574 !D.getDeclSpec().isFriendSpecified()) { 3575 // We have encountered something that the user meant to be a 3576 // specialization (because it has explicitly-specified template 3577 // arguments) but that was not introduced with a "template<>" (or had 3578 // too few of them). 3579 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 3580 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 3581 << FixItHint::CreateInsertion( 3582 D.getDeclSpec().getSourceRange().getBegin(), 3583 "template<> "); 3584 isFunctionTemplateSpecialization = true; 3585 } else { 3586 // "friend void foo<>(int);" is an implicit specialization decl. 3587 isFunctionTemplateSpecialization = true; 3588 } 3589 } else if (isFriend && isFunctionTemplateSpecialization) { 3590 // This combination is only possible in a recovery case; the user 3591 // wrote something like: 3592 // template <> friend void foo(int); 3593 // which we're recovering from as if the user had written: 3594 // friend void foo<>(int); 3595 // Go ahead and fake up a template id. 3596 HasExplicitTemplateArgs = true; 3597 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 3598 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 3599 } 3600 3601 // If it's a friend (and only if it's a friend), it's possible 3602 // that either the specialized function type or the specialized 3603 // template is dependent, and therefore matching will fail. In 3604 // this case, don't check the specialization yet. 3605 if (isFunctionTemplateSpecialization && isFriend && 3606 (NewFD->getType()->isDependentType() || DC->isDependentContext())) { 3607 assert(HasExplicitTemplateArgs && 3608 "friend function specialization without template args"); 3609 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 3610 Previous)) 3611 NewFD->setInvalidDecl(); 3612 } else if (isFunctionTemplateSpecialization) { 3613 if (CheckFunctionTemplateSpecialization(NewFD, 3614 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 3615 Previous)) 3616 NewFD->setInvalidDecl(); 3617 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 3618 if (CheckMemberSpecialization(NewFD, Previous)) 3619 NewFD->setInvalidDecl(); 3620 } 3621 3622 // Perform semantic checking on the function declaration. 3623 bool OverloadableAttrRequired = false; // FIXME: HACK! 3624 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 3625 Redeclaration, /*FIXME:*/OverloadableAttrRequired); 3626 3627 assert((NewFD->isInvalidDecl() || !Redeclaration || 3628 Previous.getResultKind() != LookupResult::FoundOverloaded) && 3629 "previous declaration set still overloaded"); 3630 3631 NamedDecl *PrincipalDecl = (FunctionTemplate 3632 ? cast<NamedDecl>(FunctionTemplate) 3633 : NewFD); 3634 3635 if (isFriend && Redeclaration) { 3636 AccessSpecifier Access = AS_public; 3637 if (!NewFD->isInvalidDecl()) 3638 Access = NewFD->getPreviousDeclaration()->getAccess(); 3639 3640 NewFD->setAccess(Access); 3641 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 3642 3643 PrincipalDecl->setObjectOfFriendDecl(true); 3644 } 3645 3646 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 3647 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 3648 PrincipalDecl->setNonMemberOperator(); 3649 3650 // If we have a function template, check the template parameter 3651 // list. This will check and merge default template arguments. 3652 if (FunctionTemplate) { 3653 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration(); 3654 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 3655 PrevTemplate? PrevTemplate->getTemplateParameters() : 0, 3656 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate 3657 : TPC_FunctionTemplate); 3658 } 3659 3660 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) { 3661 // Fake up an access specifier if it's supposed to be a class member. 3662 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext())) 3663 NewFD->setAccess(AS_public); 3664 3665 // An out-of-line member function declaration must also be a 3666 // definition (C++ [dcl.meaning]p1). 3667 // Note that this is not the case for explicit specializations of 3668 // function templates or member functions of class templates, per 3669 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension 3670 // for compatibility with old SWIG code which likes to generate them. 3671 if (!IsFunctionDefinition && !isFriend && 3672 !isFunctionTemplateSpecialization && !isExplicitSpecialization) { 3673 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 3674 << D.getCXXScopeSpec().getRange(); 3675 } 3676 if (!Redeclaration && !(isFriend && CurContext->isDependentContext())) { 3677 // The user tried to provide an out-of-line definition for a 3678 // function that is a member of a class or namespace, but there 3679 // was no such member function declared (C++ [class.mfct]p2, 3680 // C++ [namespace.memdef]p2). For example: 3681 // 3682 // class X { 3683 // void f() const; 3684 // }; 3685 // 3686 // void X::f() { } // ill-formed 3687 // 3688 // Complain about this problem, and attempt to suggest close 3689 // matches (e.g., those that differ only in cv-qualifiers and 3690 // whether the parameter types are references). 3691 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 3692 << Name << DC << D.getCXXScopeSpec().getRange(); 3693 NewFD->setInvalidDecl(); 3694 3695 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 3696 ForRedeclaration); 3697 LookupQualifiedName(Prev, DC); 3698 assert(!Prev.isAmbiguous() && 3699 "Cannot have an ambiguity in previous-declaration lookup"); 3700 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 3701 Func != FuncEnd; ++Func) { 3702 if (isa<FunctionDecl>(*Func) && 3703 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD)) 3704 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 3705 } 3706 } 3707 } 3708 3709 // Handle attributes. We need to have merged decls when handling attributes 3710 // (for example to check for conflicts, etc). 3711 // FIXME: This needs to happen before we merge declarations. Then, 3712 // let attribute merging cope with attribute conflicts. 3713 ProcessDeclAttributes(S, NewFD, D); 3714 3715 // attributes declared post-definition are currently ignored 3716 // FIXME: This should happen during attribute merging 3717 if (Redeclaration && Previous.isSingleResult()) { 3718 const FunctionDecl *Def; 3719 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 3720 if (PrevFD && PrevFD->hasBody(Def) && D.hasAttributes()) { 3721 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 3722 Diag(Def->getLocation(), diag::note_previous_definition); 3723 } 3724 } 3725 3726 AddKnownFunctionAttributes(NewFD); 3727 3728 if (OverloadableAttrRequired && !NewFD->hasAttr<OverloadableAttr>()) { 3729 // If a function name is overloadable in C, then every function 3730 // with that name must be marked "overloadable". 3731 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 3732 << Redeclaration << NewFD; 3733 if (!Previous.empty()) 3734 Diag(Previous.getRepresentativeDecl()->getLocation(), 3735 diag::note_attribute_overloadable_prev_overload); 3736 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), Context)); 3737 } 3738 3739 if (NewFD->hasAttr<OverloadableAttr>() && 3740 !NewFD->getType()->getAs<FunctionProtoType>()) { 3741 Diag(NewFD->getLocation(), 3742 diag::err_attribute_overloadable_no_prototype) 3743 << NewFD; 3744 3745 // Turn this into a variadic function with no parameters. 3746 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 3747 QualType R = Context.getFunctionType(FT->getResultType(), 3748 0, 0, true, 0, false, false, 0, 0, 3749 FT->getExtInfo()); 3750 NewFD->setType(R); 3751 } 3752 3753 // If there's a #pragma GCC visibility in scope, and this isn't a class 3754 // member, set the visibility of this function. 3755 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 3756 AddPushedVisibilityAttribute(NewFD); 3757 3758 // If this is a locally-scoped extern C function, update the 3759 // map of such names. 3760 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 3761 && !NewFD->isInvalidDecl()) 3762 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 3763 3764 // Set this FunctionDecl's range up to the right paren. 3765 NewFD->setLocEnd(D.getSourceRange().getEnd()); 3766 3767 if (FunctionTemplate && NewFD->isInvalidDecl()) 3768 FunctionTemplate->setInvalidDecl(); 3769 3770 if (FunctionTemplate) 3771 return FunctionTemplate; 3772 3773 MarkUnusedFileScopedDecl(NewFD); 3774 3775 return NewFD; 3776} 3777 3778/// \brief Perform semantic checking of a new function declaration. 3779/// 3780/// Performs semantic analysis of the new function declaration 3781/// NewFD. This routine performs all semantic checking that does not 3782/// require the actual declarator involved in the declaration, and is 3783/// used both for the declaration of functions as they are parsed 3784/// (called via ActOnDeclarator) and for the declaration of functions 3785/// that have been instantiated via C++ template instantiation (called 3786/// via InstantiateDecl). 3787/// 3788/// \param IsExplicitSpecialiation whether this new function declaration is 3789/// an explicit specialization of the previous declaration. 3790/// 3791/// This sets NewFD->isInvalidDecl() to true if there was an error. 3792void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 3793 LookupResult &Previous, 3794 bool IsExplicitSpecialization, 3795 bool &Redeclaration, 3796 bool &OverloadableAttrRequired) { 3797 // If NewFD is already known erroneous, don't do any of this checking. 3798 if (NewFD->isInvalidDecl()) { 3799 // If this is a class member, mark the class invalid immediately. 3800 // This avoids some consistency errors later. 3801 if (isa<CXXMethodDecl>(NewFD)) 3802 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl(); 3803 3804 return; 3805 } 3806 3807 if (NewFD->getResultType()->isVariablyModifiedType()) { 3808 // Functions returning a variably modified type violate C99 6.7.5.2p2 3809 // because all functions have linkage. 3810 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 3811 return NewFD->setInvalidDecl(); 3812 } 3813 3814 if (NewFD->isMain()) 3815 CheckMain(NewFD); 3816 3817 // Check for a previous declaration of this name. 3818 if (Previous.empty() && NewFD->isExternC()) { 3819 // Since we did not find anything by this name and we're declaring 3820 // an extern "C" function, look for a non-visible extern "C" 3821 // declaration with the same name. 3822 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3823 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 3824 if (Pos != LocallyScopedExternalDecls.end()) 3825 Previous.addDecl(Pos->second); 3826 } 3827 3828 // Merge or overload the declaration with an existing declaration of 3829 // the same name, if appropriate. 3830 if (!Previous.empty()) { 3831 // Determine whether NewFD is an overload of PrevDecl or 3832 // a declaration that requires merging. If it's an overload, 3833 // there's no more work to do here; we'll just add the new 3834 // function to the scope. 3835 3836 NamedDecl *OldDecl = 0; 3837 if (!AllowOverloadingOfFunction(Previous, Context)) { 3838 Redeclaration = true; 3839 OldDecl = Previous.getFoundDecl(); 3840 } else { 3841 if (!getLangOptions().CPlusPlus) 3842 OverloadableAttrRequired = true; 3843 3844 switch (CheckOverload(S, NewFD, Previous, OldDecl, 3845 /*NewIsUsingDecl*/ false)) { 3846 case Ovl_Match: 3847 Redeclaration = true; 3848 break; 3849 3850 case Ovl_NonFunction: 3851 Redeclaration = true; 3852 break; 3853 3854 case Ovl_Overload: 3855 Redeclaration = false; 3856 break; 3857 } 3858 } 3859 3860 if (Redeclaration) { 3861 // NewFD and OldDecl represent declarations that need to be 3862 // merged. 3863 if (MergeFunctionDecl(NewFD, OldDecl)) 3864 return NewFD->setInvalidDecl(); 3865 3866 Previous.clear(); 3867 Previous.addDecl(OldDecl); 3868 3869 if (FunctionTemplateDecl *OldTemplateDecl 3870 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 3871 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 3872 FunctionTemplateDecl *NewTemplateDecl 3873 = NewFD->getDescribedFunctionTemplate(); 3874 assert(NewTemplateDecl && "Template/non-template mismatch"); 3875 if (CXXMethodDecl *Method 3876 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 3877 Method->setAccess(OldTemplateDecl->getAccess()); 3878 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 3879 } 3880 3881 // If this is an explicit specialization of a member that is a function 3882 // template, mark it as a member specialization. 3883 if (IsExplicitSpecialization && 3884 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 3885 NewTemplateDecl->setMemberSpecialization(); 3886 assert(OldTemplateDecl->isMemberSpecialization()); 3887 } 3888 } else { 3889 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 3890 NewFD->setAccess(OldDecl->getAccess()); 3891 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 3892 } 3893 } 3894 } 3895 3896 // Semantic checking for this function declaration (in isolation). 3897 if (getLangOptions().CPlusPlus) { 3898 // C++-specific checks. 3899 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 3900 CheckConstructor(Constructor); 3901 } else if (CXXDestructorDecl *Destructor = 3902 dyn_cast<CXXDestructorDecl>(NewFD)) { 3903 CXXRecordDecl *Record = Destructor->getParent(); 3904 QualType ClassType = Context.getTypeDeclType(Record); 3905 3906 // FIXME: Shouldn't we be able to perform this check even when the class 3907 // type is dependent? Both gcc and edg can handle that. 3908 if (!ClassType->isDependentType()) { 3909 DeclarationName Name 3910 = Context.DeclarationNames.getCXXDestructorName( 3911 Context.getCanonicalType(ClassType)); 3912// NewFD->getDeclName().dump(); 3913// Name.dump(); 3914 if (NewFD->getDeclName() != Name) { 3915 Diag(NewFD->getLocation(), diag::err_destructor_name); 3916 return NewFD->setInvalidDecl(); 3917 } 3918 } 3919 3920 Record->setUserDeclaredDestructor(true); 3921 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 3922 // user-defined destructor. 3923 Record->setPOD(false); 3924 3925 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly- 3926 // declared destructor. 3927 // FIXME: C++0x: don't do this for "= default" destructors 3928 Record->setHasTrivialDestructor(false); 3929 } else if (CXXConversionDecl *Conversion 3930 = dyn_cast<CXXConversionDecl>(NewFD)) { 3931 ActOnConversionDeclarator(Conversion); 3932 } 3933 3934 // Find any virtual functions that this function overrides. 3935 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 3936 if (!Method->isFunctionTemplateSpecialization() && 3937 !Method->getDescribedFunctionTemplate()) 3938 AddOverriddenMethods(Method->getParent(), Method); 3939 } 3940 3941 // Extra checking for C++ overloaded operators (C++ [over.oper]). 3942 if (NewFD->isOverloadedOperator() && 3943 CheckOverloadedOperatorDeclaration(NewFD)) 3944 return NewFD->setInvalidDecl(); 3945 3946 // Extra checking for C++0x literal operators (C++0x [over.literal]). 3947 if (NewFD->getLiteralIdentifier() && 3948 CheckLiteralOperatorDeclaration(NewFD)) 3949 return NewFD->setInvalidDecl(); 3950 3951 // In C++, check default arguments now that we have merged decls. Unless 3952 // the lexical context is the class, because in this case this is done 3953 // during delayed parsing anyway. 3954 if (!CurContext->isRecord()) 3955 CheckCXXDefaultArguments(NewFD); 3956 } 3957} 3958 3959void Sema::CheckMain(FunctionDecl* FD) { 3960 // C++ [basic.start.main]p3: A program that declares main to be inline 3961 // or static is ill-formed. 3962 // C99 6.7.4p4: In a hosted environment, the inline function specifier 3963 // shall not appear in a declaration of main. 3964 // static main is not an error under C99, but we should warn about it. 3965 bool isInline = FD->isInlineSpecified(); 3966 bool isStatic = FD->getStorageClass() == FunctionDecl::Static; 3967 if (isInline || isStatic) { 3968 unsigned diagID = diag::warn_unusual_main_decl; 3969 if (isInline || getLangOptions().CPlusPlus) 3970 diagID = diag::err_unusual_main_decl; 3971 3972 int which = isStatic + (isInline << 1) - 1; 3973 Diag(FD->getLocation(), diagID) << which; 3974 } 3975 3976 QualType T = FD->getType(); 3977 assert(T->isFunctionType() && "function decl is not of function type"); 3978 const FunctionType* FT = T->getAs<FunctionType>(); 3979 3980 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 3981 // TODO: add a replacement fixit to turn the return type into 'int'. 3982 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 3983 FD->setInvalidDecl(true); 3984 } 3985 3986 // Treat protoless main() as nullary. 3987 if (isa<FunctionNoProtoType>(FT)) return; 3988 3989 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 3990 unsigned nparams = FTP->getNumArgs(); 3991 assert(FD->getNumParams() == nparams); 3992 3993 bool HasExtraParameters = (nparams > 3); 3994 3995 // Darwin passes an undocumented fourth argument of type char**. If 3996 // other platforms start sprouting these, the logic below will start 3997 // getting shifty. 3998 if (nparams == 4 && 3999 Context.Target.getTriple().getOS() == llvm::Triple::Darwin) 4000 HasExtraParameters = false; 4001 4002 if (HasExtraParameters) { 4003 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 4004 FD->setInvalidDecl(true); 4005 nparams = 3; 4006 } 4007 4008 // FIXME: a lot of the following diagnostics would be improved 4009 // if we had some location information about types. 4010 4011 QualType CharPP = 4012 Context.getPointerType(Context.getPointerType(Context.CharTy)); 4013 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 4014 4015 for (unsigned i = 0; i < nparams; ++i) { 4016 QualType AT = FTP->getArgType(i); 4017 4018 bool mismatch = true; 4019 4020 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 4021 mismatch = false; 4022 else if (Expected[i] == CharPP) { 4023 // As an extension, the following forms are okay: 4024 // char const ** 4025 // char const * const * 4026 // char * const * 4027 4028 QualifierCollector qs; 4029 const PointerType* PT; 4030 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 4031 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 4032 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 4033 qs.removeConst(); 4034 mismatch = !qs.empty(); 4035 } 4036 } 4037 4038 if (mismatch) { 4039 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 4040 // TODO: suggest replacing given type with expected type 4041 FD->setInvalidDecl(true); 4042 } 4043 } 4044 4045 if (nparams == 1 && !FD->isInvalidDecl()) { 4046 Diag(FD->getLocation(), diag::warn_main_one_arg); 4047 } 4048} 4049 4050bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 4051 // FIXME: Need strict checking. In C89, we need to check for 4052 // any assignment, increment, decrement, function-calls, or 4053 // commas outside of a sizeof. In C99, it's the same list, 4054 // except that the aforementioned are allowed in unevaluated 4055 // expressions. Everything else falls under the 4056 // "may accept other forms of constant expressions" exception. 4057 // (We never end up here for C++, so the constant expression 4058 // rules there don't matter.) 4059 if (Init->isConstantInitializer(Context, false)) 4060 return false; 4061 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 4062 << Init->getSourceRange(); 4063 return true; 4064} 4065 4066void Sema::AddInitializerToDecl(Decl *dcl, Expr *init) { 4067 AddInitializerToDecl(dcl, init, /*DirectInit=*/false); 4068} 4069 4070/// AddInitializerToDecl - Adds the initializer Init to the 4071/// declaration dcl. If DirectInit is true, this is C++ direct 4072/// initialization rather than copy initialization. 4073void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 4074 // If there is no declaration, there was an error parsing it. Just ignore 4075 // the initializer. 4076 if (RealDecl == 0) 4077 return; 4078 4079 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 4080 // With declarators parsed the way they are, the parser cannot 4081 // distinguish between a normal initializer and a pure-specifier. 4082 // Thus this grotesque test. 4083 IntegerLiteral *IL; 4084 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 4085 Context.getCanonicalType(IL->getType()) == Context.IntTy) 4086 CheckPureMethod(Method, Init->getSourceRange()); 4087 else { 4088 Diag(Method->getLocation(), diag::err_member_function_initialization) 4089 << Method->getDeclName() << Init->getSourceRange(); 4090 Method->setInvalidDecl(); 4091 } 4092 return; 4093 } 4094 4095 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 4096 if (!VDecl) { 4097 if (getLangOptions().CPlusPlus && 4098 RealDecl->getLexicalDeclContext()->isRecord() && 4099 isa<NamedDecl>(RealDecl)) 4100 Diag(RealDecl->getLocation(), diag::err_member_initialization) 4101 << cast<NamedDecl>(RealDecl)->getDeclName(); 4102 else 4103 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 4104 RealDecl->setInvalidDecl(); 4105 return; 4106 } 4107 4108 4109 4110 // A definition must end up with a complete type, which means it must be 4111 // complete with the restriction that an array type might be completed by the 4112 // initializer; note that later code assumes this restriction. 4113 QualType BaseDeclType = VDecl->getType(); 4114 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 4115 BaseDeclType = Array->getElementType(); 4116 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 4117 diag::err_typecheck_decl_incomplete_type)) { 4118 RealDecl->setInvalidDecl(); 4119 return; 4120 } 4121 4122 // The variable can not have an abstract class type. 4123 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 4124 diag::err_abstract_type_in_decl, 4125 AbstractVariableType)) 4126 VDecl->setInvalidDecl(); 4127 4128 const VarDecl *Def; 4129 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 4130 Diag(VDecl->getLocation(), diag::err_redefinition) 4131 << VDecl->getDeclName(); 4132 Diag(Def->getLocation(), diag::note_previous_definition); 4133 VDecl->setInvalidDecl(); 4134 return; 4135 } 4136 4137 // C++ [class.static.data]p4 4138 // If a static data member is of const integral or const 4139 // enumeration type, its declaration in the class definition can 4140 // specify a constant-initializer which shall be an integral 4141 // constant expression (5.19). In that case, the member can appear 4142 // in integral constant expressions. The member shall still be 4143 // defined in a namespace scope if it is used in the program and the 4144 // namespace scope definition shall not contain an initializer. 4145 // 4146 // We already performed a redefinition check above, but for static 4147 // data members we also need to check whether there was an in-class 4148 // declaration with an initializer. 4149 const VarDecl* PrevInit = 0; 4150 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 4151 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 4152 Diag(PrevInit->getLocation(), diag::note_previous_definition); 4153 return; 4154 } 4155 4156 if (getLangOptions().CPlusPlus && VDecl->hasLocalStorage()) 4157 getCurFunction()->setHasBranchProtectedScope(); 4158 4159 // Capture the variable that is being initialized and the style of 4160 // initialization. 4161 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 4162 4163 // FIXME: Poor source location information. 4164 InitializationKind Kind 4165 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 4166 Init->getLocStart(), 4167 Init->getLocEnd()) 4168 : InitializationKind::CreateCopy(VDecl->getLocation(), 4169 Init->getLocStart()); 4170 4171 // Get the decls type and save a reference for later, since 4172 // CheckInitializerTypes may change it. 4173 QualType DclT = VDecl->getType(), SavT = DclT; 4174 if (VDecl->isBlockVarDecl()) { 4175 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 4176 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 4177 VDecl->setInvalidDecl(); 4178 } else if (!VDecl->isInvalidDecl()) { 4179 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 4180 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4181 MultiExprArg(*this, &Init, 1), 4182 &DclT); 4183 if (Result.isInvalid()) { 4184 VDecl->setInvalidDecl(); 4185 return; 4186 } 4187 4188 Init = Result.takeAs<Expr>(); 4189 4190 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 4191 // Don't check invalid declarations to avoid emitting useless diagnostics. 4192 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 4193 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4. 4194 CheckForConstantInitializer(Init, DclT); 4195 } 4196 } 4197 } else if (VDecl->isStaticDataMember() && 4198 VDecl->getLexicalDeclContext()->isRecord()) { 4199 // This is an in-class initialization for a static data member, e.g., 4200 // 4201 // struct S { 4202 // static const int value = 17; 4203 // }; 4204 4205 // Attach the initializer 4206 VDecl->setInit(Init); 4207 4208 // C++ [class.mem]p4: 4209 // A member-declarator can contain a constant-initializer only 4210 // if it declares a static member (9.4) of const integral or 4211 // const enumeration type, see 9.4.2. 4212 QualType T = VDecl->getType(); 4213 if (!T->isDependentType() && 4214 (!Context.getCanonicalType(T).isConstQualified() || 4215 !T->isIntegralOrEnumerationType())) { 4216 Diag(VDecl->getLocation(), diag::err_member_initialization) 4217 << VDecl->getDeclName() << Init->getSourceRange(); 4218 VDecl->setInvalidDecl(); 4219 } else { 4220 // C++ [class.static.data]p4: 4221 // If a static data member is of const integral or const 4222 // enumeration type, its declaration in the class definition 4223 // can specify a constant-initializer which shall be an 4224 // integral constant expression (5.19). 4225 if (!Init->isTypeDependent() && 4226 !Init->getType()->isIntegralOrEnumerationType()) { 4227 // We have a non-dependent, non-integral or enumeration type. 4228 Diag(Init->getSourceRange().getBegin(), 4229 diag::err_in_class_initializer_non_integral_type) 4230 << Init->getType() << Init->getSourceRange(); 4231 VDecl->setInvalidDecl(); 4232 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) { 4233 // Check whether the expression is a constant expression. 4234 llvm::APSInt Value; 4235 SourceLocation Loc; 4236 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) { 4237 Diag(Loc, diag::err_in_class_initializer_non_constant) 4238 << Init->getSourceRange(); 4239 VDecl->setInvalidDecl(); 4240 } else if (!VDecl->getType()->isDependentType()) 4241 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast); 4242 } 4243 } 4244 } else if (VDecl->isFileVarDecl()) { 4245 if (VDecl->getStorageClass() == VarDecl::Extern && 4246 (!getLangOptions().CPlusPlus || 4247 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 4248 Diag(VDecl->getLocation(), diag::warn_extern_init); 4249 if (!VDecl->isInvalidDecl()) { 4250 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 4251 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4252 MultiExprArg(*this, &Init, 1), 4253 &DclT); 4254 if (Result.isInvalid()) { 4255 VDecl->setInvalidDecl(); 4256 return; 4257 } 4258 4259 Init = Result.takeAs<Expr>(); 4260 } 4261 4262 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 4263 // Don't check invalid declarations to avoid emitting useless diagnostics. 4264 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 4265 // C99 6.7.8p4. All file scoped initializers need to be constant. 4266 CheckForConstantInitializer(Init, DclT); 4267 } 4268 } 4269 // If the type changed, it means we had an incomplete type that was 4270 // completed by the initializer. For example: 4271 // int ary[] = { 1, 3, 5 }; 4272 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 4273 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 4274 VDecl->setType(DclT); 4275 Init->setType(DclT); 4276 } 4277 4278 Init = MaybeCreateCXXExprWithTemporaries(Init); 4279 // Attach the initializer to the decl. 4280 VDecl->setInit(Init); 4281 4282 if (getLangOptions().CPlusPlus) { 4283 if (!VDecl->isInvalidDecl() && 4284 !VDecl->getDeclContext()->isDependentContext() && 4285 VDecl->hasGlobalStorage() && 4286 !Init->isConstantInitializer(Context, 4287 VDecl->getType()->isReferenceType())) 4288 Diag(VDecl->getLocation(), diag::warn_global_constructor) 4289 << Init->getSourceRange(); 4290 4291 // Make sure we mark the destructor as used if necessary. 4292 QualType InitType = VDecl->getType(); 4293 while (const ArrayType *Array = Context.getAsArrayType(InitType)) 4294 InitType = Context.getBaseElementType(Array); 4295 if (const RecordType *Record = InitType->getAs<RecordType>()) 4296 FinalizeVarWithDestructor(VDecl, Record); 4297 } 4298 4299 return; 4300} 4301 4302/// ActOnInitializerError - Given that there was an error parsing an 4303/// initializer for the given declaration, try to return to some form 4304/// of sanity. 4305void Sema::ActOnInitializerError(Decl *D) { 4306 // Our main concern here is re-establishing invariants like "a 4307 // variable's type is either dependent or complete". 4308 if (!D || D->isInvalidDecl()) return; 4309 4310 VarDecl *VD = dyn_cast<VarDecl>(D); 4311 if (!VD) return; 4312 4313 QualType Ty = VD->getType(); 4314 if (Ty->isDependentType()) return; 4315 4316 // Require a complete type. 4317 if (RequireCompleteType(VD->getLocation(), 4318 Context.getBaseElementType(Ty), 4319 diag::err_typecheck_decl_incomplete_type)) { 4320 VD->setInvalidDecl(); 4321 return; 4322 } 4323 4324 // Require an abstract type. 4325 if (RequireNonAbstractType(VD->getLocation(), Ty, 4326 diag::err_abstract_type_in_decl, 4327 AbstractVariableType)) { 4328 VD->setInvalidDecl(); 4329 return; 4330 } 4331 4332 // Don't bother complaining about constructors or destructors, 4333 // though. 4334} 4335 4336void Sema::ActOnUninitializedDecl(Decl *RealDecl, 4337 bool TypeContainsUndeducedAuto) { 4338 // If there is no declaration, there was an error parsing it. Just ignore it. 4339 if (RealDecl == 0) 4340 return; 4341 4342 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 4343 QualType Type = Var->getType(); 4344 4345 // C++0x [dcl.spec.auto]p3 4346 if (TypeContainsUndeducedAuto) { 4347 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 4348 << Var->getDeclName() << Type; 4349 Var->setInvalidDecl(); 4350 return; 4351 } 4352 4353 switch (Var->isThisDeclarationADefinition()) { 4354 case VarDecl::Definition: 4355 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 4356 break; 4357 4358 // We have an out-of-line definition of a static data member 4359 // that has an in-class initializer, so we type-check this like 4360 // a declaration. 4361 // 4362 // Fall through 4363 4364 case VarDecl::DeclarationOnly: 4365 // It's only a declaration. 4366 4367 // Block scope. C99 6.7p7: If an identifier for an object is 4368 // declared with no linkage (C99 6.2.2p6), the type for the 4369 // object shall be complete. 4370 if (!Type->isDependentType() && Var->isBlockVarDecl() && 4371 !Var->getLinkage() && !Var->isInvalidDecl() && 4372 RequireCompleteType(Var->getLocation(), Type, 4373 diag::err_typecheck_decl_incomplete_type)) 4374 Var->setInvalidDecl(); 4375 4376 // Make sure that the type is not abstract. 4377 if (!Type->isDependentType() && !Var->isInvalidDecl() && 4378 RequireNonAbstractType(Var->getLocation(), Type, 4379 diag::err_abstract_type_in_decl, 4380 AbstractVariableType)) 4381 Var->setInvalidDecl(); 4382 return; 4383 4384 case VarDecl::TentativeDefinition: 4385 // File scope. C99 6.9.2p2: A declaration of an identifier for an 4386 // object that has file scope without an initializer, and without a 4387 // storage-class specifier or with the storage-class specifier "static", 4388 // constitutes a tentative definition. Note: A tentative definition with 4389 // external linkage is valid (C99 6.2.2p5). 4390 if (!Var->isInvalidDecl()) { 4391 if (const IncompleteArrayType *ArrayT 4392 = Context.getAsIncompleteArrayType(Type)) { 4393 if (RequireCompleteType(Var->getLocation(), 4394 ArrayT->getElementType(), 4395 diag::err_illegal_decl_array_incomplete_type)) 4396 Var->setInvalidDecl(); 4397 } else if (Var->getStorageClass() == VarDecl::Static) { 4398 // C99 6.9.2p3: If the declaration of an identifier for an object is 4399 // a tentative definition and has internal linkage (C99 6.2.2p3), the 4400 // declared type shall not be an incomplete type. 4401 // NOTE: code such as the following 4402 // static struct s; 4403 // struct s { int a; }; 4404 // is accepted by gcc. Hence here we issue a warning instead of 4405 // an error and we do not invalidate the static declaration. 4406 // NOTE: to avoid multiple warnings, only check the first declaration. 4407 if (Var->getPreviousDeclaration() == 0) 4408 RequireCompleteType(Var->getLocation(), Type, 4409 diag::ext_typecheck_decl_incomplete_type); 4410 } 4411 } 4412 4413 // Record the tentative definition; we're done. 4414 if (!Var->isInvalidDecl()) 4415 TentativeDefinitions.push_back(Var); 4416 return; 4417 } 4418 4419 // Provide a specific diagnostic for uninitialized variable 4420 // definitions with incomplete array type. 4421 if (Type->isIncompleteArrayType()) { 4422 Diag(Var->getLocation(), 4423 diag::err_typecheck_incomplete_array_needs_initializer); 4424 Var->setInvalidDecl(); 4425 return; 4426 } 4427 4428 // Provide a specific diagnostic for uninitialized variable 4429 // definitions with reference type. 4430 if (Type->isReferenceType()) { 4431 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 4432 << Var->getDeclName() 4433 << SourceRange(Var->getLocation(), Var->getLocation()); 4434 Var->setInvalidDecl(); 4435 return; 4436 } 4437 4438 // Do not attempt to type-check the default initializer for a 4439 // variable with dependent type. 4440 if (Type->isDependentType()) 4441 return; 4442 4443 if (Var->isInvalidDecl()) 4444 return; 4445 4446 if (RequireCompleteType(Var->getLocation(), 4447 Context.getBaseElementType(Type), 4448 diag::err_typecheck_decl_incomplete_type)) { 4449 Var->setInvalidDecl(); 4450 return; 4451 } 4452 4453 // The variable can not have an abstract class type. 4454 if (RequireNonAbstractType(Var->getLocation(), Type, 4455 diag::err_abstract_type_in_decl, 4456 AbstractVariableType)) { 4457 Var->setInvalidDecl(); 4458 return; 4459 } 4460 4461 const RecordType *Record 4462 = Context.getBaseElementType(Type)->getAs<RecordType>(); 4463 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x && 4464 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) { 4465 // C++03 [dcl.init]p9: 4466 // If no initializer is specified for an object, and the 4467 // object is of (possibly cv-qualified) non-POD class type (or 4468 // array thereof), the object shall be default-initialized; if 4469 // the object is of const-qualified type, the underlying class 4470 // type shall have a user-declared default 4471 // constructor. Otherwise, if no initializer is specified for 4472 // a non- static object, the object and its subobjects, if 4473 // any, have an indeterminate initial value); if the object 4474 // or any of its subobjects are of const-qualified type, the 4475 // program is ill-formed. 4476 // FIXME: DPG thinks it is very fishy that C++0x disables this. 4477 } else { 4478 // Check for jumps past the implicit initializer. C++0x 4479 // clarifies that this applies to a "variable with automatic 4480 // storage duration", not a "local variable". 4481 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) 4482 getCurFunction()->setHasBranchProtectedScope(); 4483 4484 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 4485 InitializationKind Kind 4486 = InitializationKind::CreateDefault(Var->getLocation()); 4487 4488 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 4489 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 4490 MultiExprArg(*this, 0, 0)); 4491 if (Init.isInvalid()) 4492 Var->setInvalidDecl(); 4493 else if (Init.get()) { 4494 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>())); 4495 4496 if (getLangOptions().CPlusPlus && !Var->isInvalidDecl() && 4497 Var->hasGlobalStorage() && 4498 !Var->getDeclContext()->isDependentContext() && 4499 !Var->getInit()->isConstantInitializer(Context, false)) 4500 Diag(Var->getLocation(), diag::warn_global_constructor); 4501 } 4502 } 4503 4504 if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record) 4505 FinalizeVarWithDestructor(Var, Record); 4506 } 4507} 4508 4509Sema::DeclGroupPtrTy 4510Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 4511 Decl **Group, unsigned NumDecls) { 4512 llvm::SmallVector<Decl*, 8> Decls; 4513 4514 if (DS.isTypeSpecOwned()) 4515 Decls.push_back(DS.getRepAsDecl()); 4516 4517 for (unsigned i = 0; i != NumDecls; ++i) 4518 if (Decl *D = Group[i]) 4519 Decls.push_back(D); 4520 4521 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, 4522 Decls.data(), Decls.size())); 4523} 4524 4525 4526/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 4527/// to introduce parameters into function prototype scope. 4528Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 4529 const DeclSpec &DS = D.getDeclSpec(); 4530 4531 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 4532 VarDecl::StorageClass StorageClass = VarDecl::None; 4533 VarDecl::StorageClass StorageClassAsWritten = VarDecl::None; 4534 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4535 StorageClass = VarDecl::Register; 4536 StorageClassAsWritten = VarDecl::Register; 4537 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 4538 Diag(DS.getStorageClassSpecLoc(), 4539 diag::err_invalid_storage_class_in_func_decl); 4540 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4541 } 4542 4543 if (D.getDeclSpec().isThreadSpecified()) 4544 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4545 4546 DiagnoseFunctionSpecifiers(D); 4547 4548 // Check that there are no default arguments inside the type of this 4549 // parameter (C++ only). 4550 if (getLangOptions().CPlusPlus) 4551 CheckExtraCXXDefaultArguments(D); 4552 4553 TagDecl *OwnedDecl = 0; 4554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl); 4555 QualType parmDeclType = TInfo->getType(); 4556 4557 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) { 4558 // C++ [dcl.fct]p6: 4559 // Types shall not be defined in return or parameter types. 4560 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type) 4561 << Context.getTypeDeclType(OwnedDecl); 4562 } 4563 4564 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 4565 IdentifierInfo *II = D.getIdentifier(); 4566 if (II) { 4567 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 4568 ForRedeclaration); 4569 LookupName(R, S); 4570 if (R.isSingleResult()) { 4571 NamedDecl *PrevDecl = R.getFoundDecl(); 4572 if (PrevDecl->isTemplateParameter()) { 4573 // Maybe we will complain about the shadowed template parameter. 4574 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4575 // Just pretend that we didn't see the previous declaration. 4576 PrevDecl = 0; 4577 } else if (S->isDeclScope(PrevDecl)) { 4578 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 4579 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4580 4581 // Recover by removing the name 4582 II = 0; 4583 D.SetIdentifier(0, D.getIdentifierLoc()); 4584 D.setInvalidType(true); 4585 } 4586 } 4587 } 4588 4589 // Temporarily put parameter variables in the translation unit, not 4590 // the enclosing context. This prevents them from accidentally 4591 // looking like class members in C++. 4592 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 4593 TInfo, parmDeclType, II, 4594 D.getIdentifierLoc(), 4595 StorageClass, StorageClassAsWritten); 4596 4597 if (D.isInvalidType()) 4598 New->setInvalidDecl(); 4599 4600 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4601 if (D.getCXXScopeSpec().isSet()) { 4602 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 4603 << D.getCXXScopeSpec().getRange(); 4604 New->setInvalidDecl(); 4605 } 4606 4607 // Add the parameter declaration into this scope. 4608 S->AddDecl(New); 4609 if (II) 4610 IdResolver.AddDecl(New); 4611 4612 ProcessDeclAttributes(S, New, D); 4613 4614 if (New->hasAttr<BlocksAttr>()) { 4615 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4616 } 4617 return New; 4618} 4619 4620/// \brief Synthesizes a variable for a parameter arising from a 4621/// typedef. 4622ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 4623 SourceLocation Loc, 4624 QualType T) { 4625 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, 0, 4626 T, Context.getTrivialTypeSourceInfo(T, Loc), 4627 VarDecl::None, VarDecl::None, 0); 4628 Param->setImplicit(); 4629 return Param; 4630} 4631 4632void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 4633 ParmVarDecl * const *ParamEnd) { 4634 if (Diags.getDiagnosticLevel(diag::warn_unused_parameter) == 4635 Diagnostic::Ignored) 4636 return; 4637 4638 // Don't diagnose unused-parameter errors in template instantiations; we 4639 // will already have done so in the template itself. 4640 if (!ActiveTemplateInstantiations.empty()) 4641 return; 4642 4643 for (; Param != ParamEnd; ++Param) { 4644 if (!(*Param)->isUsed() && (*Param)->getDeclName() && 4645 !(*Param)->hasAttr<UnusedAttr>()) { 4646 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 4647 << (*Param)->getDeclName(); 4648 } 4649 } 4650} 4651 4652ParmVarDecl *Sema::CheckParameter(DeclContext *DC, 4653 TypeSourceInfo *TSInfo, QualType T, 4654 IdentifierInfo *Name, 4655 SourceLocation NameLoc, 4656 VarDecl::StorageClass StorageClass, 4657 VarDecl::StorageClass StorageClassAsWritten) { 4658 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name, 4659 adjustParameterType(T), TSInfo, 4660 StorageClass, StorageClassAsWritten, 4661 0); 4662 4663 // Parameters can not be abstract class types. 4664 // For record types, this is done by the AbstractClassUsageDiagnoser once 4665 // the class has been completely parsed. 4666 if (!CurContext->isRecord() && 4667 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 4668 AbstractParamType)) 4669 New->setInvalidDecl(); 4670 4671 // Parameter declarators cannot be interface types. All ObjC objects are 4672 // passed by reference. 4673 if (T->isObjCObjectType()) { 4674 Diag(NameLoc, 4675 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 4676 New->setInvalidDecl(); 4677 } 4678 4679 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4680 // duration shall not be qualified by an address-space qualifier." 4681 // Since all parameters have automatic store duration, they can not have 4682 // an address space. 4683 if (T.getAddressSpace() != 0) { 4684 Diag(NameLoc, diag::err_arg_with_address_space); 4685 New->setInvalidDecl(); 4686 } 4687 4688 return New; 4689} 4690 4691void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 4692 SourceLocation LocAfterDecls) { 4693 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 4694 "Not a function declarator!"); 4695 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 4696 4697 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 4698 // for a K&R function. 4699 if (!FTI.hasPrototype) { 4700 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 4701 --i; 4702 if (FTI.ArgInfo[i].Param == 0) { 4703 llvm::SmallString<256> Code; 4704 llvm::raw_svector_ostream(Code) << " int " 4705 << FTI.ArgInfo[i].Ident->getName() 4706 << ";\n"; 4707 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 4708 << FTI.ArgInfo[i].Ident 4709 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 4710 4711 // Implicitly declare the argument as type 'int' for lack of a better 4712 // type. 4713 DeclSpec DS; 4714 const char* PrevSpec; // unused 4715 unsigned DiagID; // unused 4716 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 4717 PrevSpec, DiagID); 4718 Declarator ParamD(DS, Declarator::KNRTypeListContext); 4719 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 4720 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 4721 } 4722 } 4723 } 4724} 4725 4726Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 4727 Declarator &D) { 4728 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 4729 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 4730 "Not a function declarator!"); 4731 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 4732 4733 if (FTI.hasPrototype) { 4734 // FIXME: Diagnose arguments without names in C. 4735 } 4736 4737 Scope *ParentScope = FnBodyScope->getParent(); 4738 4739 Decl *DP = HandleDeclarator(ParentScope, D, 4740 MultiTemplateParamsArg(*this), 4741 /*IsFunctionDefinition=*/true); 4742 return ActOnStartOfFunctionDef(FnBodyScope, DP); 4743} 4744 4745static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 4746 // Don't warn about invalid declarations. 4747 if (FD->isInvalidDecl()) 4748 return false; 4749 4750 // Or declarations that aren't global. 4751 if (!FD->isGlobal()) 4752 return false; 4753 4754 // Don't warn about C++ member functions. 4755 if (isa<CXXMethodDecl>(FD)) 4756 return false; 4757 4758 // Don't warn about 'main'. 4759 if (FD->isMain()) 4760 return false; 4761 4762 // Don't warn about inline functions. 4763 if (FD->isInlineSpecified()) 4764 return false; 4765 4766 // Don't warn about function templates. 4767 if (FD->getDescribedFunctionTemplate()) 4768 return false; 4769 4770 // Don't warn about function template specializations. 4771 if (FD->isFunctionTemplateSpecialization()) 4772 return false; 4773 4774 bool MissingPrototype = true; 4775 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 4776 Prev; Prev = Prev->getPreviousDeclaration()) { 4777 // Ignore any declarations that occur in function or method 4778 // scope, because they aren't visible from the header. 4779 if (Prev->getDeclContext()->isFunctionOrMethod()) 4780 continue; 4781 4782 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 4783 break; 4784 } 4785 4786 return MissingPrototype; 4787} 4788 4789Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 4790 // Clear the last template instantiation error context. 4791 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 4792 4793 if (!D) 4794 return D; 4795 FunctionDecl *FD = 0; 4796 4797 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 4798 FD = FunTmpl->getTemplatedDecl(); 4799 else 4800 FD = cast<FunctionDecl>(D); 4801 4802 // Enter a new function scope 4803 PushFunctionScope(); 4804 4805 // See if this is a redefinition. 4806 // But don't complain if we're in GNU89 mode and the previous definition 4807 // was an extern inline function. 4808 const FunctionDecl *Definition; 4809 if (FD->hasBody(Definition) && 4810 !canRedefineFunction(Definition, getLangOptions())) { 4811 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 4812 Diag(Definition->getLocation(), diag::note_previous_definition); 4813 } 4814 4815 // Builtin functions cannot be defined. 4816 if (unsigned BuiltinID = FD->getBuiltinID()) { 4817 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4818 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 4819 FD->setInvalidDecl(); 4820 } 4821 } 4822 4823 // The return type of a function definition must be complete 4824 // (C99 6.9.1p3, C++ [dcl.fct]p6). 4825 QualType ResultType = FD->getResultType(); 4826 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 4827 !FD->isInvalidDecl() && 4828 RequireCompleteType(FD->getLocation(), ResultType, 4829 diag::err_func_def_incomplete_result)) 4830 FD->setInvalidDecl(); 4831 4832 // GNU warning -Wmissing-prototypes: 4833 // Warn if a global function is defined without a previous 4834 // prototype declaration. This warning is issued even if the 4835 // definition itself provides a prototype. The aim is to detect 4836 // global functions that fail to be declared in header files. 4837 if (ShouldWarnAboutMissingPrototype(FD)) 4838 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 4839 4840 if (FnBodyScope) 4841 PushDeclContext(FnBodyScope, FD); 4842 4843 // Check the validity of our function parameters 4844 CheckParmsForFunctionDef(FD); 4845 4846 bool ShouldCheckShadow = 4847 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored; 4848 4849 // Introduce our parameters into the function scope 4850 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 4851 ParmVarDecl *Param = FD->getParamDecl(p); 4852 Param->setOwningFunction(FD); 4853 4854 // If this has an identifier, add it to the scope stack. 4855 if (Param->getIdentifier() && FnBodyScope) { 4856 if (ShouldCheckShadow) 4857 CheckShadow(FnBodyScope, Param); 4858 4859 PushOnScopeChains(Param, FnBodyScope); 4860 } 4861 } 4862 4863 // Checking attributes of current function definition 4864 // dllimport attribute. 4865 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 4866 if (DA && (!FD->getAttr<DLLExportAttr>())) { 4867 // dllimport attribute cannot be directly applied to definition. 4868 if (!DA->isInherited()) { 4869 Diag(FD->getLocation(), 4870 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 4871 << "dllimport"; 4872 FD->setInvalidDecl(); 4873 return FD; 4874 } 4875 4876 // Visual C++ appears to not think this is an issue, so only issue 4877 // a warning when Microsoft extensions are disabled. 4878 if (!LangOpts.Microsoft) { 4879 // If a symbol previously declared dllimport is later defined, the 4880 // attribute is ignored in subsequent references, and a warning is 4881 // emitted. 4882 Diag(FD->getLocation(), 4883 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4884 << FD->getName() << "dllimport"; 4885 } 4886 } 4887 return FD; 4888} 4889 4890/// \brief Given the set of return statements within a function body, 4891/// compute the variables that are subject to the named return value 4892/// optimization. 4893/// 4894/// Each of the variables that is subject to the named return value 4895/// optimization will be marked as NRVO variables in the AST, and any 4896/// return statement that has a marked NRVO variable as its NRVO candidate can 4897/// use the named return value optimization. 4898/// 4899/// This function applies a very simplistic algorithm for NRVO: if every return 4900/// statement in the function has the same NRVO candidate, that candidate is 4901/// the NRVO variable. 4902/// 4903/// FIXME: Employ a smarter algorithm that accounts for multiple return 4904/// statements and the lifetimes of the NRVO candidates. We should be able to 4905/// find a maximal set of NRVO variables. 4906static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 4907 ReturnStmt **Returns = Scope->Returns.data(); 4908 4909 const VarDecl *NRVOCandidate = 0; 4910 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 4911 if (!Returns[I]->getNRVOCandidate()) 4912 return; 4913 4914 if (!NRVOCandidate) 4915 NRVOCandidate = Returns[I]->getNRVOCandidate(); 4916 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 4917 return; 4918 } 4919 4920 if (NRVOCandidate) 4921 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 4922} 4923 4924Decl *Sema::ActOnFinishFunctionBody(Decl *D, StmtArg BodyArg) { 4925 return ActOnFinishFunctionBody(D, move(BodyArg), false); 4926} 4927 4928Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 4929 bool IsInstantiation) { 4930 FunctionDecl *FD = 0; 4931 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 4932 if (FunTmpl) 4933 FD = FunTmpl->getTemplatedDecl(); 4934 else 4935 FD = dyn_cast_or_null<FunctionDecl>(dcl); 4936 4937 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 4938 4939 if (FD) { 4940 FD->setBody(Body); 4941 if (FD->isMain()) { 4942 // C and C++ allow for main to automagically return 0. 4943 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 4944 FD->setHasImplicitReturnZero(true); 4945 WP.disableCheckFallThrough(); 4946 } 4947 4948 if (!FD->isInvalidDecl()) { 4949 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 4950 4951 // If this is a constructor, we need a vtable. 4952 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 4953 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 4954 4955 ComputeNRVO(Body, getCurFunction()); 4956 } 4957 4958 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 4959 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 4960 assert(MD == getCurMethodDecl() && "Method parsing confused"); 4961 MD->setBody(Body); 4962 MD->setEndLoc(Body->getLocEnd()); 4963 if (!MD->isInvalidDecl()) 4964 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 4965 } else { 4966 return 0; 4967 } 4968 4969 // Verify and clean out per-function state. 4970 4971 // Check goto/label use. 4972 FunctionScopeInfo *CurFn = getCurFunction(); 4973 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 4974 I = CurFn->LabelMap.begin(), E = CurFn->LabelMap.end(); I != E; ++I) { 4975 LabelStmt *L = I->second; 4976 4977 // Verify that we have no forward references left. If so, there was a goto 4978 // or address of a label taken, but no definition of it. Label fwd 4979 // definitions are indicated with a null substmt. 4980 if (L->getSubStmt() != 0) 4981 continue; 4982 4983 // Emit error. 4984 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 4985 4986 // At this point, we have gotos that use the bogus label. Stitch it into 4987 // the function body so that they aren't leaked and that the AST is well 4988 // formed. 4989 if (Body == 0) { 4990 // The whole function wasn't parsed correctly. 4991 continue; 4992 } 4993 4994 // Otherwise, the body is valid: we want to stitch the label decl into the 4995 // function somewhere so that it is properly owned and so that the goto 4996 // has a valid target. Do this by creating a new compound stmt with the 4997 // label in it. 4998 4999 // Give the label a sub-statement. 5000 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 5001 5002 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ? 5003 cast<CXXTryStmt>(Body)->getTryBlock() : 5004 cast<CompoundStmt>(Body); 5005 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(), 5006 Compound->body_end()); 5007 Elements.push_back(L); 5008 Compound->setStmts(Context, Elements.data(), Elements.size()); 5009 } 5010 5011 if (Body) { 5012 // C++ constructors that have function-try-blocks can't have return 5013 // statements in the handlers of that block. (C++ [except.handle]p14) 5014 // Verify this. 5015 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 5016 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 5017 5018 // Verify that that gotos and switch cases don't jump into scopes illegally. 5019 // Verify that that gotos and switch cases don't jump into scopes illegally. 5020 if (getCurFunction()->NeedsScopeChecking() && 5021 !dcl->isInvalidDecl() && 5022 !hasAnyErrorsInThisFunction()) 5023 DiagnoseInvalidJumps(Body); 5024 5025 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 5026 if (!Destructor->getParent()->isDependentType()) 5027 CheckDestructor(Destructor); 5028 5029 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 5030 Destructor->getParent()); 5031 } 5032 5033 // If any errors have occurred, clear out any temporaries that may have 5034 // been leftover. This ensures that these temporaries won't be picked up for 5035 // deletion in some later function. 5036 if (PP.getDiagnostics().hasErrorOccurred()) 5037 ExprTemporaries.clear(); 5038 else if (!isa<FunctionTemplateDecl>(dcl)) { 5039 // Since the body is valid, issue any analysis-based warnings that are 5040 // enabled. 5041 QualType ResultType; 5042 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) { 5043 AnalysisWarnings.IssueWarnings(WP, FD); 5044 } else { 5045 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl); 5046 AnalysisWarnings.IssueWarnings(WP, MD); 5047 } 5048 } 5049 5050 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 5051 } 5052 5053 if (!IsInstantiation) 5054 PopDeclContext(); 5055 5056 PopFunctionOrBlockScope(); 5057 5058 // If any errors have occurred, clear out any temporaries that may have 5059 // been leftover. This ensures that these temporaries won't be picked up for 5060 // deletion in some later function. 5061 if (getDiagnostics().hasErrorOccurred()) 5062 ExprTemporaries.clear(); 5063 5064 return dcl; 5065} 5066 5067/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 5068/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 5069NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 5070 IdentifierInfo &II, Scope *S) { 5071 // Before we produce a declaration for an implicitly defined 5072 // function, see whether there was a locally-scoped declaration of 5073 // this name as a function or variable. If so, use that 5074 // (non-visible) declaration, and complain about it. 5075 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5076 = LocallyScopedExternalDecls.find(&II); 5077 if (Pos != LocallyScopedExternalDecls.end()) { 5078 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 5079 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 5080 return Pos->second; 5081 } 5082 5083 // Extension in C99. Legal in C90, but warn about it. 5084 if (II.getName().startswith("__builtin_")) 5085 Diag(Loc, diag::warn_builtin_unknown) << &II; 5086 else if (getLangOptions().C99) 5087 Diag(Loc, diag::ext_implicit_function_decl) << &II; 5088 else 5089 Diag(Loc, diag::warn_implicit_function_decl) << &II; 5090 5091 // Set a Declarator for the implicit definition: int foo(); 5092 const char *Dummy; 5093 DeclSpec DS; 5094 unsigned DiagID; 5095 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 5096 Error = Error; // Silence warning. 5097 assert(!Error && "Error setting up implicit decl!"); 5098 Declarator D(DS, Declarator::BlockContext); 5099 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 5100 0, 0, false, SourceLocation(), 5101 false, 0,0,0, Loc, Loc, D), 5102 SourceLocation()); 5103 D.SetIdentifier(&II, Loc); 5104 5105 // Insert this function into translation-unit scope. 5106 5107 DeclContext *PrevDC = CurContext; 5108 CurContext = Context.getTranslationUnitDecl(); 5109 5110 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 5111 FD->setImplicit(); 5112 5113 CurContext = PrevDC; 5114 5115 AddKnownFunctionAttributes(FD); 5116 5117 return FD; 5118} 5119 5120/// \brief Adds any function attributes that we know a priori based on 5121/// the declaration of this function. 5122/// 5123/// These attributes can apply both to implicitly-declared builtins 5124/// (like __builtin___printf_chk) or to library-declared functions 5125/// like NSLog or printf. 5126void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 5127 if (FD->isInvalidDecl()) 5128 return; 5129 5130 // If this is a built-in function, map its builtin attributes to 5131 // actual attributes. 5132 if (unsigned BuiltinID = FD->getBuiltinID()) { 5133 // Handle printf-formatting attributes. 5134 unsigned FormatIdx; 5135 bool HasVAListArg; 5136 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 5137 if (!FD->getAttr<FormatAttr>()) 5138 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 5139 "printf", FormatIdx+1, 5140 HasVAListArg ? 0 : FormatIdx+2)); 5141 } 5142 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 5143 HasVAListArg)) { 5144 if (!FD->getAttr<FormatAttr>()) 5145 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 5146 "scanf", FormatIdx+1, 5147 HasVAListArg ? 0 : FormatIdx+2)); 5148 } 5149 5150 // Mark const if we don't care about errno and that is the only 5151 // thing preventing the function from being const. This allows 5152 // IRgen to use LLVM intrinsics for such functions. 5153 if (!getLangOptions().MathErrno && 5154 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 5155 if (!FD->getAttr<ConstAttr>()) 5156 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 5157 } 5158 5159 if (Context.BuiltinInfo.isNoReturn(BuiltinID)) 5160 FD->setType(Context.getNoReturnType(FD->getType())); 5161 if (Context.BuiltinInfo.isNoThrow(BuiltinID)) 5162 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 5163 if (Context.BuiltinInfo.isConst(BuiltinID)) 5164 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 5165 } 5166 5167 IdentifierInfo *Name = FD->getIdentifier(); 5168 if (!Name) 5169 return; 5170 if ((!getLangOptions().CPlusPlus && 5171 FD->getDeclContext()->isTranslationUnit()) || 5172 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 5173 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 5174 LinkageSpecDecl::lang_c)) { 5175 // Okay: this could be a libc/libm/Objective-C function we know 5176 // about. 5177 } else 5178 return; 5179 5180 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 5181 // FIXME: NSLog and NSLogv should be target specific 5182 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 5183 // FIXME: We known better than our headers. 5184 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 5185 } else 5186 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 5187 "printf", 1, 5188 Name->isStr("NSLogv") ? 0 : 2)); 5189 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 5190 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 5191 // target-specific builtins, perhaps? 5192 if (!FD->getAttr<FormatAttr>()) 5193 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 5194 "printf", 2, 5195 Name->isStr("vasprintf") ? 0 : 3)); 5196 } 5197} 5198 5199TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 5200 TypeSourceInfo *TInfo) { 5201 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 5202 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 5203 5204 if (!TInfo) { 5205 assert(D.isInvalidType() && "no declarator info for valid type"); 5206 TInfo = Context.getTrivialTypeSourceInfo(T); 5207 } 5208 5209 // Scope manipulation handled by caller. 5210 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 5211 D.getIdentifierLoc(), 5212 D.getIdentifier(), 5213 TInfo); 5214 5215 if (const TagType *TT = T->getAs<TagType>()) { 5216 TagDecl *TD = TT->getDecl(); 5217 5218 // If the TagDecl that the TypedefDecl points to is an anonymous decl 5219 // keep track of the TypedefDecl. 5220 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 5221 TD->setTypedefForAnonDecl(NewTD); 5222 } 5223 5224 if (D.isInvalidType()) 5225 NewTD->setInvalidDecl(); 5226 return NewTD; 5227} 5228 5229 5230/// \brief Determine whether a tag with a given kind is acceptable 5231/// as a redeclaration of the given tag declaration. 5232/// 5233/// \returns true if the new tag kind is acceptable, false otherwise. 5234bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 5235 TagTypeKind NewTag, 5236 SourceLocation NewTagLoc, 5237 const IdentifierInfo &Name) { 5238 // C++ [dcl.type.elab]p3: 5239 // The class-key or enum keyword present in the 5240 // elaborated-type-specifier shall agree in kind with the 5241 // declaration to which the name in the elaborated-type-specifier 5242 // refers. This rule also applies to the form of 5243 // elaborated-type-specifier that declares a class-name or 5244 // friend class since it can be construed as referring to the 5245 // definition of the class. Thus, in any 5246 // elaborated-type-specifier, the enum keyword shall be used to 5247 // refer to an enumeration (7.2), the union class-key shall be 5248 // used to refer to a union (clause 9), and either the class or 5249 // struct class-key shall be used to refer to a class (clause 9) 5250 // declared using the class or struct class-key. 5251 TagTypeKind OldTag = Previous->getTagKind(); 5252 if (OldTag == NewTag) 5253 return true; 5254 5255 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 5256 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 5257 // Warn about the struct/class tag mismatch. 5258 bool isTemplate = false; 5259 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 5260 isTemplate = Record->getDescribedClassTemplate(); 5261 5262 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 5263 << (NewTag == TTK_Class) 5264 << isTemplate << &Name 5265 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 5266 OldTag == TTK_Class? "class" : "struct"); 5267 Diag(Previous->getLocation(), diag::note_previous_use); 5268 return true; 5269 } 5270 return false; 5271} 5272 5273/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 5274/// former case, Name will be non-null. In the later case, Name will be null. 5275/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 5276/// reference/declaration/definition of a tag. 5277Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 5278 SourceLocation KWLoc, CXXScopeSpec &SS, 5279 IdentifierInfo *Name, SourceLocation NameLoc, 5280 AttributeList *Attr, AccessSpecifier AS, 5281 MultiTemplateParamsArg TemplateParameterLists, 5282 bool &OwnedDecl, bool &IsDependent) { 5283 // If this is not a definition, it must have a name. 5284 assert((Name != 0 || TUK == TUK_Definition) && 5285 "Nameless record must be a definition!"); 5286 5287 OwnedDecl = false; 5288 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 5289 5290 // FIXME: Check explicit specializations more carefully. 5291 bool isExplicitSpecialization = false; 5292 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size(); 5293 bool Invalid = false; 5294 if (TUK != TUK_Reference) { 5295 if (TemplateParameterList *TemplateParams 5296 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS, 5297 (TemplateParameterList**)TemplateParameterLists.get(), 5298 TemplateParameterLists.size(), 5299 TUK == TUK_Friend, 5300 isExplicitSpecialization, 5301 Invalid)) { 5302 // All but one template parameter lists have been matching. 5303 --NumMatchedTemplateParamLists; 5304 5305 if (TemplateParams->size() > 0) { 5306 // This is a declaration or definition of a class template (which may 5307 // be a member of another template). 5308 if (Invalid) 5309 return 0; 5310 5311 OwnedDecl = false; 5312 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 5313 SS, Name, NameLoc, Attr, 5314 TemplateParams, 5315 AS); 5316 TemplateParameterLists.release(); 5317 return Result.get(); 5318 } else { 5319 // The "template<>" header is extraneous. 5320 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 5321 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 5322 isExplicitSpecialization = true; 5323 } 5324 } 5325 } 5326 5327 DeclContext *SearchDC = CurContext; 5328 DeclContext *DC = CurContext; 5329 bool isStdBadAlloc = false; 5330 5331 RedeclarationKind Redecl = ForRedeclaration; 5332 if (TUK == TUK_Friend || TUK == TUK_Reference) 5333 Redecl = NotForRedeclaration; 5334 5335 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 5336 5337 if (Name && SS.isNotEmpty()) { 5338 // We have a nested-name tag ('struct foo::bar'). 5339 5340 // Check for invalid 'foo::'. 5341 if (SS.isInvalid()) { 5342 Name = 0; 5343 goto CreateNewDecl; 5344 } 5345 5346 // If this is a friend or a reference to a class in a dependent 5347 // context, don't try to make a decl for it. 5348 if (TUK == TUK_Friend || TUK == TUK_Reference) { 5349 DC = computeDeclContext(SS, false); 5350 if (!DC) { 5351 IsDependent = true; 5352 return 0; 5353 } 5354 } else { 5355 DC = computeDeclContext(SS, true); 5356 if (!DC) { 5357 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 5358 << SS.getRange(); 5359 return 0; 5360 } 5361 } 5362 5363 if (RequireCompleteDeclContext(SS, DC)) 5364 return 0; 5365 5366 SearchDC = DC; 5367 // Look-up name inside 'foo::'. 5368 LookupQualifiedName(Previous, DC); 5369 5370 if (Previous.isAmbiguous()) 5371 return 0; 5372 5373 if (Previous.empty()) { 5374 // Name lookup did not find anything. However, if the 5375 // nested-name-specifier refers to the current instantiation, 5376 // and that current instantiation has any dependent base 5377 // classes, we might find something at instantiation time: treat 5378 // this as a dependent elaborated-type-specifier. 5379 if (Previous.wasNotFoundInCurrentInstantiation()) { 5380 IsDependent = true; 5381 return 0; 5382 } 5383 5384 // A tag 'foo::bar' must already exist. 5385 Diag(NameLoc, diag::err_not_tag_in_scope) 5386 << Kind << Name << DC << SS.getRange(); 5387 Name = 0; 5388 Invalid = true; 5389 goto CreateNewDecl; 5390 } 5391 } else if (Name) { 5392 // If this is a named struct, check to see if there was a previous forward 5393 // declaration or definition. 5394 // FIXME: We're looking into outer scopes here, even when we 5395 // shouldn't be. Doing so can result in ambiguities that we 5396 // shouldn't be diagnosing. 5397 LookupName(Previous, S); 5398 5399 // Note: there used to be some attempt at recovery here. 5400 if (Previous.isAmbiguous()) 5401 return 0; 5402 5403 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 5404 // FIXME: This makes sure that we ignore the contexts associated 5405 // with C structs, unions, and enums when looking for a matching 5406 // tag declaration or definition. See the similar lookup tweak 5407 // in Sema::LookupName; is there a better way to deal with this? 5408 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 5409 SearchDC = SearchDC->getParent(); 5410 } 5411 } 5412 5413 if (Previous.isSingleResult() && 5414 Previous.getFoundDecl()->isTemplateParameter()) { 5415 // Maybe we will complain about the shadowed template parameter. 5416 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 5417 // Just pretend that we didn't see the previous declaration. 5418 Previous.clear(); 5419 } 5420 5421 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 5422 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 5423 // This is a declaration of or a reference to "std::bad_alloc". 5424 isStdBadAlloc = true; 5425 5426 if (Previous.empty() && StdBadAlloc) { 5427 // std::bad_alloc has been implicitly declared (but made invisible to 5428 // name lookup). Fill in this implicit declaration as the previous 5429 // declaration, so that the declarations get chained appropriately. 5430 Previous.addDecl(getStdBadAlloc()); 5431 } 5432 } 5433 5434 // If we didn't find a previous declaration, and this is a reference 5435 // (or friend reference), move to the correct scope. In C++, we 5436 // also need to do a redeclaration lookup there, just in case 5437 // there's a shadow friend decl. 5438 if (Name && Previous.empty() && 5439 (TUK == TUK_Reference || TUK == TUK_Friend)) { 5440 if (Invalid) goto CreateNewDecl; 5441 assert(SS.isEmpty()); 5442 5443 if (TUK == TUK_Reference) { 5444 // C++ [basic.scope.pdecl]p5: 5445 // -- for an elaborated-type-specifier of the form 5446 // 5447 // class-key identifier 5448 // 5449 // if the elaborated-type-specifier is used in the 5450 // decl-specifier-seq or parameter-declaration-clause of a 5451 // function defined in namespace scope, the identifier is 5452 // declared as a class-name in the namespace that contains 5453 // the declaration; otherwise, except as a friend 5454 // declaration, the identifier is declared in the smallest 5455 // non-class, non-function-prototype scope that contains the 5456 // declaration. 5457 // 5458 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 5459 // C structs and unions. 5460 // 5461 // It is an error in C++ to declare (rather than define) an enum 5462 // type, including via an elaborated type specifier. We'll 5463 // diagnose that later; for now, declare the enum in the same 5464 // scope as we would have picked for any other tag type. 5465 // 5466 // GNU C also supports this behavior as part of its incomplete 5467 // enum types extension, while GNU C++ does not. 5468 // 5469 // Find the context where we'll be declaring the tag. 5470 // FIXME: We would like to maintain the current DeclContext as the 5471 // lexical context, 5472 while (SearchDC->isRecord()) 5473 SearchDC = SearchDC->getParent(); 5474 5475 // Find the scope where we'll be declaring the tag. 5476 while (S->isClassScope() || 5477 (getLangOptions().CPlusPlus && 5478 S->isFunctionPrototypeScope()) || 5479 ((S->getFlags() & Scope::DeclScope) == 0) || 5480 (S->getEntity() && 5481 ((DeclContext *)S->getEntity())->isTransparentContext())) 5482 S = S->getParent(); 5483 } else { 5484 assert(TUK == TUK_Friend); 5485 // C++ [namespace.memdef]p3: 5486 // If a friend declaration in a non-local class first declares a 5487 // class or function, the friend class or function is a member of 5488 // the innermost enclosing namespace. 5489 SearchDC = SearchDC->getEnclosingNamespaceContext(); 5490 } 5491 5492 // In C++, we need to do a redeclaration lookup to properly 5493 // diagnose some problems. 5494 if (getLangOptions().CPlusPlus) { 5495 Previous.setRedeclarationKind(ForRedeclaration); 5496 LookupQualifiedName(Previous, SearchDC); 5497 } 5498 } 5499 5500 if (!Previous.empty()) { 5501 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 5502 5503 // It's okay to have a tag decl in the same scope as a typedef 5504 // which hides a tag decl in the same scope. Finding this 5505 // insanity with a redeclaration lookup can only actually happen 5506 // in C++. 5507 // 5508 // This is also okay for elaborated-type-specifiers, which is 5509 // technically forbidden by the current standard but which is 5510 // okay according to the likely resolution of an open issue; 5511 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 5512 if (getLangOptions().CPlusPlus) { 5513 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) { 5514 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 5515 TagDecl *Tag = TT->getDecl(); 5516 if (Tag->getDeclName() == Name && 5517 Tag->getDeclContext()->getLookupContext() 5518 ->Equals(TD->getDeclContext()->getLookupContext())) { 5519 PrevDecl = Tag; 5520 Previous.clear(); 5521 Previous.addDecl(Tag); 5522 } 5523 } 5524 } 5525 } 5526 5527 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 5528 // If this is a use of a previous tag, or if the tag is already declared 5529 // in the same scope (so that the definition/declaration completes or 5530 // rementions the tag), reuse the decl. 5531 if (TUK == TUK_Reference || TUK == TUK_Friend || 5532 isDeclInScope(PrevDecl, SearchDC, S)) { 5533 // Make sure that this wasn't declared as an enum and now used as a 5534 // struct or something similar. 5535 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) { 5536 bool SafeToContinue 5537 = (PrevTagDecl->getTagKind() != TTK_Enum && 5538 Kind != TTK_Enum); 5539 if (SafeToContinue) 5540 Diag(KWLoc, diag::err_use_with_wrong_tag) 5541 << Name 5542 << FixItHint::CreateReplacement(SourceRange(KWLoc), 5543 PrevTagDecl->getKindName()); 5544 else 5545 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 5546 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 5547 5548 if (SafeToContinue) 5549 Kind = PrevTagDecl->getTagKind(); 5550 else { 5551 // Recover by making this an anonymous redefinition. 5552 Name = 0; 5553 Previous.clear(); 5554 Invalid = true; 5555 } 5556 } 5557 5558 if (!Invalid) { 5559 // If this is a use, just return the declaration we found. 5560 5561 // FIXME: In the future, return a variant or some other clue 5562 // for the consumer of this Decl to know it doesn't own it. 5563 // For our current ASTs this shouldn't be a problem, but will 5564 // need to be changed with DeclGroups. 5565 if ((TUK == TUK_Reference && !PrevTagDecl->getFriendObjectKind()) || 5566 TUK == TUK_Friend) 5567 return PrevTagDecl; 5568 5569 // Diagnose attempts to redefine a tag. 5570 if (TUK == TUK_Definition) { 5571 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 5572 // If we're defining a specialization and the previous definition 5573 // is from an implicit instantiation, don't emit an error 5574 // here; we'll catch this in the general case below. 5575 if (!isExplicitSpecialization || 5576 !isa<CXXRecordDecl>(Def) || 5577 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 5578 == TSK_ExplicitSpecialization) { 5579 Diag(NameLoc, diag::err_redefinition) << Name; 5580 Diag(Def->getLocation(), diag::note_previous_definition); 5581 // If this is a redefinition, recover by making this 5582 // struct be anonymous, which will make any later 5583 // references get the previous definition. 5584 Name = 0; 5585 Previous.clear(); 5586 Invalid = true; 5587 } 5588 } else { 5589 // If the type is currently being defined, complain 5590 // about a nested redefinition. 5591 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 5592 if (Tag->isBeingDefined()) { 5593 Diag(NameLoc, diag::err_nested_redefinition) << Name; 5594 Diag(PrevTagDecl->getLocation(), 5595 diag::note_previous_definition); 5596 Name = 0; 5597 Previous.clear(); 5598 Invalid = true; 5599 } 5600 } 5601 5602 // Okay, this is definition of a previously declared or referenced 5603 // tag PrevDecl. We're going to create a new Decl for it. 5604 } 5605 } 5606 // If we get here we have (another) forward declaration or we 5607 // have a definition. Just create a new decl. 5608 5609 } else { 5610 // If we get here, this is a definition of a new tag type in a nested 5611 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 5612 // new decl/type. We set PrevDecl to NULL so that the entities 5613 // have distinct types. 5614 Previous.clear(); 5615 } 5616 // If we get here, we're going to create a new Decl. If PrevDecl 5617 // is non-NULL, it's a definition of the tag declared by 5618 // PrevDecl. If it's NULL, we have a new definition. 5619 5620 5621 // Otherwise, PrevDecl is not a tag, but was found with tag 5622 // lookup. This is only actually possible in C++, where a few 5623 // things like templates still live in the tag namespace. 5624 } else { 5625 assert(getLangOptions().CPlusPlus); 5626 5627 // Use a better diagnostic if an elaborated-type-specifier 5628 // found the wrong kind of type on the first 5629 // (non-redeclaration) lookup. 5630 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 5631 !Previous.isForRedeclaration()) { 5632 unsigned Kind = 0; 5633 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 5634 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2; 5635 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 5636 Diag(PrevDecl->getLocation(), diag::note_declared_at); 5637 Invalid = true; 5638 5639 // Otherwise, only diagnose if the declaration is in scope. 5640 } else if (!isDeclInScope(PrevDecl, SearchDC, S)) { 5641 // do nothing 5642 5643 // Diagnose implicit declarations introduced by elaborated types. 5644 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 5645 unsigned Kind = 0; 5646 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 5647 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2; 5648 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 5649 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 5650 Invalid = true; 5651 5652 // Otherwise it's a declaration. Call out a particularly common 5653 // case here. 5654 } else if (isa<TypedefDecl>(PrevDecl)) { 5655 Diag(NameLoc, diag::err_tag_definition_of_typedef) 5656 << Name 5657 << cast<TypedefDecl>(PrevDecl)->getUnderlyingType(); 5658 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 5659 Invalid = true; 5660 5661 // Otherwise, diagnose. 5662 } else { 5663 // The tag name clashes with something else in the target scope, 5664 // issue an error and recover by making this tag be anonymous. 5665 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 5666 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5667 Name = 0; 5668 Invalid = true; 5669 } 5670 5671 // The existing declaration isn't relevant to us; we're in a 5672 // new scope, so clear out the previous declaration. 5673 Previous.clear(); 5674 } 5675 } 5676 5677CreateNewDecl: 5678 5679 TagDecl *PrevDecl = 0; 5680 if (Previous.isSingleResult()) 5681 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 5682 5683 // If there is an identifier, use the location of the identifier as the 5684 // location of the decl, otherwise use the location of the struct/union 5685 // keyword. 5686 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 5687 5688 // Otherwise, create a new declaration. If there is a previous 5689 // declaration of the same entity, the two will be linked via 5690 // PrevDecl. 5691 TagDecl *New; 5692 5693 if (Kind == TTK_Enum) { 5694 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 5695 // enum X { A, B, C } D; D should chain to X. 5696 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc, 5697 cast_or_null<EnumDecl>(PrevDecl)); 5698 // If this is an undefined enum, warn. 5699 if (TUK != TUK_Definition && !Invalid) { 5700 TagDecl *Def; 5701 if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 5702 Diag(Loc, diag::ext_forward_ref_enum_def) 5703 << New; 5704 Diag(Def->getLocation(), diag::note_previous_definition); 5705 } else { 5706 Diag(Loc, 5707 getLangOptions().CPlusPlus? diag::err_forward_ref_enum 5708 : diag::ext_forward_ref_enum); 5709 } 5710 } 5711 } else { 5712 // struct/union/class 5713 5714 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 5715 // struct X { int A; } D; D should chain to X. 5716 if (getLangOptions().CPlusPlus) { 5717 // FIXME: Look for a way to use RecordDecl for simple structs. 5718 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 5719 cast_or_null<CXXRecordDecl>(PrevDecl)); 5720 5721 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 5722 StdBadAlloc = cast<CXXRecordDecl>(New); 5723 } else 5724 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 5725 cast_or_null<RecordDecl>(PrevDecl)); 5726 } 5727 5728 // Maybe add qualifier info. 5729 if (SS.isNotEmpty()) { 5730 if (SS.isSet()) { 5731 NestedNameSpecifier *NNS 5732 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 5733 New->setQualifierInfo(NNS, SS.getRange()); 5734 if (NumMatchedTemplateParamLists > 0) { 5735 New->setTemplateParameterListsInfo(Context, 5736 NumMatchedTemplateParamLists, 5737 (TemplateParameterList**) TemplateParameterLists.release()); 5738 } 5739 } 5740 else 5741 Invalid = true; 5742 } 5743 5744 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 5745 // Add alignment attributes if necessary; these attributes are checked when 5746 // the ASTContext lays out the structure. 5747 // 5748 // It is important for implementing the correct semantics that this 5749 // happen here (in act on tag decl). The #pragma pack stack is 5750 // maintained as a result of parser callbacks which can occur at 5751 // many points during the parsing of a struct declaration (because 5752 // the #pragma tokens are effectively skipped over during the 5753 // parsing of the struct). 5754 AddAlignmentAttributesForRecord(RD); 5755 } 5756 5757 // If this is a specialization of a member class (of a class template), 5758 // check the specialization. 5759 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 5760 Invalid = true; 5761 5762 if (Invalid) 5763 New->setInvalidDecl(); 5764 5765 if (Attr) 5766 ProcessDeclAttributeList(S, New, Attr); 5767 5768 // If we're declaring or defining a tag in function prototype scope 5769 // in C, note that this type can only be used within the function. 5770 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 5771 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 5772 5773 // Set the lexical context. If the tag has a C++ scope specifier, the 5774 // lexical context will be different from the semantic context. 5775 New->setLexicalDeclContext(CurContext); 5776 5777 // Mark this as a friend decl if applicable. 5778 if (TUK == TUK_Friend) 5779 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty()); 5780 5781 // Set the access specifier. 5782 if (!Invalid && SearchDC->isRecord()) 5783 SetMemberAccessSpecifier(New, PrevDecl, AS); 5784 5785 if (TUK == TUK_Definition) 5786 New->startDefinition(); 5787 5788 // If this has an identifier, add it to the scope stack. 5789 if (TUK == TUK_Friend) { 5790 // We might be replacing an existing declaration in the lookup tables; 5791 // if so, borrow its access specifier. 5792 if (PrevDecl) 5793 New->setAccess(PrevDecl->getAccess()); 5794 5795 DeclContext *DC = New->getDeclContext()->getLookupContext(); 5796 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 5797 if (Name) // can be null along some error paths 5798 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5799 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 5800 } else if (Name) { 5801 S = getNonFieldDeclScope(S); 5802 PushOnScopeChains(New, S); 5803 } else { 5804 CurContext->addDecl(New); 5805 } 5806 5807 // If this is the C FILE type, notify the AST context. 5808 if (IdentifierInfo *II = New->getIdentifier()) 5809 if (!New->isInvalidDecl() && 5810 New->getDeclContext()->getLookupContext()->isTranslationUnit() && 5811 II->isStr("FILE")) 5812 Context.setFILEDecl(New); 5813 5814 OwnedDecl = true; 5815 return New; 5816} 5817 5818void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 5819 AdjustDeclIfTemplate(TagD); 5820 TagDecl *Tag = cast<TagDecl>(TagD); 5821 5822 // Enter the tag context. 5823 PushDeclContext(S, Tag); 5824} 5825 5826void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 5827 SourceLocation LBraceLoc) { 5828 AdjustDeclIfTemplate(TagD); 5829 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 5830 5831 FieldCollector->StartClass(); 5832 5833 if (!Record->getIdentifier()) 5834 return; 5835 5836 // C++ [class]p2: 5837 // [...] The class-name is also inserted into the scope of the 5838 // class itself; this is known as the injected-class-name. For 5839 // purposes of access checking, the injected-class-name is treated 5840 // as if it were a public member name. 5841 CXXRecordDecl *InjectedClassName 5842 = CXXRecordDecl::Create(Context, Record->getTagKind(), 5843 CurContext, Record->getLocation(), 5844 Record->getIdentifier(), 5845 Record->getTagKeywordLoc(), 5846 Record); 5847 InjectedClassName->setImplicit(); 5848 InjectedClassName->setAccess(AS_public); 5849 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 5850 InjectedClassName->setDescribedClassTemplate(Template); 5851 PushOnScopeChains(InjectedClassName, S); 5852 assert(InjectedClassName->isInjectedClassName() && 5853 "Broken injected-class-name"); 5854} 5855 5856void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 5857 SourceLocation RBraceLoc) { 5858 AdjustDeclIfTemplate(TagD); 5859 TagDecl *Tag = cast<TagDecl>(TagD); 5860 Tag->setRBraceLoc(RBraceLoc); 5861 5862 if (isa<CXXRecordDecl>(Tag)) 5863 FieldCollector->FinishClass(); 5864 5865 // Exit this scope of this tag's definition. 5866 PopDeclContext(); 5867 5868 // Notify the consumer that we've defined a tag. 5869 Consumer.HandleTagDeclDefinition(Tag); 5870} 5871 5872void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 5873 AdjustDeclIfTemplate(TagD); 5874 TagDecl *Tag = cast<TagDecl>(TagD); 5875 Tag->setInvalidDecl(); 5876 5877 // We're undoing ActOnTagStartDefinition here, not 5878 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 5879 // the FieldCollector. 5880 5881 PopDeclContext(); 5882} 5883 5884// Note that FieldName may be null for anonymous bitfields. 5885bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 5886 QualType FieldTy, const Expr *BitWidth, 5887 bool *ZeroWidth) { 5888 // Default to true; that shouldn't confuse checks for emptiness 5889 if (ZeroWidth) 5890 *ZeroWidth = true; 5891 5892 // C99 6.7.2.1p4 - verify the field type. 5893 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 5894 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 5895 // Handle incomplete types with specific error. 5896 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 5897 return true; 5898 if (FieldName) 5899 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 5900 << FieldName << FieldTy << BitWidth->getSourceRange(); 5901 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 5902 << FieldTy << BitWidth->getSourceRange(); 5903 } 5904 5905 // If the bit-width is type- or value-dependent, don't try to check 5906 // it now. 5907 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 5908 return false; 5909 5910 llvm::APSInt Value; 5911 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 5912 return true; 5913 5914 if (Value != 0 && ZeroWidth) 5915 *ZeroWidth = false; 5916 5917 // Zero-width bitfield is ok for anonymous field. 5918 if (Value == 0 && FieldName) 5919 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 5920 5921 if (Value.isSigned() && Value.isNegative()) { 5922 if (FieldName) 5923 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 5924 << FieldName << Value.toString(10); 5925 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 5926 << Value.toString(10); 5927 } 5928 5929 if (!FieldTy->isDependentType()) { 5930 uint64_t TypeSize = Context.getTypeSize(FieldTy); 5931 if (Value.getZExtValue() > TypeSize) { 5932 if (!getLangOptions().CPlusPlus) { 5933 if (FieldName) 5934 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 5935 << FieldName << (unsigned)Value.getZExtValue() 5936 << (unsigned)TypeSize; 5937 5938 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 5939 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 5940 } 5941 5942 if (FieldName) 5943 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 5944 << FieldName << (unsigned)Value.getZExtValue() 5945 << (unsigned)TypeSize; 5946 else 5947 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 5948 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 5949 } 5950 } 5951 5952 return false; 5953} 5954 5955/// ActOnField - Each field of a struct/union/class is passed into this in order 5956/// to create a FieldDecl object for it. 5957Decl *Sema::ActOnField(Scope *S, Decl *TagD, 5958 SourceLocation DeclStart, 5959 Declarator &D, ExprTy *BitfieldWidth) { 5960 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 5961 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 5962 AS_public); 5963 return Res; 5964} 5965 5966/// HandleField - Analyze a field of a C struct or a C++ data member. 5967/// 5968FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 5969 SourceLocation DeclStart, 5970 Declarator &D, Expr *BitWidth, 5971 AccessSpecifier AS) { 5972 IdentifierInfo *II = D.getIdentifier(); 5973 SourceLocation Loc = DeclStart; 5974 if (II) Loc = D.getIdentifierLoc(); 5975 5976 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5977 QualType T = TInfo->getType(); 5978 if (getLangOptions().CPlusPlus) 5979 CheckExtraCXXDefaultArguments(D); 5980 5981 DiagnoseFunctionSpecifiers(D); 5982 5983 if (D.getDeclSpec().isThreadSpecified()) 5984 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5985 5986 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 5987 ForRedeclaration); 5988 5989 if (PrevDecl && PrevDecl->isTemplateParameter()) { 5990 // Maybe we will complain about the shadowed template parameter. 5991 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5992 // Just pretend that we didn't see the previous declaration. 5993 PrevDecl = 0; 5994 } 5995 5996 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 5997 PrevDecl = 0; 5998 5999 bool Mutable 6000 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 6001 SourceLocation TSSL = D.getSourceRange().getBegin(); 6002 FieldDecl *NewFD 6003 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL, 6004 AS, PrevDecl, &D); 6005 6006 if (NewFD->isInvalidDecl()) 6007 Record->setInvalidDecl(); 6008 6009 if (NewFD->isInvalidDecl() && PrevDecl) { 6010 // Don't introduce NewFD into scope; there's already something 6011 // with the same name in the same scope. 6012 } else if (II) { 6013 PushOnScopeChains(NewFD, S); 6014 } else 6015 Record->addDecl(NewFD); 6016 6017 return NewFD; 6018} 6019 6020/// \brief Build a new FieldDecl and check its well-formedness. 6021/// 6022/// This routine builds a new FieldDecl given the fields name, type, 6023/// record, etc. \p PrevDecl should refer to any previous declaration 6024/// with the same name and in the same scope as the field to be 6025/// created. 6026/// 6027/// \returns a new FieldDecl. 6028/// 6029/// \todo The Declarator argument is a hack. It will be removed once 6030FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 6031 TypeSourceInfo *TInfo, 6032 RecordDecl *Record, SourceLocation Loc, 6033 bool Mutable, Expr *BitWidth, 6034 SourceLocation TSSL, 6035 AccessSpecifier AS, NamedDecl *PrevDecl, 6036 Declarator *D) { 6037 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6038 bool InvalidDecl = false; 6039 if (D) InvalidDecl = D->isInvalidType(); 6040 6041 // If we receive a broken type, recover by assuming 'int' and 6042 // marking this declaration as invalid. 6043 if (T.isNull()) { 6044 InvalidDecl = true; 6045 T = Context.IntTy; 6046 } 6047 6048 QualType EltTy = Context.getBaseElementType(T); 6049 if (!EltTy->isDependentType() && 6050 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 6051 // Fields of incomplete type force their record to be invalid. 6052 Record->setInvalidDecl(); 6053 InvalidDecl = true; 6054 } 6055 6056 // C99 6.7.2.1p8: A member of a structure or union may have any type other 6057 // than a variably modified type. 6058 if (!InvalidDecl && T->isVariablyModifiedType()) { 6059 bool SizeIsNegative; 6060 llvm::APSInt Oversized; 6061 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 6062 SizeIsNegative, 6063 Oversized); 6064 if (!FixedTy.isNull()) { 6065 Diag(Loc, diag::warn_illegal_constant_array_size); 6066 T = FixedTy; 6067 } else { 6068 if (SizeIsNegative) 6069 Diag(Loc, diag::err_typecheck_negative_array_size); 6070 else if (Oversized.getBoolValue()) 6071 Diag(Loc, diag::err_array_too_large) 6072 << Oversized.toString(10); 6073 else 6074 Diag(Loc, diag::err_typecheck_field_variable_size); 6075 InvalidDecl = true; 6076 } 6077 } 6078 6079 // Fields can not have abstract class types 6080 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 6081 diag::err_abstract_type_in_decl, 6082 AbstractFieldType)) 6083 InvalidDecl = true; 6084 6085 bool ZeroWidth = false; 6086 // If this is declared as a bit-field, check the bit-field. 6087 if (!InvalidDecl && BitWidth && 6088 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 6089 InvalidDecl = true; 6090 DeleteExpr(BitWidth); 6091 BitWidth = 0; 6092 ZeroWidth = false; 6093 } 6094 6095 // Check that 'mutable' is consistent with the type of the declaration. 6096 if (!InvalidDecl && Mutable) { 6097 unsigned DiagID = 0; 6098 if (T->isReferenceType()) 6099 DiagID = diag::err_mutable_reference; 6100 else if (T.isConstQualified()) 6101 DiagID = diag::err_mutable_const; 6102 6103 if (DiagID) { 6104 SourceLocation ErrLoc = Loc; 6105 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 6106 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 6107 Diag(ErrLoc, DiagID); 6108 Mutable = false; 6109 InvalidDecl = true; 6110 } 6111 } 6112 6113 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo, 6114 BitWidth, Mutable); 6115 if (InvalidDecl) 6116 NewFD->setInvalidDecl(); 6117 6118 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 6119 Diag(Loc, diag::err_duplicate_member) << II; 6120 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6121 NewFD->setInvalidDecl(); 6122 } 6123 6124 if (!InvalidDecl && getLangOptions().CPlusPlus) { 6125 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record); 6126 6127 if (!T->isPODType()) 6128 CXXRecord->setPOD(false); 6129 if (!ZeroWidth) 6130 CXXRecord->setEmpty(false); 6131 6132 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 6133 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 6134 if (RDecl->getDefinition()) { 6135 if (!RDecl->hasTrivialConstructor()) 6136 CXXRecord->setHasTrivialConstructor(false); 6137 if (!RDecl->hasTrivialCopyConstructor()) 6138 CXXRecord->setHasTrivialCopyConstructor(false); 6139 if (!RDecl->hasTrivialCopyAssignment()) 6140 CXXRecord->setHasTrivialCopyAssignment(false); 6141 if (!RDecl->hasTrivialDestructor()) 6142 CXXRecord->setHasTrivialDestructor(false); 6143 6144 // C++ 9.5p1: An object of a class with a non-trivial 6145 // constructor, a non-trivial copy constructor, a non-trivial 6146 // destructor, or a non-trivial copy assignment operator 6147 // cannot be a member of a union, nor can an array of such 6148 // objects. 6149 // TODO: C++0x alters this restriction significantly. 6150 if (Record->isUnion() && CheckNontrivialField(NewFD)) 6151 NewFD->setInvalidDecl(); 6152 } 6153 } 6154 } 6155 6156 // FIXME: We need to pass in the attributes given an AST 6157 // representation, not a parser representation. 6158 if (D) 6159 // FIXME: What to pass instead of TUScope? 6160 ProcessDeclAttributes(TUScope, NewFD, *D); 6161 6162 if (T.isObjCGCWeak()) 6163 Diag(Loc, diag::warn_attribute_weak_on_field); 6164 6165 NewFD->setAccess(AS); 6166 6167 // C++ [dcl.init.aggr]p1: 6168 // An aggregate is an array or a class (clause 9) with [...] no 6169 // private or protected non-static data members (clause 11). 6170 // A POD must be an aggregate. 6171 if (getLangOptions().CPlusPlus && 6172 (AS == AS_private || AS == AS_protected)) { 6173 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 6174 CXXRecord->setAggregate(false); 6175 CXXRecord->setPOD(false); 6176 } 6177 6178 return NewFD; 6179} 6180 6181bool Sema::CheckNontrivialField(FieldDecl *FD) { 6182 assert(FD); 6183 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 6184 6185 if (FD->isInvalidDecl()) 6186 return true; 6187 6188 QualType EltTy = Context.getBaseElementType(FD->getType()); 6189 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 6190 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 6191 if (RDecl->getDefinition()) { 6192 // We check for copy constructors before constructors 6193 // because otherwise we'll never get complaints about 6194 // copy constructors. 6195 6196 CXXSpecialMember member = CXXInvalid; 6197 if (!RDecl->hasTrivialCopyConstructor()) 6198 member = CXXCopyConstructor; 6199 else if (!RDecl->hasTrivialConstructor()) 6200 member = CXXConstructor; 6201 else if (!RDecl->hasTrivialCopyAssignment()) 6202 member = CXXCopyAssignment; 6203 else if (!RDecl->hasTrivialDestructor()) 6204 member = CXXDestructor; 6205 6206 if (member != CXXInvalid) { 6207 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member) 6208 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 6209 DiagnoseNontrivial(RT, member); 6210 return true; 6211 } 6212 } 6213 } 6214 6215 return false; 6216} 6217 6218/// DiagnoseNontrivial - Given that a class has a non-trivial 6219/// special member, figure out why. 6220void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 6221 QualType QT(T, 0U); 6222 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 6223 6224 // Check whether the member was user-declared. 6225 switch (member) { 6226 case CXXInvalid: 6227 break; 6228 6229 case CXXConstructor: 6230 if (RD->hasUserDeclaredConstructor()) { 6231 typedef CXXRecordDecl::ctor_iterator ctor_iter; 6232 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 6233 const FunctionDecl *body = 0; 6234 ci->hasBody(body); 6235 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 6236 SourceLocation CtorLoc = ci->getLocation(); 6237 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 6238 return; 6239 } 6240 } 6241 6242 assert(0 && "found no user-declared constructors"); 6243 return; 6244 } 6245 break; 6246 6247 case CXXCopyConstructor: 6248 if (RD->hasUserDeclaredCopyConstructor()) { 6249 SourceLocation CtorLoc = 6250 RD->getCopyConstructor(Context, 0)->getLocation(); 6251 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 6252 return; 6253 } 6254 break; 6255 6256 case CXXCopyAssignment: 6257 if (RD->hasUserDeclaredCopyAssignment()) { 6258 // FIXME: this should use the location of the copy 6259 // assignment, not the type. 6260 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 6261 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 6262 return; 6263 } 6264 break; 6265 6266 case CXXDestructor: 6267 if (RD->hasUserDeclaredDestructor()) { 6268 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 6269 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 6270 return; 6271 } 6272 break; 6273 } 6274 6275 typedef CXXRecordDecl::base_class_iterator base_iter; 6276 6277 // Virtual bases and members inhibit trivial copying/construction, 6278 // but not trivial destruction. 6279 if (member != CXXDestructor) { 6280 // Check for virtual bases. vbases includes indirect virtual bases, 6281 // so we just iterate through the direct bases. 6282 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 6283 if (bi->isVirtual()) { 6284 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 6285 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 6286 return; 6287 } 6288 6289 // Check for virtual methods. 6290 typedef CXXRecordDecl::method_iterator meth_iter; 6291 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 6292 ++mi) { 6293 if (mi->isVirtual()) { 6294 SourceLocation MLoc = mi->getSourceRange().getBegin(); 6295 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 6296 return; 6297 } 6298 } 6299 } 6300 6301 bool (CXXRecordDecl::*hasTrivial)() const; 6302 switch (member) { 6303 case CXXConstructor: 6304 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break; 6305 case CXXCopyConstructor: 6306 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 6307 case CXXCopyAssignment: 6308 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 6309 case CXXDestructor: 6310 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 6311 default: 6312 assert(0 && "unexpected special member"); return; 6313 } 6314 6315 // Check for nontrivial bases (and recurse). 6316 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 6317 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 6318 assert(BaseRT && "Don't know how to handle dependent bases"); 6319 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 6320 if (!(BaseRecTy->*hasTrivial)()) { 6321 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 6322 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 6323 DiagnoseNontrivial(BaseRT, member); 6324 return; 6325 } 6326 } 6327 6328 // Check for nontrivial members (and recurse). 6329 typedef RecordDecl::field_iterator field_iter; 6330 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 6331 ++fi) { 6332 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 6333 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 6334 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 6335 6336 if (!(EltRD->*hasTrivial)()) { 6337 SourceLocation FLoc = (*fi)->getLocation(); 6338 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 6339 DiagnoseNontrivial(EltRT, member); 6340 return; 6341 } 6342 } 6343 } 6344 6345 assert(0 && "found no explanation for non-trivial member"); 6346} 6347 6348/// TranslateIvarVisibility - Translate visibility from a token ID to an 6349/// AST enum value. 6350static ObjCIvarDecl::AccessControl 6351TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 6352 switch (ivarVisibility) { 6353 default: assert(0 && "Unknown visitibility kind"); 6354 case tok::objc_private: return ObjCIvarDecl::Private; 6355 case tok::objc_public: return ObjCIvarDecl::Public; 6356 case tok::objc_protected: return ObjCIvarDecl::Protected; 6357 case tok::objc_package: return ObjCIvarDecl::Package; 6358 } 6359} 6360 6361/// ActOnIvar - Each ivar field of an objective-c class is passed into this 6362/// in order to create an IvarDecl object for it. 6363Decl *Sema::ActOnIvar(Scope *S, 6364 SourceLocation DeclStart, 6365 Decl *IntfDecl, 6366 Declarator &D, ExprTy *BitfieldWidth, 6367 tok::ObjCKeywordKind Visibility) { 6368 6369 IdentifierInfo *II = D.getIdentifier(); 6370 Expr *BitWidth = (Expr*)BitfieldWidth; 6371 SourceLocation Loc = DeclStart; 6372 if (II) Loc = D.getIdentifierLoc(); 6373 6374 // FIXME: Unnamed fields can be handled in various different ways, for 6375 // example, unnamed unions inject all members into the struct namespace! 6376 6377 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6378 QualType T = TInfo->getType(); 6379 6380 if (BitWidth) { 6381 // 6.7.2.1p3, 6.7.2.1p4 6382 if (VerifyBitField(Loc, II, T, BitWidth)) { 6383 D.setInvalidType(); 6384 DeleteExpr(BitWidth); 6385 BitWidth = 0; 6386 } 6387 } else { 6388 // Not a bitfield. 6389 6390 // validate II. 6391 6392 } 6393 if (T->isReferenceType()) { 6394 Diag(Loc, diag::err_ivar_reference_type); 6395 D.setInvalidType(); 6396 } 6397 // C99 6.7.2.1p8: A member of a structure or union may have any type other 6398 // than a variably modified type. 6399 else if (T->isVariablyModifiedType()) { 6400 Diag(Loc, diag::err_typecheck_ivar_variable_size); 6401 D.setInvalidType(); 6402 } 6403 6404 // Get the visibility (access control) for this ivar. 6405 ObjCIvarDecl::AccessControl ac = 6406 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 6407 : ObjCIvarDecl::None; 6408 // Must set ivar's DeclContext to its enclosing interface. 6409 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl); 6410 ObjCContainerDecl *EnclosingContext; 6411 if (ObjCImplementationDecl *IMPDecl = 6412 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 6413 if (!LangOpts.ObjCNonFragileABI2) { 6414 // Case of ivar declared in an implementation. Context is that of its class. 6415 EnclosingContext = IMPDecl->getClassInterface(); 6416 assert(EnclosingContext && "Implementation has no class interface!"); 6417 } 6418 else 6419 EnclosingContext = EnclosingDecl; 6420 } else { 6421 if (ObjCCategoryDecl *CDecl = 6422 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 6423 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 6424 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 6425 return 0; 6426 } 6427 } 6428 EnclosingContext = EnclosingDecl; 6429 } 6430 6431 // Construct the decl. 6432 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, 6433 EnclosingContext, Loc, II, T, 6434 TInfo, ac, (Expr *)BitfieldWidth); 6435 6436 if (II) { 6437 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 6438 ForRedeclaration); 6439 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 6440 && !isa<TagDecl>(PrevDecl)) { 6441 Diag(Loc, diag::err_duplicate_member) << II; 6442 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6443 NewID->setInvalidDecl(); 6444 } 6445 } 6446 6447 // Process attributes attached to the ivar. 6448 ProcessDeclAttributes(S, NewID, D); 6449 6450 if (D.isInvalidType()) 6451 NewID->setInvalidDecl(); 6452 6453 if (II) { 6454 // FIXME: When interfaces are DeclContexts, we'll need to add 6455 // these to the interface. 6456 S->AddDecl(NewID); 6457 IdResolver.AddDecl(NewID); 6458 } 6459 6460 return NewID; 6461} 6462 6463/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 6464/// class and class extensions. For every class @interface and class 6465/// extension @interface, if the last ivar is a bitfield of any type, 6466/// then add an implicit `char :0` ivar to the end of that interface. 6467void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl, 6468 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) { 6469 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 6470 return; 6471 6472 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 6473 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 6474 6475 if (!Ivar->isBitField()) 6476 return; 6477 uint64_t BitFieldSize = 6478 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue(); 6479 if (BitFieldSize == 0) 6480 return; 6481 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl); 6482 if (!ID) { 6483 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 6484 if (!CD->IsClassExtension()) 6485 return; 6486 } 6487 // No need to add this to end of @implementation. 6488 else 6489 return; 6490 } 6491 // All conditions are met. Add a new bitfield to the tail end of ivars. 6492 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0); 6493 Expr * BW = 6494 new (Context) IntegerLiteral(Zero, Context.CharTy, DeclLoc); 6495 6496 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl), 6497 DeclLoc, 0, 6498 Context.CharTy, 6499 Context.CreateTypeSourceInfo(Context.CharTy), 6500 ObjCIvarDecl::Private, BW, 6501 true); 6502 AllIvarDecls.push_back(Ivar); 6503} 6504 6505void Sema::ActOnFields(Scope* S, 6506 SourceLocation RecLoc, Decl *EnclosingDecl, 6507 Decl **Fields, unsigned NumFields, 6508 SourceLocation LBrac, SourceLocation RBrac, 6509 AttributeList *Attr) { 6510 assert(EnclosingDecl && "missing record or interface decl"); 6511 6512 // If the decl this is being inserted into is invalid, then it may be a 6513 // redeclaration or some other bogus case. Don't try to add fields to it. 6514 if (EnclosingDecl->isInvalidDecl()) { 6515 // FIXME: Deallocate fields? 6516 return; 6517 } 6518 6519 6520 // Verify that all the fields are okay. 6521 unsigned NumNamedMembers = 0; 6522 llvm::SmallVector<FieldDecl*, 32> RecFields; 6523 6524 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 6525 for (unsigned i = 0; i != NumFields; ++i) { 6526 FieldDecl *FD = cast<FieldDecl>(Fields[i]); 6527 6528 // Get the type for the field. 6529 Type *FDTy = FD->getType().getTypePtr(); 6530 6531 if (!FD->isAnonymousStructOrUnion()) { 6532 // Remember all fields written by the user. 6533 RecFields.push_back(FD); 6534 } 6535 6536 // If the field is already invalid for some reason, don't emit more 6537 // diagnostics about it. 6538 if (FD->isInvalidDecl()) { 6539 EnclosingDecl->setInvalidDecl(); 6540 continue; 6541 } 6542 6543 // C99 6.7.2.1p2: 6544 // A structure or union shall not contain a member with 6545 // incomplete or function type (hence, a structure shall not 6546 // contain an instance of itself, but may contain a pointer to 6547 // an instance of itself), except that the last member of a 6548 // structure with more than one named member may have incomplete 6549 // array type; such a structure (and any union containing, 6550 // possibly recursively, a member that is such a structure) 6551 // shall not be a member of a structure or an element of an 6552 // array. 6553 if (FDTy->isFunctionType()) { 6554 // Field declared as a function. 6555 Diag(FD->getLocation(), diag::err_field_declared_as_function) 6556 << FD->getDeclName(); 6557 FD->setInvalidDecl(); 6558 EnclosingDecl->setInvalidDecl(); 6559 continue; 6560 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 6561 Record && Record->isStruct()) { 6562 // Flexible array member. 6563 if (NumNamedMembers < 1) { 6564 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 6565 << FD->getDeclName(); 6566 FD->setInvalidDecl(); 6567 EnclosingDecl->setInvalidDecl(); 6568 continue; 6569 } 6570 if (!FD->getType()->isDependentType() && 6571 !Context.getBaseElementType(FD->getType())->isPODType()) { 6572 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 6573 << FD->getDeclName() << FD->getType(); 6574 FD->setInvalidDecl(); 6575 EnclosingDecl->setInvalidDecl(); 6576 continue; 6577 } 6578 6579 // Okay, we have a legal flexible array member at the end of the struct. 6580 if (Record) 6581 Record->setHasFlexibleArrayMember(true); 6582 } else if (!FDTy->isDependentType() && 6583 RequireCompleteType(FD->getLocation(), FD->getType(), 6584 diag::err_field_incomplete)) { 6585 // Incomplete type 6586 FD->setInvalidDecl(); 6587 EnclosingDecl->setInvalidDecl(); 6588 continue; 6589 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 6590 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 6591 // If this is a member of a union, then entire union becomes "flexible". 6592 if (Record && Record->isUnion()) { 6593 Record->setHasFlexibleArrayMember(true); 6594 } else { 6595 // If this is a struct/class and this is not the last element, reject 6596 // it. Note that GCC supports variable sized arrays in the middle of 6597 // structures. 6598 if (i != NumFields-1) 6599 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 6600 << FD->getDeclName() << FD->getType(); 6601 else { 6602 // We support flexible arrays at the end of structs in 6603 // other structs as an extension. 6604 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 6605 << FD->getDeclName(); 6606 if (Record) 6607 Record->setHasFlexibleArrayMember(true); 6608 } 6609 } 6610 } 6611 if (Record && FDTTy->getDecl()->hasObjectMember()) 6612 Record->setHasObjectMember(true); 6613 } else if (FDTy->isObjCObjectType()) { 6614 /// A field cannot be an Objective-c object 6615 Diag(FD->getLocation(), diag::err_statically_allocated_object); 6616 FD->setInvalidDecl(); 6617 EnclosingDecl->setInvalidDecl(); 6618 continue; 6619 } else if (getLangOptions().ObjC1 && 6620 getLangOptions().getGCMode() != LangOptions::NonGC && 6621 Record && 6622 (FD->getType()->isObjCObjectPointerType() || 6623 FD->getType().isObjCGCStrong())) 6624 Record->setHasObjectMember(true); 6625 else if (Context.getAsArrayType(FD->getType())) { 6626 QualType BaseType = Context.getBaseElementType(FD->getType()); 6627 if (Record && BaseType->isRecordType() && 6628 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 6629 Record->setHasObjectMember(true); 6630 } 6631 // Keep track of the number of named members. 6632 if (FD->getIdentifier()) 6633 ++NumNamedMembers; 6634 } 6635 6636 // Okay, we successfully defined 'Record'. 6637 if (Record) { 6638 Record->completeDefinition(); 6639 } else { 6640 ObjCIvarDecl **ClsFields = 6641 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 6642 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 6643 ID->setLocEnd(RBrac); 6644 // Add ivar's to class's DeclContext. 6645 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 6646 ClsFields[i]->setLexicalDeclContext(ID); 6647 ID->addDecl(ClsFields[i]); 6648 } 6649 // Must enforce the rule that ivars in the base classes may not be 6650 // duplicates. 6651 if (ID->getSuperClass()) 6652 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 6653 } else if (ObjCImplementationDecl *IMPDecl = 6654 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 6655 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 6656 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 6657 // Ivar declared in @implementation never belongs to the implementation. 6658 // Only it is in implementation's lexical context. 6659 ClsFields[I]->setLexicalDeclContext(IMPDecl); 6660 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 6661 } else if (ObjCCategoryDecl *CDecl = 6662 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 6663 // case of ivars in class extension; all other cases have been 6664 // reported as errors elsewhere. 6665 // FIXME. Class extension does not have a LocEnd field. 6666 // CDecl->setLocEnd(RBrac); 6667 // Add ivar's to class extension's DeclContext. 6668 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 6669 ClsFields[i]->setLexicalDeclContext(CDecl); 6670 CDecl->addDecl(ClsFields[i]); 6671 } 6672 } 6673 } 6674 6675 if (Attr) 6676 ProcessDeclAttributeList(S, Record, Attr); 6677 6678 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 6679 // set the visibility of this record. 6680 if (Record && !Record->getDeclContext()->isRecord()) 6681 AddPushedVisibilityAttribute(Record); 6682} 6683 6684/// \brief Determine whether the given integral value is representable within 6685/// the given type T. 6686static bool isRepresentableIntegerValue(ASTContext &Context, 6687 llvm::APSInt &Value, 6688 QualType T) { 6689 assert(T->isIntegralType(Context) && "Integral type required!"); 6690 unsigned BitWidth = Context.getIntWidth(T); 6691 6692 if (Value.isUnsigned() || Value.isNonNegative()) 6693 return Value.getActiveBits() < BitWidth; 6694 6695 return Value.getMinSignedBits() <= BitWidth; 6696} 6697 6698// \brief Given an integral type, return the next larger integral type 6699// (or a NULL type of no such type exists). 6700static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 6701 // FIXME: Int128/UInt128 support, which also needs to be introduced into 6702 // enum checking below. 6703 assert(T->isIntegralType(Context) && "Integral type required!"); 6704 const unsigned NumTypes = 4; 6705 QualType SignedIntegralTypes[NumTypes] = { 6706 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 6707 }; 6708 QualType UnsignedIntegralTypes[NumTypes] = { 6709 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 6710 Context.UnsignedLongLongTy 6711 }; 6712 6713 unsigned BitWidth = Context.getTypeSize(T); 6714 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes 6715 : UnsignedIntegralTypes; 6716 for (unsigned I = 0; I != NumTypes; ++I) 6717 if (Context.getTypeSize(Types[I]) > BitWidth) 6718 return Types[I]; 6719 6720 return QualType(); 6721} 6722 6723EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 6724 EnumConstantDecl *LastEnumConst, 6725 SourceLocation IdLoc, 6726 IdentifierInfo *Id, 6727 Expr *Val) { 6728 unsigned IntWidth = Context.Target.getIntWidth(); 6729 llvm::APSInt EnumVal(IntWidth); 6730 QualType EltTy; 6731 if (Val) { 6732 if (Enum->isDependentType() || Val->isTypeDependent()) 6733 EltTy = Context.DependentTy; 6734 else { 6735 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 6736 SourceLocation ExpLoc; 6737 if (!Val->isValueDependent() && 6738 VerifyIntegerConstantExpression(Val, &EnumVal)) { 6739 Val = 0; 6740 } else { 6741 if (!getLangOptions().CPlusPlus) { 6742 // C99 6.7.2.2p2: 6743 // The expression that defines the value of an enumeration constant 6744 // shall be an integer constant expression that has a value 6745 // representable as an int. 6746 6747 // Complain if the value is not representable in an int. 6748 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 6749 Diag(IdLoc, diag::ext_enum_value_not_int) 6750 << EnumVal.toString(10) << Val->getSourceRange() 6751 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 6752 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 6753 // Force the type of the expression to 'int'. 6754 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast); 6755 } 6756 } 6757 6758 // C++0x [dcl.enum]p5: 6759 // If the underlying type is not fixed, the type of each enumerator 6760 // is the type of its initializing value: 6761 // - If an initializer is specified for an enumerator, the 6762 // initializing value has the same type as the expression. 6763 EltTy = Val->getType(); 6764 } 6765 } 6766 } 6767 6768 if (!Val) { 6769 if (Enum->isDependentType()) 6770 EltTy = Context.DependentTy; 6771 else if (!LastEnumConst) { 6772 // C++0x [dcl.enum]p5: 6773 // If the underlying type is not fixed, the type of each enumerator 6774 // is the type of its initializing value: 6775 // - If no initializer is specified for the first enumerator, the 6776 // initializing value has an unspecified integral type. 6777 // 6778 // GCC uses 'int' for its unspecified integral type, as does 6779 // C99 6.7.2.2p3. 6780 EltTy = Context.IntTy; 6781 } else { 6782 // Assign the last value + 1. 6783 EnumVal = LastEnumConst->getInitVal(); 6784 ++EnumVal; 6785 EltTy = LastEnumConst->getType(); 6786 6787 // Check for overflow on increment. 6788 if (EnumVal < LastEnumConst->getInitVal()) { 6789 // C++0x [dcl.enum]p5: 6790 // If the underlying type is not fixed, the type of each enumerator 6791 // is the type of its initializing value: 6792 // 6793 // - Otherwise the type of the initializing value is the same as 6794 // the type of the initializing value of the preceding enumerator 6795 // unless the incremented value is not representable in that type, 6796 // in which case the type is an unspecified integral type 6797 // sufficient to contain the incremented value. If no such type 6798 // exists, the program is ill-formed. 6799 QualType T = getNextLargerIntegralType(Context, EltTy); 6800 if (T.isNull()) { 6801 // There is no integral type larger enough to represent this 6802 // value. Complain, then allow the value to wrap around. 6803 EnumVal = LastEnumConst->getInitVal(); 6804 EnumVal.zext(EnumVal.getBitWidth() * 2); 6805 Diag(IdLoc, diag::warn_enumerator_too_large) 6806 << EnumVal.toString(10); 6807 } else { 6808 EltTy = T; 6809 } 6810 6811 // Retrieve the last enumerator's value, extent that type to the 6812 // type that is supposed to be large enough to represent the incremented 6813 // value, then increment. 6814 EnumVal = LastEnumConst->getInitVal(); 6815 EnumVal.setIsSigned(EltTy->isSignedIntegerType()); 6816 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 6817 ++EnumVal; 6818 6819 // If we're not in C++, diagnose the overflow of enumerator values, 6820 // which in C99 means that the enumerator value is not representable in 6821 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 6822 // permits enumerator values that are representable in some larger 6823 // integral type. 6824 if (!getLangOptions().CPlusPlus && !T.isNull()) 6825 Diag(IdLoc, diag::warn_enum_value_overflow); 6826 } else if (!getLangOptions().CPlusPlus && 6827 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 6828 // Enforce C99 6.7.2.2p2 even when we compute the next value. 6829 Diag(IdLoc, diag::ext_enum_value_not_int) 6830 << EnumVal.toString(10) << 1; 6831 } 6832 } 6833 } 6834 6835 if (!EltTy->isDependentType()) { 6836 // Make the enumerator value match the signedness and size of the 6837 // enumerator's type. 6838 EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 6839 EnumVal.setIsSigned(EltTy->isSignedIntegerType()); 6840 } 6841 6842 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 6843 Val, EnumVal); 6844} 6845 6846 6847Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, 6848 Decl *lastEnumConst, 6849 SourceLocation IdLoc, 6850 IdentifierInfo *Id, 6851 SourceLocation EqualLoc, ExprTy *val) { 6852 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 6853 EnumConstantDecl *LastEnumConst = 6854 cast_or_null<EnumConstantDecl>(lastEnumConst); 6855 Expr *Val = static_cast<Expr*>(val); 6856 6857 // The scope passed in may not be a decl scope. Zip up the scope tree until 6858 // we find one that is. 6859 S = getNonFieldDeclScope(S); 6860 6861 // Verify that there isn't already something declared with this name in this 6862 // scope. 6863 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 6864 ForRedeclaration); 6865 if (PrevDecl && PrevDecl->isTemplateParameter()) { 6866 // Maybe we will complain about the shadowed template parameter. 6867 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 6868 // Just pretend that we didn't see the previous declaration. 6869 PrevDecl = 0; 6870 } 6871 6872 if (PrevDecl) { 6873 // When in C++, we may get a TagDecl with the same name; in this case the 6874 // enum constant will 'hide' the tag. 6875 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 6876 "Received TagDecl when not in C++!"); 6877 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 6878 if (isa<EnumConstantDecl>(PrevDecl)) 6879 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 6880 else 6881 Diag(IdLoc, diag::err_redefinition) << Id; 6882 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6883 return 0; 6884 } 6885 } 6886 6887 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 6888 IdLoc, Id, Val); 6889 6890 // Register this decl in the current scope stack. 6891 if (New) { 6892 New->setAccess(TheEnumDecl->getAccess()); 6893 PushOnScopeChains(New, S); 6894 } 6895 6896 return New; 6897} 6898 6899void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 6900 SourceLocation RBraceLoc, Decl *EnumDeclX, 6901 Decl **Elements, unsigned NumElements, 6902 Scope *S, AttributeList *Attr) { 6903 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 6904 QualType EnumType = Context.getTypeDeclType(Enum); 6905 6906 if (Attr) 6907 ProcessDeclAttributeList(S, Enum, Attr); 6908 6909 if (Enum->isDependentType()) { 6910 for (unsigned i = 0; i != NumElements; ++i) { 6911 EnumConstantDecl *ECD = 6912 cast_or_null<EnumConstantDecl>(Elements[i]); 6913 if (!ECD) continue; 6914 6915 ECD->setType(EnumType); 6916 } 6917 6918 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 6919 return; 6920 } 6921 6922 // TODO: If the result value doesn't fit in an int, it must be a long or long 6923 // long value. ISO C does not support this, but GCC does as an extension, 6924 // emit a warning. 6925 unsigned IntWidth = Context.Target.getIntWidth(); 6926 unsigned CharWidth = Context.Target.getCharWidth(); 6927 unsigned ShortWidth = Context.Target.getShortWidth(); 6928 6929 // Verify that all the values are okay, compute the size of the values, and 6930 // reverse the list. 6931 unsigned NumNegativeBits = 0; 6932 unsigned NumPositiveBits = 0; 6933 6934 // Keep track of whether all elements have type int. 6935 bool AllElementsInt = true; 6936 6937 for (unsigned i = 0; i != NumElements; ++i) { 6938 EnumConstantDecl *ECD = 6939 cast_or_null<EnumConstantDecl>(Elements[i]); 6940 if (!ECD) continue; // Already issued a diagnostic. 6941 6942 const llvm::APSInt &InitVal = ECD->getInitVal(); 6943 6944 // Keep track of the size of positive and negative values. 6945 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 6946 NumPositiveBits = std::max(NumPositiveBits, 6947 (unsigned)InitVal.getActiveBits()); 6948 else 6949 NumNegativeBits = std::max(NumNegativeBits, 6950 (unsigned)InitVal.getMinSignedBits()); 6951 6952 // Keep track of whether every enum element has type int (very commmon). 6953 if (AllElementsInt) 6954 AllElementsInt = ECD->getType() == Context.IntTy; 6955 } 6956 6957 // Figure out the type that should be used for this enum. 6958 // FIXME: Support -fshort-enums. 6959 QualType BestType; 6960 unsigned BestWidth; 6961 6962 // C++0x N3000 [conv.prom]p3: 6963 // An rvalue of an unscoped enumeration type whose underlying 6964 // type is not fixed can be converted to an rvalue of the first 6965 // of the following types that can represent all the values of 6966 // the enumeration: int, unsigned int, long int, unsigned long 6967 // int, long long int, or unsigned long long int. 6968 // C99 6.4.4.3p2: 6969 // An identifier declared as an enumeration constant has type int. 6970 // The C99 rule is modified by a gcc extension 6971 QualType BestPromotionType; 6972 6973 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 6974 6975 if (NumNegativeBits) { 6976 // If there is a negative value, figure out the smallest integer type (of 6977 // int/long/longlong) that fits. 6978 // If it's packed, check also if it fits a char or a short. 6979 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 6980 BestType = Context.SignedCharTy; 6981 BestWidth = CharWidth; 6982 } else if (Packed && NumNegativeBits <= ShortWidth && 6983 NumPositiveBits < ShortWidth) { 6984 BestType = Context.ShortTy; 6985 BestWidth = ShortWidth; 6986 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 6987 BestType = Context.IntTy; 6988 BestWidth = IntWidth; 6989 } else { 6990 BestWidth = Context.Target.getLongWidth(); 6991 6992 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 6993 BestType = Context.LongTy; 6994 } else { 6995 BestWidth = Context.Target.getLongLongWidth(); 6996 6997 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 6998 Diag(Enum->getLocation(), diag::warn_enum_too_large); 6999 BestType = Context.LongLongTy; 7000 } 7001 } 7002 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 7003 } else { 7004 // If there is no negative value, figure out the smallest type that fits 7005 // all of the enumerator values. 7006 // If it's packed, check also if it fits a char or a short. 7007 if (Packed && NumPositiveBits <= CharWidth) { 7008 BestType = Context.UnsignedCharTy; 7009 BestPromotionType = Context.IntTy; 7010 BestWidth = CharWidth; 7011 } else if (Packed && NumPositiveBits <= ShortWidth) { 7012 BestType = Context.UnsignedShortTy; 7013 BestPromotionType = Context.IntTy; 7014 BestWidth = ShortWidth; 7015 } else if (NumPositiveBits <= IntWidth) { 7016 BestType = Context.UnsignedIntTy; 7017 BestWidth = IntWidth; 7018 BestPromotionType 7019 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 7020 ? Context.UnsignedIntTy : Context.IntTy; 7021 } else if (NumPositiveBits <= 7022 (BestWidth = Context.Target.getLongWidth())) { 7023 BestType = Context.UnsignedLongTy; 7024 BestPromotionType 7025 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 7026 ? Context.UnsignedLongTy : Context.LongTy; 7027 } else { 7028 BestWidth = Context.Target.getLongLongWidth(); 7029 assert(NumPositiveBits <= BestWidth && 7030 "How could an initializer get larger than ULL?"); 7031 BestType = Context.UnsignedLongLongTy; 7032 BestPromotionType 7033 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 7034 ? Context.UnsignedLongLongTy : Context.LongLongTy; 7035 } 7036 } 7037 7038 // Loop over all of the enumerator constants, changing their types to match 7039 // the type of the enum if needed. 7040 for (unsigned i = 0; i != NumElements; ++i) { 7041 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 7042 if (!ECD) continue; // Already issued a diagnostic. 7043 7044 // Standard C says the enumerators have int type, but we allow, as an 7045 // extension, the enumerators to be larger than int size. If each 7046 // enumerator value fits in an int, type it as an int, otherwise type it the 7047 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 7048 // that X has type 'int', not 'unsigned'. 7049 7050 // Determine whether the value fits into an int. 7051 llvm::APSInt InitVal = ECD->getInitVal(); 7052 7053 // If it fits into an integer type, force it. Otherwise force it to match 7054 // the enum decl type. 7055 QualType NewTy; 7056 unsigned NewWidth; 7057 bool NewSign; 7058 if (!getLangOptions().CPlusPlus && 7059 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 7060 NewTy = Context.IntTy; 7061 NewWidth = IntWidth; 7062 NewSign = true; 7063 } else if (ECD->getType() == BestType) { 7064 // Already the right type! 7065 if (getLangOptions().CPlusPlus) 7066 // C++ [dcl.enum]p4: Following the closing brace of an 7067 // enum-specifier, each enumerator has the type of its 7068 // enumeration. 7069 ECD->setType(EnumType); 7070 continue; 7071 } else { 7072 NewTy = BestType; 7073 NewWidth = BestWidth; 7074 NewSign = BestType->isSignedIntegerType(); 7075 } 7076 7077 // Adjust the APSInt value. 7078 InitVal.extOrTrunc(NewWidth); 7079 InitVal.setIsSigned(NewSign); 7080 ECD->setInitVal(InitVal); 7081 7082 // Adjust the Expr initializer and type. 7083 if (ECD->getInitExpr()) 7084 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 7085 CastExpr::CK_IntegralCast, 7086 ECD->getInitExpr(), 7087 /*base paths*/ 0, 7088 VK_RValue)); 7089 if (getLangOptions().CPlusPlus) 7090 // C++ [dcl.enum]p4: Following the closing brace of an 7091 // enum-specifier, each enumerator has the type of its 7092 // enumeration. 7093 ECD->setType(EnumType); 7094 else 7095 ECD->setType(NewTy); 7096 } 7097 7098 Enum->completeDefinition(BestType, BestPromotionType, 7099 NumPositiveBits, NumNegativeBits); 7100} 7101 7102Decl *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, Expr *expr) { 7103 StringLiteral *AsmString = cast<StringLiteral>(expr); 7104 7105 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 7106 Loc, AsmString); 7107 CurContext->addDecl(New); 7108 return New; 7109} 7110 7111void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 7112 SourceLocation PragmaLoc, 7113 SourceLocation NameLoc) { 7114 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 7115 7116 if (PrevDecl) { 7117 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 7118 } else { 7119 (void)WeakUndeclaredIdentifiers.insert( 7120 std::pair<IdentifierInfo*,WeakInfo> 7121 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 7122 } 7123} 7124 7125void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 7126 IdentifierInfo* AliasName, 7127 SourceLocation PragmaLoc, 7128 SourceLocation NameLoc, 7129 SourceLocation AliasNameLoc) { 7130 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 7131 LookupOrdinaryName); 7132 WeakInfo W = WeakInfo(Name, NameLoc); 7133 7134 if (PrevDecl) { 7135 if (!PrevDecl->hasAttr<AliasAttr>()) 7136 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 7137 DeclApplyPragmaWeak(TUScope, ND, W); 7138 } else { 7139 (void)WeakUndeclaredIdentifiers.insert( 7140 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 7141 } 7142} 7143