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