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