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