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