SemaDecl.cpp revision 23a48cc69e7ed4f219996a8864cb7d3f24f1157f
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 "clang/AST/APValue.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/DeclTemplate.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/Parse/DeclSpec.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Basic/SourceManager.h" 24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Lex/HeaderSearch.h" 27#include "llvm/ADT/SmallSet.h" 28#include "llvm/ADT/STLExtras.h" 29#include <algorithm> 30#include <functional> 31using namespace clang; 32 33/// getDeclName - Return a pretty name for the specified decl if possible, or 34/// an empty string if not. This is used for pretty crash reporting. 35std::string Sema::getDeclName(DeclPtrTy d) { 36 Decl *D = d.getAs<Decl>(); 37 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D)) 38 return DN->getQualifiedNameAsString(); 39 return ""; 40} 41 42Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) { 43 return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>())); 44} 45 46/// \brief If the identifier refers to a type name within this scope, 47/// return the declaration of that type. 48/// 49/// This routine performs ordinary name lookup of the identifier II 50/// within the given scope, with optional C++ scope specifier SS, to 51/// determine whether the name refers to a type. If so, returns an 52/// opaque pointer (actually a QualType) corresponding to that 53/// type. Otherwise, returns NULL. 54/// 55/// If name lookup results in an ambiguity, this routine will complain 56/// and then return NULL. 57Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 58 Scope *S, const CXXScopeSpec *SS) { 59 // C++ [temp.res]p3: 60 // A qualified-id that refers to a type and in which the 61 // nested-name-specifier depends on a template-parameter (14.6.2) 62 // shall be prefixed by the keyword typename to indicate that the 63 // qualified-id denotes a type, forming an 64 // elaborated-type-specifier (7.1.5.3). 65 // 66 // We therefore do not perform any name lookup up SS is a dependent 67 // scope name. FIXME: we will need to perform a special kind of 68 // lookup if the scope specifier names a member of the current 69 // instantiation. 70 if (SS && isDependentScopeSpecifier(*SS)) 71 return 0; 72 73 NamedDecl *IIDecl = 0; 74 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName, 75 false, false); 76 switch (Result.getKind()) { 77 case LookupResult::NotFound: 78 case LookupResult::FoundOverloaded: 79 return 0; 80 81 case LookupResult::AmbiguousBaseSubobjectTypes: 82 case LookupResult::AmbiguousBaseSubobjects: 83 case LookupResult::AmbiguousReference: { 84 // Look to see if we have a type anywhere in the list of results. 85 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 86 Res != ResEnd; ++Res) { 87 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 88 if (!IIDecl || 89 (*Res)->getLocation().getRawEncoding() < 90 IIDecl->getLocation().getRawEncoding()) 91 IIDecl = *Res; 92 } 93 } 94 95 if (!IIDecl) { 96 // None of the entities we found is a type, so there is no way 97 // to even assume that the result is a type. In this case, don't 98 // complain about the ambiguity. The parser will either try to 99 // perform this lookup again (e.g., as an object name), which 100 // will produce the ambiguity, or will complain that it expected 101 // a type name. 102 Result.Destroy(); 103 return 0; 104 } 105 106 // We found a type within the ambiguous lookup; diagnose the 107 // ambiguity and then return that type. This might be the right 108 // answer, or it might not be, but it suppresses any attempt to 109 // perform the name lookup again. 110 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc); 111 break; 112 } 113 114 case LookupResult::Found: 115 IIDecl = Result.getAsDecl(); 116 break; 117 } 118 119 if (IIDecl) { 120 QualType T; 121 122 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 123 // Check whether we can use this type 124 (void)DiagnoseUseOfDecl(IIDecl, NameLoc); 125 126 T = Context.getTypeDeclType(TD); 127 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 128 // Check whether we can use this interface. 129 (void)DiagnoseUseOfDecl(IIDecl, NameLoc); 130 131 T = Context.getObjCInterfaceType(IDecl); 132 } else 133 return 0; 134 135 if (SS) 136 T = getQualifiedNameType(*SS, T); 137 138 return T.getAsOpaquePtr(); 139 } 140 141 return 0; 142} 143 144/// isTagName() - This method is called *for error recovery purposes only* 145/// to determine if the specified name is a valid tag name ("struct foo"). If 146/// so, this returns the TST for the tag corresponding to it (TST_enum, 147/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 148/// where the user forgot to specify the tag. 149DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 150 // Do a tag name lookup in this scope. 151 LookupResult R = LookupName(S, &II, LookupTagName, false, false); 152 if (R.getKind() == LookupResult::Found) 153 if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) { 154 switch (TD->getTagKind()) { 155 case TagDecl::TK_struct: return DeclSpec::TST_struct; 156 case TagDecl::TK_union: return DeclSpec::TST_union; 157 case TagDecl::TK_class: return DeclSpec::TST_class; 158 case TagDecl::TK_enum: return DeclSpec::TST_enum; 159 } 160 } 161 162 return DeclSpec::TST_unspecified; 163} 164 165 166 167DeclContext *Sema::getContainingDC(DeclContext *DC) { 168 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 169 // A C++ out-of-line method will return to the file declaration context. 170 if (MD->isOutOfLineDefinition()) 171 return MD->getLexicalDeclContext(); 172 173 // A C++ inline method is parsed *after* the topmost class it was declared 174 // in is fully parsed (it's "complete"). 175 // The parsing of a C++ inline method happens at the declaration context of 176 // the topmost (non-nested) class it is lexically declared in. 177 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record."); 178 DC = MD->getParent(); 179 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 180 DC = RD; 181 182 // Return the declaration context of the topmost class the inline method is 183 // declared in. 184 return DC; 185 } 186 187 if (isa<ObjCMethodDecl>(DC)) 188 return Context.getTranslationUnitDecl(); 189 190 return DC->getLexicalParent(); 191} 192 193void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 194 assert(getContainingDC(DC) == CurContext && 195 "The next DeclContext should be lexically contained in the current one."); 196 CurContext = DC; 197 S->setEntity(DC); 198} 199 200void Sema::PopDeclContext() { 201 assert(CurContext && "DeclContext imbalance!"); 202 203 CurContext = getContainingDC(CurContext); 204} 205 206/// \brief Determine whether we allow overloading of the function 207/// PrevDecl with another declaration. 208/// 209/// This routine determines whether overloading is possible, not 210/// whether some new function is actually an overload. It will return 211/// true in C++ (where we can always provide overloads) or, as an 212/// extension, in C when the previous function is already an 213/// overloaded function declaration or has the "overloadable" 214/// attribute. 215static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) { 216 if (Context.getLangOptions().CPlusPlus) 217 return true; 218 219 if (isa<OverloadedFunctionDecl>(PrevDecl)) 220 return true; 221 222 return PrevDecl->getAttr<OverloadableAttr>() != 0; 223} 224 225/// Add this decl to the scope shadowed decl chains. 226void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) { 227 // Move up the scope chain until we find the nearest enclosing 228 // non-transparent context. The declaration will be introduced into this 229 // scope. 230 while (S->getEntity() && 231 ((DeclContext *)S->getEntity())->isTransparentContext()) 232 S = S->getParent(); 233 234 S->AddDecl(DeclPtrTy::make(D)); 235 236 // Add scoped declarations into their context, so that they can be 237 // found later. Declarations without a context won't be inserted 238 // into any context. 239 CurContext->addDecl(Context, D); 240 241 // C++ [basic.scope]p4: 242 // -- exactly one declaration shall declare a class name or 243 // enumeration name that is not a typedef name and the other 244 // declarations shall all refer to the same object or 245 // enumerator, or all refer to functions and function templates; 246 // in this case the class name or enumeration name is hidden. 247 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 248 // We are pushing the name of a tag (enum or class). 249 if (CurContext->getLookupContext() 250 == TD->getDeclContext()->getLookupContext()) { 251 // We're pushing the tag into the current context, which might 252 // require some reshuffling in the identifier resolver. 253 IdentifierResolver::iterator 254 I = IdResolver.begin(TD->getDeclName()), 255 IEnd = IdResolver.end(); 256 if (I != IEnd && isDeclInScope(*I, CurContext, S)) { 257 NamedDecl *PrevDecl = *I; 258 for (; I != IEnd && isDeclInScope(*I, CurContext, S); 259 PrevDecl = *I, ++I) { 260 if (TD->declarationReplaces(*I)) { 261 // This is a redeclaration. Remove it from the chain and 262 // break out, so that we'll add in the shadowed 263 // declaration. 264 S->RemoveDecl(DeclPtrTy::make(*I)); 265 if (PrevDecl == *I) { 266 IdResolver.RemoveDecl(*I); 267 IdResolver.AddDecl(TD); 268 return; 269 } else { 270 IdResolver.RemoveDecl(*I); 271 break; 272 } 273 } 274 } 275 276 // There is already a declaration with the same name in the same 277 // scope, which is not a tag declaration. It must be found 278 // before we find the new declaration, so insert the new 279 // declaration at the end of the chain. 280 IdResolver.AddShadowedDecl(TD, PrevDecl); 281 282 return; 283 } 284 } 285 } else if (isa<FunctionDecl>(D) && 286 AllowOverloadingOfFunction(D, Context)) { 287 // We are pushing the name of a function, which might be an 288 // overloaded name. 289 FunctionDecl *FD = cast<FunctionDecl>(D); 290 IdentifierResolver::iterator Redecl 291 = std::find_if(IdResolver.begin(FD->getDeclName()), 292 IdResolver.end(), 293 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces), 294 FD)); 295 if (Redecl != IdResolver.end() && 296 S->isDeclScope(DeclPtrTy::make(*Redecl))) { 297 // There is already a declaration of a function on our 298 // IdResolver chain. Replace it with this declaration. 299 S->RemoveDecl(DeclPtrTy::make(*Redecl)); 300 IdResolver.RemoveDecl(*Redecl); 301 } 302 } 303 304 IdResolver.AddDecl(D); 305} 306 307void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 308 if (S->decl_empty()) return; 309 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 310 "Scope shouldn't contain decls!"); 311 312 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 313 I != E; ++I) { 314 Decl *TmpD = (*I).getAs<Decl>(); 315 assert(TmpD && "This decl didn't get pushed??"); 316 317 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 318 NamedDecl *D = cast<NamedDecl>(TmpD); 319 320 if (!D->getDeclName()) continue; 321 322 // Remove this name from our lexical scope. 323 IdResolver.RemoveDecl(D); 324 } 325} 326 327/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 328/// return 0 if one not found. 329ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 330 // The third "scope" argument is 0 since we aren't enabling lazy built-in 331 // creation from this context. 332 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName); 333 334 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 335} 336 337/// getNonFieldDeclScope - Retrieves the innermost scope, starting 338/// from S, where a non-field would be declared. This routine copes 339/// with the difference between C and C++ scoping rules in structs and 340/// unions. For example, the following code is well-formed in C but 341/// ill-formed in C++: 342/// @code 343/// struct S6 { 344/// enum { BAR } e; 345/// }; 346/// 347/// void test_S6() { 348/// struct S6 a; 349/// a.e = BAR; 350/// } 351/// @endcode 352/// For the declaration of BAR, this routine will return a different 353/// scope. The scope S will be the scope of the unnamed enumeration 354/// within S6. In C++, this routine will return the scope associated 355/// with S6, because the enumeration's scope is a transparent 356/// context but structures can contain non-field names. In C, this 357/// routine will return the translation unit scope, since the 358/// enumeration's scope is a transparent context and structures cannot 359/// contain non-field names. 360Scope *Sema::getNonFieldDeclScope(Scope *S) { 361 while (((S->getFlags() & Scope::DeclScope) == 0) || 362 (S->getEntity() && 363 ((DeclContext *)S->getEntity())->isTransparentContext()) || 364 (S->isClassScope() && !getLangOptions().CPlusPlus)) 365 S = S->getParent(); 366 return S; 367} 368 369void Sema::InitBuiltinVaListType() { 370 if (!Context.getBuiltinVaListType().isNull()) 371 return; 372 373 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 374 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName); 375 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 376 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 377} 378 379/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 380/// file scope. lazily create a decl for it. ForRedeclaration is true 381/// if we're creating this built-in in anticipation of redeclaring the 382/// built-in. 383NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 384 Scope *S, bool ForRedeclaration, 385 SourceLocation Loc) { 386 Builtin::ID BID = (Builtin::ID)bid; 387 388 if (Context.BuiltinInfo.hasVAListUse(BID)) 389 InitBuiltinVaListType(); 390 391 Builtin::Context::GetBuiltinTypeError Error; 392 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error); 393 switch (Error) { 394 case Builtin::Context::GE_None: 395 // Okay 396 break; 397 398 case Builtin::Context::GE_Missing_FILE: 399 if (ForRedeclaration) 400 Diag(Loc, diag::err_implicit_decl_requires_stdio) 401 << Context.BuiltinInfo.GetName(BID); 402 return 0; 403 } 404 405 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 406 Diag(Loc, diag::ext_implicit_lib_function_decl) 407 << Context.BuiltinInfo.GetName(BID) 408 << R; 409 if (Context.BuiltinInfo.getHeaderName(BID) && 410 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl) 411 != Diagnostic::Ignored) 412 Diag(Loc, diag::note_please_include_header) 413 << Context.BuiltinInfo.getHeaderName(BID) 414 << Context.BuiltinInfo.GetName(BID); 415 } 416 417 FunctionDecl *New = FunctionDecl::Create(Context, 418 Context.getTranslationUnitDecl(), 419 Loc, II, R, 420 FunctionDecl::Extern, false, 421 /*hasPrototype=*/true); 422 New->setImplicit(); 423 424 // Create Decl objects for each parameter, adding them to the 425 // FunctionDecl. 426 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 427 llvm::SmallVector<ParmVarDecl*, 16> Params; 428 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 429 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 430 FT->getArgType(i), VarDecl::None, 0)); 431 New->setParams(Context, &Params[0], Params.size()); 432 } 433 434 AddKnownFunctionAttributes(New); 435 436 // TUScope is the translation-unit scope to insert this function into. 437 // FIXME: This is hideous. We need to teach PushOnScopeChains to 438 // relate Scopes to DeclContexts, and probably eliminate CurContext 439 // entirely, but we're not there yet. 440 DeclContext *SavedContext = CurContext; 441 CurContext = Context.getTranslationUnitDecl(); 442 PushOnScopeChains(New, TUScope); 443 CurContext = SavedContext; 444 return New; 445} 446 447/// GetStdNamespace - This method gets the C++ "std" namespace. This is where 448/// everything from the standard library is defined. 449NamespaceDecl *Sema::GetStdNamespace() { 450 if (!StdNamespace) { 451 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std"); 452 DeclContext *Global = Context.getTranslationUnitDecl(); 453 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName); 454 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std); 455 } 456 return StdNamespace; 457} 458 459/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the 460/// same name and scope as a previous declaration 'Old'. Figure out 461/// how to resolve this situation, merging decls or emitting 462/// diagnostics as appropriate. Returns true if there was an error, 463/// false otherwise. 464/// 465bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 466 bool objc_types = false; 467 // Allow multiple definitions for ObjC built-in typedefs. 468 // FIXME: Verify the underlying types are equivalent! 469 if (getLangOptions().ObjC1) { 470 const IdentifierInfo *TypeID = New->getIdentifier(); 471 switch (TypeID->getLength()) { 472 default: break; 473 case 2: 474 if (!TypeID->isStr("id")) 475 break; 476 Context.setObjCIdType(New); 477 objc_types = true; 478 break; 479 case 5: 480 if (!TypeID->isStr("Class")) 481 break; 482 Context.setObjCClassType(New); 483 objc_types = true; 484 return false; 485 case 3: 486 if (!TypeID->isStr("SEL")) 487 break; 488 Context.setObjCSelType(New); 489 objc_types = true; 490 return false; 491 case 8: 492 if (!TypeID->isStr("Protocol")) 493 break; 494 Context.setObjCProtoType(New->getUnderlyingType()); 495 objc_types = true; 496 return false; 497 } 498 // Fall through - the typedef name was not a builtin type. 499 } 500 // Verify the old decl was also a type. 501 TypeDecl *Old = dyn_cast<TypeDecl>(OldD); 502 if (!Old) { 503 Diag(New->getLocation(), diag::err_redefinition_different_kind) 504 << New->getDeclName(); 505 if (!objc_types) 506 Diag(OldD->getLocation(), diag::note_previous_definition); 507 return true; 508 } 509 510 // Determine the "old" type we'll use for checking and diagnostics. 511 QualType OldType; 512 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 513 OldType = OldTypedef->getUnderlyingType(); 514 else 515 OldType = Context.getTypeDeclType(Old); 516 517 // If the typedef types are not identical, reject them in all languages and 518 // with any extensions enabled. 519 520 if (OldType != New->getUnderlyingType() && 521 Context.getCanonicalType(OldType) != 522 Context.getCanonicalType(New->getUnderlyingType())) { 523 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 524 << New->getUnderlyingType() << OldType; 525 if (!objc_types) 526 Diag(Old->getLocation(), diag::note_previous_definition); 527 return true; 528 } 529 if (objc_types) return false; 530 if (getLangOptions().Microsoft) return false; 531 532 // C++ [dcl.typedef]p2: 533 // In a given non-class scope, a typedef specifier can be used to 534 // redefine the name of any type declared in that scope to refer 535 // to the type to which it already refers. 536 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext)) 537 return false; 538 539 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1). 540 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if 541 // *either* declaration is in a system header. The code below implements 542 // this adhoc compatibility rule. FIXME: The following code will not 543 // work properly when compiling ".i" files (containing preprocessed output). 544 if (PP.getDiagnostics().getSuppressSystemWarnings()) { 545 SourceManager &SrcMgr = Context.getSourceManager(); 546 if (SrcMgr.isInSystemHeader(Old->getLocation())) 547 return false; 548 if (SrcMgr.isInSystemHeader(New->getLocation())) 549 return false; 550 } 551 552 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 553 Diag(Old->getLocation(), diag::note_previous_definition); 554 return true; 555} 556 557/// DeclhasAttr - returns true if decl Declaration already has the target 558/// attribute. 559static bool DeclHasAttr(const Decl *decl, const Attr *target) { 560 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 561 if (attr->getKind() == target->getKind()) 562 return true; 563 564 return false; 565} 566 567/// MergeAttributes - append attributes from the Old decl to the New one. 568static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) { 569 Attr *attr = const_cast<Attr*>(Old->getAttrs()); 570 571 while (attr) { 572 Attr *tmp = attr; 573 attr = attr->getNext(); 574 575 if (!DeclHasAttr(New, tmp) && tmp->isMerged()) { 576 tmp->setInherited(true); 577 New->addAttr(tmp); 578 } else { 579 tmp->setNext(0); 580 tmp->Destroy(C); 581 } 582 } 583 584 Old->invalidateAttrs(); 585} 586 587/// Used in MergeFunctionDecl to keep track of function parameters in 588/// C. 589struct GNUCompatibleParamWarning { 590 ParmVarDecl *OldParm; 591 ParmVarDecl *NewParm; 592 QualType PromotedType; 593}; 594 595/// MergeFunctionDecl - We just parsed a function 'New' from 596/// declarator D which has the same name and scope as a previous 597/// declaration 'Old'. Figure out how to resolve this situation, 598/// merging decls or emitting diagnostics as appropriate. 599/// 600/// In C++, New and Old must be declarations that are not 601/// overloaded. Use IsOverload to determine whether New and Old are 602/// overloaded, and to select the Old declaration that New should be 603/// merged with. 604/// 605/// Returns true if there was an error, false otherwise. 606bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 607 assert(!isa<OverloadedFunctionDecl>(OldD) && 608 "Cannot merge with an overloaded function declaration"); 609 610 // Verify the old decl was also a function. 611 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD); 612 if (!Old) { 613 Diag(New->getLocation(), diag::err_redefinition_different_kind) 614 << New->getDeclName(); 615 Diag(OldD->getLocation(), diag::note_previous_definition); 616 return true; 617 } 618 619 // Determine whether the previous declaration was a definition, 620 // implicit declaration, or a declaration. 621 diag::kind PrevDiag; 622 if (Old->isThisDeclarationADefinition()) 623 PrevDiag = diag::note_previous_definition; 624 else if (Old->isImplicit()) 625 PrevDiag = diag::note_previous_implicit_declaration; 626 else 627 PrevDiag = diag::note_previous_declaration; 628 629 QualType OldQType = Context.getCanonicalType(Old->getType()); 630 QualType NewQType = Context.getCanonicalType(New->getType()); 631 632 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 633 New->getStorageClass() == FunctionDecl::Static && 634 Old->getStorageClass() != FunctionDecl::Static) { 635 Diag(New->getLocation(), diag::err_static_non_static) 636 << New; 637 Diag(Old->getLocation(), PrevDiag); 638 return true; 639 } 640 641 if (getLangOptions().CPlusPlus) { 642 // (C++98 13.1p2): 643 // Certain function declarations cannot be overloaded: 644 // -- Function declarations that differ only in the return type 645 // cannot be overloaded. 646 QualType OldReturnType 647 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 648 QualType NewReturnType 649 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 650 if (OldReturnType != NewReturnType) { 651 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 652 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 653 return true; 654 } 655 656 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 657 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 658 if (OldMethod && NewMethod && 659 OldMethod->getLexicalDeclContext() == 660 NewMethod->getLexicalDeclContext()) { 661 // -- Member function declarations with the same name and the 662 // same parameter types cannot be overloaded if any of them 663 // is a static member function declaration. 664 if (OldMethod->isStatic() || NewMethod->isStatic()) { 665 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 666 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 667 return true; 668 } 669 670 // C++ [class.mem]p1: 671 // [...] A member shall not be declared twice in the 672 // member-specification, except that a nested class or member 673 // class template can be declared and then later defined. 674 unsigned NewDiag; 675 if (isa<CXXConstructorDecl>(OldMethod)) 676 NewDiag = diag::err_constructor_redeclared; 677 else if (isa<CXXDestructorDecl>(NewMethod)) 678 NewDiag = diag::err_destructor_redeclared; 679 else if (isa<CXXConversionDecl>(NewMethod)) 680 NewDiag = diag::err_conv_function_redeclared; 681 else 682 NewDiag = diag::err_member_redeclared; 683 684 Diag(New->getLocation(), NewDiag); 685 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 686 } 687 688 // (C++98 8.3.5p3): 689 // All declarations for a function shall agree exactly in both the 690 // return type and the parameter-type-list. 691 if (OldQType == NewQType) 692 return MergeCompatibleFunctionDecls(New, Old); 693 694 // Fall through for conflicting redeclarations and redefinitions. 695 } 696 697 // C: Function types need to be compatible, not identical. This handles 698 // duplicate function decls like "void f(int); void f(enum X);" properly. 699 if (!getLangOptions().CPlusPlus && 700 Context.typesAreCompatible(OldQType, NewQType)) { 701 const FunctionType *OldFuncType = OldQType->getAsFunctionType(); 702 const FunctionType *NewFuncType = NewQType->getAsFunctionType(); 703 const FunctionProtoType *OldProto = 0; 704 if (isa<FunctionNoProtoType>(NewFuncType) && 705 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 706 // The old declaration provided a function prototype, but the 707 // new declaration does not. Merge in the prototype. 708 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 709 OldProto->arg_type_end()); 710 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 711 &ParamTypes[0], ParamTypes.size(), 712 OldProto->isVariadic(), 713 OldProto->getTypeQuals()); 714 New->setType(NewQType); 715 New->setInheritedPrototype(); 716 717 // Synthesize a parameter for each argument type. 718 llvm::SmallVector<ParmVarDecl*, 16> Params; 719 for (FunctionProtoType::arg_type_iterator 720 ParamType = OldProto->arg_type_begin(), 721 ParamEnd = OldProto->arg_type_end(); 722 ParamType != ParamEnd; ++ParamType) { 723 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 724 SourceLocation(), 0, 725 *ParamType, VarDecl::None, 726 0); 727 Param->setImplicit(); 728 Params.push_back(Param); 729 } 730 731 New->setParams(Context, &Params[0], Params.size()); 732 } 733 734 return MergeCompatibleFunctionDecls(New, Old); 735 } 736 737 // GNU C permits a K&R definition to follow a prototype declaration 738 // if the declared types of the parameters in the K&R definition 739 // match the types in the prototype declaration, even when the 740 // promoted types of the parameters from the K&R definition differ 741 // from the types in the prototype. GCC then keeps the types from 742 // the prototype. 743 if (!getLangOptions().CPlusPlus && 744 !getLangOptions().NoExtensions && 745 Old->hasPrototype() && !New->hasPrototype() && 746 New->getType()->getAsFunctionProtoType() && 747 Old->getNumParams() == New->getNumParams()) { 748 llvm::SmallVector<QualType, 16> ArgTypes; 749 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 750 const FunctionProtoType *OldProto 751 = Old->getType()->getAsFunctionProtoType(); 752 const FunctionProtoType *NewProto 753 = New->getType()->getAsFunctionProtoType(); 754 755 // Determine whether this is the GNU C extension. 756 bool GNUCompatible = 757 Context.typesAreCompatible(OldProto->getResultType(), 758 NewProto->getResultType()) && 759 (OldProto->isVariadic() == NewProto->isVariadic()); 760 for (unsigned Idx = 0, End = Old->getNumParams(); 761 GNUCompatible && Idx != End; ++Idx) { 762 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 763 ParmVarDecl *NewParm = New->getParamDecl(Idx); 764 if (Context.typesAreCompatible(OldParm->getType(), 765 NewProto->getArgType(Idx))) { 766 ArgTypes.push_back(NewParm->getType()); 767 } else if (Context.typesAreCompatible(OldParm->getType(), 768 NewParm->getType())) { 769 GNUCompatibleParamWarning Warn 770 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 771 Warnings.push_back(Warn); 772 ArgTypes.push_back(NewParm->getType()); 773 } else 774 GNUCompatible = false; 775 } 776 777 if (GNUCompatible) { 778 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 779 Diag(Warnings[Warn].NewParm->getLocation(), 780 diag::ext_param_promoted_not_compatible_with_prototype) 781 << Warnings[Warn].PromotedType 782 << Warnings[Warn].OldParm->getType(); 783 Diag(Warnings[Warn].OldParm->getLocation(), 784 diag::note_previous_declaration); 785 } 786 787 New->setType(Context.getFunctionType(NewProto->getResultType(), 788 &ArgTypes[0], ArgTypes.size(), 789 NewProto->isVariadic(), 790 NewProto->getTypeQuals())); 791 return MergeCompatibleFunctionDecls(New, Old); 792 } 793 794 // Fall through to diagnose conflicting types. 795 } 796 797 // A function that has already been declared has been redeclared or defined 798 // with a different type- show appropriate diagnostic 799 if (unsigned BuiltinID = Old->getBuiltinID(Context)) { 800 // The user has declared a builtin function with an incompatible 801 // signature. 802 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 803 // The function the user is redeclaring is a library-defined 804 // function like 'malloc' or 'printf'. Warn about the 805 // redeclaration, then pretend that we don't know about this 806 // library built-in. 807 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 808 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 809 << Old << Old->getType(); 810 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 811 Old->setInvalidDecl(); 812 return false; 813 } 814 815 PrevDiag = diag::note_previous_builtin_declaration; 816 } 817 818 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 819 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 820 return true; 821} 822 823/// \brief Completes the merge of two function declarations that are 824/// known to be compatible. 825/// 826/// This routine handles the merging of attributes and other 827/// properties of function declarations form the old declaration to 828/// the new declaration, once we know that New is in fact a 829/// redeclaration of Old. 830/// 831/// \returns false 832bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 833 // Merge the attributes 834 MergeAttributes(New, Old, Context); 835 836 // Merge the storage class. 837 New->setStorageClass(Old->getStorageClass()); 838 839 // FIXME: need to implement inline semantics 840 841 // Merge "pure" flag. 842 if (Old->isPure()) 843 New->setPure(); 844 845 // Merge the "deleted" flag. 846 if (Old->isDeleted()) 847 New->setDeleted(); 848 849 if (getLangOptions().CPlusPlus) 850 return MergeCXXFunctionDecl(New, Old); 851 852 return false; 853} 854 855/// MergeVarDecl - We just parsed a variable 'New' which has the same name 856/// and scope as a previous declaration 'Old'. Figure out how to resolve this 857/// situation, merging decls or emitting diagnostics as appropriate. 858/// 859/// Tentative definition rules (C99 6.9.2p2) are checked by 860/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 861/// definitions here, since the initializer hasn't been attached. 862/// 863bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 864 // Verify the old decl was also a variable. 865 VarDecl *Old = dyn_cast<VarDecl>(OldD); 866 if (!Old) { 867 Diag(New->getLocation(), diag::err_redefinition_different_kind) 868 << New->getDeclName(); 869 Diag(OldD->getLocation(), diag::note_previous_definition); 870 return true; 871 } 872 873 MergeAttributes(New, Old, Context); 874 875 // Merge the types 876 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType()); 877 if (MergedT.isNull()) { 878 Diag(New->getLocation(), diag::err_redefinition_different_type) 879 << New->getDeclName(); 880 Diag(Old->getLocation(), diag::note_previous_definition); 881 return true; 882 } 883 New->setType(MergedT); 884 885 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 886 if (New->getStorageClass() == VarDecl::Static && 887 (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) { 888 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 889 Diag(Old->getLocation(), diag::note_previous_definition); 890 return true; 891 } 892 // C99 6.2.2p4: 893 // For an identifier declared with the storage-class specifier 894 // extern in a scope in which a prior declaration of that 895 // identifier is visible,23) if the prior declaration specifies 896 // internal or external linkage, the linkage of the identifier at 897 // the later declaration is the same as the linkage specified at 898 // the prior declaration. If no prior declaration is visible, or 899 // if the prior declaration specifies no linkage, then the 900 // identifier has external linkage. 901 if (New->hasExternalStorage() && Old->hasLinkage()) 902 /* Okay */; 903 else if (New->getStorageClass() != VarDecl::Static && 904 Old->getStorageClass() == VarDecl::Static) { 905 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 906 Diag(Old->getLocation(), diag::note_previous_definition); 907 return true; 908 } 909 910 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 911 912 // FIXME: The test for external storage here seems wrong? We still 913 // need to check for mismatches. 914 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 915 // Don't complain about out-of-line definitions of static members. 916 !(Old->getLexicalDeclContext()->isRecord() && 917 !New->getLexicalDeclContext()->isRecord())) { 918 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 919 Diag(Old->getLocation(), diag::note_previous_definition); 920 return true; 921 } 922 923 // Keep a chain of previous declarations. 924 New->setPreviousDeclaration(Old); 925 926 return false; 927} 928 929/// CheckParmsForFunctionDef - Check that the parameters of the given 930/// function are appropriate for the definition of a function. This 931/// takes care of any checks that cannot be performed on the 932/// declaration itself, e.g., that the types of each of the function 933/// parameters are complete. 934bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 935 bool HasInvalidParm = false; 936 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 937 ParmVarDecl *Param = FD->getParamDecl(p); 938 939 // C99 6.7.5.3p4: the parameters in a parameter type list in a 940 // function declarator that is part of a function definition of 941 // that function shall not have incomplete type. 942 // 943 // This is also C++ [dcl.fct]p6. 944 if (!Param->isInvalidDecl() && 945 RequireCompleteType(Param->getLocation(), Param->getType(), 946 diag::err_typecheck_decl_incomplete_type)) { 947 Param->setInvalidDecl(); 948 HasInvalidParm = true; 949 } 950 951 // C99 6.9.1p5: If the declarator includes a parameter type list, the 952 // declaration of each parameter shall include an identifier. 953 if (Param->getIdentifier() == 0 && 954 !Param->isImplicit() && 955 !getLangOptions().CPlusPlus) 956 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 957 } 958 959 return HasInvalidParm; 960} 961 962/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 963/// no declarator (e.g. "struct foo;") is parsed. 964Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 965 // FIXME: Error on auto/register at file scope 966 // FIXME: Error on inline/virtual/explicit 967 // FIXME: Error on invalid restrict 968 // FIXME: Warn on useless const/volatile 969 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable 970 // FIXME: Warn on useless attributes 971 972 TagDecl *Tag = 0; 973 if (DS.getTypeSpecType() == DeclSpec::TST_class || 974 DS.getTypeSpecType() == DeclSpec::TST_struct || 975 DS.getTypeSpecType() == DeclSpec::TST_union || 976 DS.getTypeSpecType() == DeclSpec::TST_enum) 977 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 978 979 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 980 if (!Record->getDeclName() && Record->isDefinition() && 981 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 982 if (getLangOptions().CPlusPlus || 983 Record->getDeclContext()->isRecord()) 984 return BuildAnonymousStructOrUnion(S, DS, Record); 985 986 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 987 << DS.getSourceRange(); 988 } 989 990 // Microsoft allows unnamed struct/union fields. Don't complain 991 // about them. 992 // FIXME: Should we support Microsoft's extensions in this area? 993 if (Record->getDeclName() && getLangOptions().Microsoft) 994 return DeclPtrTy::make(Tag); 995 } 996 997 if (!DS.isMissingDeclaratorOk() && 998 DS.getTypeSpecType() != DeclSpec::TST_error) { 999 // Warn about typedefs of enums without names, since this is an 1000 // extension in both Microsoft an GNU. 1001 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 1002 Tag && isa<EnumDecl>(Tag)) { 1003 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 1004 << DS.getSourceRange(); 1005 return DeclPtrTy::make(Tag); 1006 } 1007 1008 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 1009 << DS.getSourceRange(); 1010 return DeclPtrTy(); 1011 } 1012 1013 return DeclPtrTy::make(Tag); 1014} 1015 1016/// InjectAnonymousStructOrUnionMembers - Inject the members of the 1017/// anonymous struct or union AnonRecord into the owning context Owner 1018/// and scope S. This routine will be invoked just after we realize 1019/// that an unnamed union or struct is actually an anonymous union or 1020/// struct, e.g., 1021/// 1022/// @code 1023/// union { 1024/// int i; 1025/// float f; 1026/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 1027/// // f into the surrounding scope.x 1028/// @endcode 1029/// 1030/// This routine is recursive, injecting the names of nested anonymous 1031/// structs/unions into the owning context and scope as well. 1032bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner, 1033 RecordDecl *AnonRecord) { 1034 bool Invalid = false; 1035 for (RecordDecl::field_iterator F = AnonRecord->field_begin(Context), 1036 FEnd = AnonRecord->field_end(Context); 1037 F != FEnd; ++F) { 1038 if ((*F)->getDeclName()) { 1039 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(), 1040 LookupOrdinaryName, true); 1041 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 1042 // C++ [class.union]p2: 1043 // The names of the members of an anonymous union shall be 1044 // distinct from the names of any other entity in the 1045 // scope in which the anonymous union is declared. 1046 unsigned diagKind 1047 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl 1048 : diag::err_anonymous_struct_member_redecl; 1049 Diag((*F)->getLocation(), diagKind) 1050 << (*F)->getDeclName(); 1051 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 1052 Invalid = true; 1053 } else { 1054 // C++ [class.union]p2: 1055 // For the purpose of name lookup, after the anonymous union 1056 // definition, the members of the anonymous union are 1057 // considered to have been defined in the scope in which the 1058 // anonymous union is declared. 1059 Owner->makeDeclVisibleInContext(Context, *F); 1060 S->AddDecl(DeclPtrTy::make(*F)); 1061 IdResolver.AddDecl(*F); 1062 } 1063 } else if (const RecordType *InnerRecordType 1064 = (*F)->getType()->getAsRecordType()) { 1065 RecordDecl *InnerRecord = InnerRecordType->getDecl(); 1066 if (InnerRecord->isAnonymousStructOrUnion()) 1067 Invalid = Invalid || 1068 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord); 1069 } 1070 } 1071 1072 return Invalid; 1073} 1074 1075/// ActOnAnonymousStructOrUnion - Handle the declaration of an 1076/// anonymous structure or union. Anonymous unions are a C++ feature 1077/// (C++ [class.union]) and a GNU C extension; anonymous structures 1078/// are a GNU C and GNU C++ extension. 1079Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1080 RecordDecl *Record) { 1081 DeclContext *Owner = Record->getDeclContext(); 1082 1083 // Diagnose whether this anonymous struct/union is an extension. 1084 if (Record->isUnion() && !getLangOptions().CPlusPlus) 1085 Diag(Record->getLocation(), diag::ext_anonymous_union); 1086 else if (!Record->isUnion()) 1087 Diag(Record->getLocation(), diag::ext_anonymous_struct); 1088 1089 // C and C++ require different kinds of checks for anonymous 1090 // structs/unions. 1091 bool Invalid = false; 1092 if (getLangOptions().CPlusPlus) { 1093 const char* PrevSpec = 0; 1094 // C++ [class.union]p3: 1095 // Anonymous unions declared in a named namespace or in the 1096 // global namespace shall be declared static. 1097 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 1098 (isa<TranslationUnitDecl>(Owner) || 1099 (isa<NamespaceDecl>(Owner) && 1100 cast<NamespaceDecl>(Owner)->getDeclName()))) { 1101 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 1102 Invalid = true; 1103 1104 // Recover by adding 'static'. 1105 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec); 1106 } 1107 // C++ [class.union]p3: 1108 // A storage class is not allowed in a declaration of an 1109 // anonymous union in a class scope. 1110 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1111 isa<RecordDecl>(Owner)) { 1112 Diag(DS.getStorageClassSpecLoc(), 1113 diag::err_anonymous_union_with_storage_spec); 1114 Invalid = true; 1115 1116 // Recover by removing the storage specifier. 1117 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 1118 PrevSpec); 1119 } 1120 1121 // C++ [class.union]p2: 1122 // The member-specification of an anonymous union shall only 1123 // define non-static data members. [Note: nested types and 1124 // functions cannot be declared within an anonymous union. ] 1125 for (DeclContext::decl_iterator Mem = Record->decls_begin(Context), 1126 MemEnd = Record->decls_end(Context); 1127 Mem != MemEnd; ++Mem) { 1128 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 1129 // C++ [class.union]p3: 1130 // An anonymous union shall not have private or protected 1131 // members (clause 11). 1132 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) { 1133 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 1134 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 1135 Invalid = true; 1136 } 1137 } else if ((*Mem)->isImplicit()) { 1138 // Any implicit members are fine. 1139 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 1140 // This is a type that showed up in an 1141 // elaborated-type-specifier inside the anonymous struct or 1142 // union, but which actually declares a type outside of the 1143 // anonymous struct or union. It's okay. 1144 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 1145 if (!MemRecord->isAnonymousStructOrUnion() && 1146 MemRecord->getDeclName()) { 1147 // This is a nested type declaration. 1148 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 1149 << (int)Record->isUnion(); 1150 Invalid = true; 1151 } 1152 } else { 1153 // We have something that isn't a non-static data 1154 // member. Complain about it. 1155 unsigned DK = diag::err_anonymous_record_bad_member; 1156 if (isa<TypeDecl>(*Mem)) 1157 DK = diag::err_anonymous_record_with_type; 1158 else if (isa<FunctionDecl>(*Mem)) 1159 DK = diag::err_anonymous_record_with_function; 1160 else if (isa<VarDecl>(*Mem)) 1161 DK = diag::err_anonymous_record_with_static; 1162 Diag((*Mem)->getLocation(), DK) 1163 << (int)Record->isUnion(); 1164 Invalid = true; 1165 } 1166 } 1167 } 1168 1169 if (!Record->isUnion() && !Owner->isRecord()) { 1170 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 1171 << (int)getLangOptions().CPlusPlus; 1172 Invalid = true; 1173 } 1174 1175 // Create a declaration for this anonymous struct/union. 1176 NamedDecl *Anon = 0; 1177 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 1178 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 1179 /*IdentifierInfo=*/0, 1180 Context.getTypeDeclType(Record), 1181 /*BitWidth=*/0, /*Mutable=*/false); 1182 Anon->setAccess(AS_public); 1183 if (getLangOptions().CPlusPlus) 1184 FieldCollector->Add(cast<FieldDecl>(Anon)); 1185 } else { 1186 VarDecl::StorageClass SC; 1187 switch (DS.getStorageClassSpec()) { 1188 default: assert(0 && "Unknown storage class!"); 1189 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1190 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1191 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1192 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1193 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1194 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1195 case DeclSpec::SCS_mutable: 1196 // mutable can only appear on non-static class members, so it's always 1197 // an error here 1198 Diag(Record->getLocation(), diag::err_mutable_nonmember); 1199 Invalid = true; 1200 SC = VarDecl::None; 1201 break; 1202 } 1203 1204 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 1205 /*IdentifierInfo=*/0, 1206 Context.getTypeDeclType(Record), 1207 SC, DS.getSourceRange().getBegin()); 1208 } 1209 Anon->setImplicit(); 1210 1211 // Add the anonymous struct/union object to the current 1212 // context. We'll be referencing this object when we refer to one of 1213 // its members. 1214 Owner->addDecl(Context, Anon); 1215 1216 // Inject the members of the anonymous struct/union into the owning 1217 // context and into the identifier resolver chain for name lookup 1218 // purposes. 1219 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record)) 1220 Invalid = true; 1221 1222 // Mark this as an anonymous struct/union type. Note that we do not 1223 // do this until after we have already checked and injected the 1224 // members of this anonymous struct/union type, because otherwise 1225 // the members could be injected twice: once by DeclContext when it 1226 // builds its lookup table, and once by 1227 // InjectAnonymousStructOrUnionMembers. 1228 Record->setAnonymousStructOrUnion(true); 1229 1230 if (Invalid) 1231 Anon->setInvalidDecl(); 1232 1233 return DeclPtrTy::make(Anon); 1234} 1235 1236 1237/// GetNameForDeclarator - Determine the full declaration name for the 1238/// given Declarator. 1239DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 1240 switch (D.getKind()) { 1241 case Declarator::DK_Abstract: 1242 assert(D.getIdentifier() == 0 && "abstract declarators have no name"); 1243 return DeclarationName(); 1244 1245 case Declarator::DK_Normal: 1246 assert (D.getIdentifier() != 0 && "normal declarators have an identifier"); 1247 return DeclarationName(D.getIdentifier()); 1248 1249 case Declarator::DK_Constructor: { 1250 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1251 Ty = Context.getCanonicalType(Ty); 1252 return Context.DeclarationNames.getCXXConstructorName(Ty); 1253 } 1254 1255 case Declarator::DK_Destructor: { 1256 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1257 Ty = Context.getCanonicalType(Ty); 1258 return Context.DeclarationNames.getCXXDestructorName(Ty); 1259 } 1260 1261 case Declarator::DK_Conversion: { 1262 // FIXME: We'd like to keep the non-canonical type for diagnostics! 1263 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1264 Ty = Context.getCanonicalType(Ty); 1265 return Context.DeclarationNames.getCXXConversionFunctionName(Ty); 1266 } 1267 1268 case Declarator::DK_Operator: 1269 assert(D.getIdentifier() == 0 && "operator names have no identifier"); 1270 return Context.DeclarationNames.getCXXOperatorName( 1271 D.getOverloadedOperator()); 1272 } 1273 1274 assert(false && "Unknown name kind"); 1275 return DeclarationName(); 1276} 1277 1278/// isNearlyMatchingFunction - Determine whether the C++ functions 1279/// Declaration and Definition are "nearly" matching. This heuristic 1280/// is used to improve diagnostics in the case where an out-of-line 1281/// function definition doesn't match any declaration within 1282/// the class or namespace. 1283static bool isNearlyMatchingFunction(ASTContext &Context, 1284 FunctionDecl *Declaration, 1285 FunctionDecl *Definition) { 1286 if (Declaration->param_size() != Definition->param_size()) 1287 return false; 1288 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 1289 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 1290 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 1291 1292 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType()); 1293 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType()); 1294 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType()) 1295 return false; 1296 } 1297 1298 return true; 1299} 1300 1301Sema::DeclPtrTy 1302Sema::ActOnDeclarator(Scope *S, Declarator &D, bool IsFunctionDefinition) { 1303 DeclarationName Name = GetNameForDeclarator(D); 1304 1305 // All of these full declarators require an identifier. If it doesn't have 1306 // one, the ParsedFreeStandingDeclSpec action should be used. 1307 if (!Name) { 1308 if (!D.getInvalidType()) // Reject this if we think it is valid. 1309 Diag(D.getDeclSpec().getSourceRange().getBegin(), 1310 diag::err_declarator_need_ident) 1311 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 1312 return DeclPtrTy(); 1313 } 1314 1315 // The scope passed in may not be a decl scope. Zip up the scope tree until 1316 // we find one that is. 1317 while ((S->getFlags() & Scope::DeclScope) == 0 || 1318 (S->getFlags() & Scope::TemplateParamScope) != 0) 1319 S = S->getParent(); 1320 1321 DeclContext *DC; 1322 NamedDecl *PrevDecl; 1323 NamedDecl *New; 1324 bool InvalidDecl = false; 1325 1326 QualType R = GetTypeForDeclarator(D, S); 1327 if (R.isNull()) { 1328 InvalidDecl = true; 1329 R = Context.IntTy; 1330 if (IsFunctionDefinition) // int(...) 1331 R = Context.getFunctionType(R, 0, 0, true, 0); 1332 1333 } 1334 1335 // See if this is a redefinition of a variable in the same scope. 1336 if (D.getCXXScopeSpec().isInvalid()) { 1337 DC = CurContext; 1338 PrevDecl = 0; 1339 InvalidDecl = true; 1340 } else if (!D.getCXXScopeSpec().isSet()) { 1341 LookupNameKind NameKind = LookupOrdinaryName; 1342 1343 // If the declaration we're planning to build will be a function 1344 // or object with linkage, then look for another declaration with 1345 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 1346 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1347 /* Do nothing*/; 1348 else if (R->isFunctionType()) { 1349 if (CurContext->isFunctionOrMethod()) 1350 NameKind = LookupRedeclarationWithLinkage; 1351 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 1352 NameKind = LookupRedeclarationWithLinkage; 1353 1354 DC = CurContext; 1355 PrevDecl = LookupName(S, Name, NameKind, true, 1356 D.getDeclSpec().getStorageClassSpec() != 1357 DeclSpec::SCS_static, 1358 D.getIdentifierLoc()); 1359 } else { // Something like "int foo::x;" 1360 DC = computeDeclContext(D.getCXXScopeSpec()); 1361 // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ? 1362 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true); 1363 1364 // C++ 7.3.1.2p2: 1365 // Members (including explicit specializations of templates) of a named 1366 // namespace can also be defined outside that namespace by explicit 1367 // qualification of the name being defined, provided that the entity being 1368 // defined was already declared in the namespace and the definition appears 1369 // after the point of declaration in a namespace that encloses the 1370 // declarations namespace. 1371 // 1372 // Note that we only check the context at this point. We don't yet 1373 // have enough information to make sure that PrevDecl is actually 1374 // the declaration we want to match. For example, given: 1375 // 1376 // class X { 1377 // void f(); 1378 // void f(float); 1379 // }; 1380 // 1381 // void X::f(int) { } // ill-formed 1382 // 1383 // In this case, PrevDecl will point to the overload set 1384 // containing the two f's declared in X, but neither of them 1385 // matches. 1386 1387 // First check whether we named the global scope. 1388 if (isa<TranslationUnitDecl>(DC)) { 1389 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 1390 << Name << D.getCXXScopeSpec().getRange(); 1391 } else if (!CurContext->Encloses(DC)) { 1392 // The qualifying scope doesn't enclose the original declaration. 1393 // Emit diagnostic based on current scope. 1394 SourceLocation L = D.getIdentifierLoc(); 1395 SourceRange R = D.getCXXScopeSpec().getRange(); 1396 if (isa<FunctionDecl>(CurContext)) 1397 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 1398 else 1399 Diag(L, diag::err_invalid_declarator_scope) 1400 << Name << cast<NamedDecl>(DC) << R; 1401 InvalidDecl = true; 1402 } 1403 } 1404 1405 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1406 // Maybe we will complain about the shadowed template parameter. 1407 InvalidDecl = InvalidDecl 1408 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 1409 // Just pretend that we didn't see the previous declaration. 1410 PrevDecl = 0; 1411 } 1412 1413 // In C++, the previous declaration we find might be a tag type 1414 // (class or enum). In this case, the new declaration will hide the 1415 // tag type. Note that this does does not apply if we're declaring a 1416 // typedef (C++ [dcl.typedef]p4). 1417 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag && 1418 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 1419 PrevDecl = 0; 1420 1421 bool Redeclaration = false; 1422 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 1423 New = ActOnTypedefDeclarator(S, D, DC, R, PrevDecl, 1424 InvalidDecl, Redeclaration); 1425 } else if (R->isFunctionType()) { 1426 New = ActOnFunctionDeclarator(S, D, DC, R, PrevDecl, 1427 IsFunctionDefinition, InvalidDecl, 1428 Redeclaration); 1429 } else { 1430 New = ActOnVariableDeclarator(S, D, DC, R, PrevDecl, 1431 InvalidDecl, Redeclaration); 1432 } 1433 1434 if (New == 0) 1435 return DeclPtrTy(); 1436 1437 // If this has an identifier and is not an invalid redeclaration, 1438 // add it to the scope stack. 1439 if (Name && !(Redeclaration && InvalidDecl)) 1440 PushOnScopeChains(New, S); 1441 // If any semantic error occurred, mark the decl as invalid. 1442 if (D.getInvalidType() || InvalidDecl) 1443 New->setInvalidDecl(); 1444 1445 return DeclPtrTy::make(New); 1446} 1447 1448/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 1449/// types into constant array types in certain situations which would otherwise 1450/// be errors (for GCC compatibility). 1451static QualType TryToFixInvalidVariablyModifiedType(QualType T, 1452 ASTContext &Context, 1453 bool &SizeIsNegative) { 1454 // This method tries to turn a variable array into a constant 1455 // array even when the size isn't an ICE. This is necessary 1456 // for compatibility with code that depends on gcc's buggy 1457 // constant expression folding, like struct {char x[(int)(char*)2];} 1458 SizeIsNegative = false; 1459 1460 if (const PointerType* PTy = dyn_cast<PointerType>(T)) { 1461 QualType Pointee = PTy->getPointeeType(); 1462 QualType FixedType = 1463 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative); 1464 if (FixedType.isNull()) return FixedType; 1465 FixedType = Context.getPointerType(FixedType); 1466 FixedType.setCVRQualifiers(T.getCVRQualifiers()); 1467 return FixedType; 1468 } 1469 1470 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 1471 if (!VLATy) 1472 return QualType(); 1473 // FIXME: We should probably handle this case 1474 if (VLATy->getElementType()->isVariablyModifiedType()) 1475 return QualType(); 1476 1477 Expr::EvalResult EvalResult; 1478 if (!VLATy->getSizeExpr() || 1479 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 1480 !EvalResult.Val.isInt()) 1481 return QualType(); 1482 1483 llvm::APSInt &Res = EvalResult.Val.getInt(); 1484 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 1485 return Context.getConstantArrayType(VLATy->getElementType(), 1486 Res, ArrayType::Normal, 0); 1487 1488 SizeIsNegative = true; 1489 return QualType(); 1490} 1491 1492/// \brief Register the given locally-scoped external C declaration so 1493/// that it can be found later for redeclarations 1494void 1495Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl, 1496 Scope *S) { 1497 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 1498 "Decl is not a locally-scoped decl!"); 1499 // Note that we have a locally-scoped external with this name. 1500 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 1501 1502 if (!PrevDecl) 1503 return; 1504 1505 // If there was a previous declaration of this variable, it may be 1506 // in our identifier chain. Update the identifier chain with the new 1507 // declaration. 1508 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 1509 // The previous declaration was found on the identifer resolver 1510 // chain, so remove it from its scope. 1511 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl))) 1512 S = S->getParent(); 1513 1514 if (S) 1515 S->RemoveDecl(DeclPtrTy::make(PrevDecl)); 1516 } 1517} 1518 1519/// \brief Diagnose function specifiers on a declaration of an identifier that 1520/// does not identify a function. 1521void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 1522 // FIXME: We should probably indicate the identifier in question to avoid 1523 // confusion for constructs like "inline int a(), b;" 1524 if (D.getDeclSpec().isInlineSpecified()) 1525 Diag(D.getDeclSpec().getInlineSpecLoc(), 1526 diag::err_inline_non_function); 1527 1528 if (D.getDeclSpec().isVirtualSpecified()) 1529 Diag(D.getDeclSpec().getVirtualSpecLoc(), 1530 diag::err_virtual_non_function); 1531 1532 if (D.getDeclSpec().isExplicitSpecified()) 1533 Diag(D.getDeclSpec().getExplicitSpecLoc(), 1534 diag::err_explicit_non_function); 1535} 1536 1537NamedDecl* 1538Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1539 QualType R, Decl* PrevDecl, bool& InvalidDecl, 1540 bool &Redeclaration) { 1541 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 1542 if (D.getCXXScopeSpec().isSet()) { 1543 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 1544 << D.getCXXScopeSpec().getRange(); 1545 InvalidDecl = true; 1546 // Pretend we didn't see the scope specifier. 1547 DC = 0; 1548 } 1549 1550 if (getLangOptions().CPlusPlus) { 1551 // Check that there are no default arguments (C++ only). 1552 CheckExtraCXXDefaultArguments(D); 1553 } 1554 1555 DiagnoseFunctionSpecifiers(D); 1556 1557 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R); 1558 if (!NewTD) return 0; 1559 1560 // Handle attributes prior to checking for duplicates in MergeVarDecl 1561 ProcessDeclAttributes(NewTD, D); 1562 // Merge the decl with the existing one if appropriate. If the decl is 1563 // in an outer scope, it isn't the same thing. 1564 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1565 Redeclaration = true; 1566 if (MergeTypeDefDecl(NewTD, PrevDecl)) 1567 InvalidDecl = true; 1568 } 1569 1570 if (S->getFnParent() == 0) { 1571 QualType T = NewTD->getUnderlyingType(); 1572 // C99 6.7.7p2: If a typedef name specifies a variably modified type 1573 // then it shall have block scope. 1574 if (T->isVariablyModifiedType()) { 1575 bool SizeIsNegative; 1576 QualType FixedTy = 1577 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 1578 if (!FixedTy.isNull()) { 1579 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size); 1580 NewTD->setUnderlyingType(FixedTy); 1581 } else { 1582 if (SizeIsNegative) 1583 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size); 1584 else if (T->isVariableArrayType()) 1585 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 1586 else 1587 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 1588 InvalidDecl = true; 1589 } 1590 } 1591 } 1592 return NewTD; 1593} 1594 1595/// \brief Determines whether the given declaration is an out-of-scope 1596/// previous declaration. 1597/// 1598/// This routine should be invoked when name lookup has found a 1599/// previous declaration (PrevDecl) that is not in the scope where a 1600/// new declaration by the same name is being introduced. If the new 1601/// declaration occurs in a local scope, previous declarations with 1602/// linkage may still be considered previous declarations (C99 1603/// 6.2.2p4-5, C++ [basic.link]p6). 1604/// 1605/// \param PrevDecl the previous declaration found by name 1606/// lookup 1607/// 1608/// \param DC the context in which the new declaration is being 1609/// declared. 1610/// 1611/// \returns true if PrevDecl is an out-of-scope previous declaration 1612/// for a new delcaration with the same name. 1613static bool 1614isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 1615 ASTContext &Context) { 1616 if (!PrevDecl) 1617 return 0; 1618 1619 // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which 1620 // case we need to check each of the overloaded functions. 1621 if (!PrevDecl->hasLinkage()) 1622 return false; 1623 1624 if (Context.getLangOptions().CPlusPlus) { 1625 // C++ [basic.link]p6: 1626 // If there is a visible declaration of an entity with linkage 1627 // having the same name and type, ignoring entities declared 1628 // outside the innermost enclosing namespace scope, the block 1629 // scope declaration declares that same entity and receives the 1630 // linkage of the previous declaration. 1631 DeclContext *OuterContext = DC->getLookupContext(); 1632 if (!OuterContext->isFunctionOrMethod()) 1633 // This rule only applies to block-scope declarations. 1634 return false; 1635 else { 1636 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 1637 if (PrevOuterContext->isRecord()) 1638 // We found a member function: ignore it. 1639 return false; 1640 else { 1641 // Find the innermost enclosing namespace for the new and 1642 // previous declarations. 1643 while (!OuterContext->isFileContext()) 1644 OuterContext = OuterContext->getParent(); 1645 while (!PrevOuterContext->isFileContext()) 1646 PrevOuterContext = PrevOuterContext->getParent(); 1647 1648 // The previous declaration is in a different namespace, so it 1649 // isn't the same function. 1650 if (OuterContext->getPrimaryContext() != 1651 PrevOuterContext->getPrimaryContext()) 1652 return false; 1653 } 1654 } 1655 } 1656 1657 return true; 1658} 1659 1660NamedDecl* 1661Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1662 QualType R,NamedDecl* PrevDecl, bool& InvalidDecl, 1663 bool &Redeclaration) { 1664 DeclarationName Name = GetNameForDeclarator(D); 1665 1666 // Check that there are no default arguments (C++ only). 1667 if (getLangOptions().CPlusPlus) 1668 CheckExtraCXXDefaultArguments(D); 1669 1670 VarDecl *NewVD; 1671 VarDecl::StorageClass SC; 1672 switch (D.getDeclSpec().getStorageClassSpec()) { 1673 default: assert(0 && "Unknown storage class!"); 1674 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1675 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1676 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1677 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1678 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1679 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1680 case DeclSpec::SCS_mutable: 1681 // mutable can only appear on non-static class members, so it's always 1682 // an error here 1683 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 1684 InvalidDecl = true; 1685 SC = VarDecl::None; 1686 break; 1687 } 1688 1689 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1690 if (!II) { 1691 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 1692 << Name.getAsString(); 1693 return 0; 1694 } 1695 1696 DiagnoseFunctionSpecifiers(D); 1697 1698 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 1699 if (!DC->isRecord() && S->getFnParent() == 0) { 1700 // C99 6.9p2: The storage-class specifiers auto and register shall not 1701 // appear in the declaration specifiers in an external declaration. 1702 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 1703 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 1704 InvalidDecl = true; 1705 } 1706 } 1707 if (DC->isRecord() && !CurContext->isRecord()) { 1708 // This is an out-of-line definition of a static data member. 1709 if (SC == VarDecl::Static) { 1710 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 1711 diag::err_static_out_of_line) 1712 << CodeModificationHint::CreateRemoval( 1713 SourceRange(D.getDeclSpec().getStorageClassSpecLoc())); 1714 } else if (SC == VarDecl::None) 1715 SC = VarDecl::Static; 1716 } 1717 1718 // The variable can not 1719 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 1720 II, R, SC, 1721 // FIXME: Move to DeclGroup... 1722 D.getDeclSpec().getSourceRange().getBegin()); 1723 NewVD->setThreadSpecified(ThreadSpecified); 1724 1725 // Set the lexical context. If the declarator has a C++ scope specifier, the 1726 // lexical context will be different from the semantic context. 1727 NewVD->setLexicalDeclContext(CurContext); 1728 1729 // Handle attributes prior to checking for duplicates in MergeVarDecl 1730 ProcessDeclAttributes(NewVD, D); 1731 1732 // Handle GNU asm-label extension (encoded as an attribute). 1733 if (Expr *E = (Expr*) D.getAsmLabel()) { 1734 // The parser guarantees this is a string. 1735 StringLiteral *SE = cast<StringLiteral>(E); 1736 NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(), 1737 SE->getByteLength()))); 1738 } 1739 1740 // If name lookup finds a previous declaration that is not in the 1741 // same scope as the new declaration, this may still be an 1742 // acceptable redeclaration. 1743 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) && 1744 !(NewVD->hasLinkage() && 1745 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context))) 1746 PrevDecl = 0; 1747 1748 // Merge the decl with the existing one if appropriate. 1749 if (PrevDecl) { 1750 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) { 1751 // The user tried to define a non-static data member 1752 // out-of-line (C++ [dcl.meaning]p1). 1753 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 1754 << D.getCXXScopeSpec().getRange(); 1755 PrevDecl = 0; 1756 InvalidDecl = true; 1757 } 1758 } else if (D.getCXXScopeSpec().isSet()) { 1759 // No previous declaration in the qualifying scope. 1760 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member) 1761 << Name << D.getCXXScopeSpec().getRange(); 1762 InvalidDecl = true; 1763 } 1764 1765 if (CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration)) 1766 InvalidDecl = true; 1767 1768 // If this is a locally-scoped extern C variable, update the map of 1769 // such variables. 1770 if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) && 1771 !InvalidDecl) 1772 RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S); 1773 1774 return NewVD; 1775} 1776 1777/// \brief Perform semantic checking on a newly-created variable 1778/// declaration. 1779/// 1780/// This routine performs all of the type-checking required for a 1781/// variable declaration once it has been build. It is used both to 1782/// check variables after they have been parsed and their declarators 1783/// have been translated into a declaration, and to check 1784/// 1785/// \returns true if an error was encountered, false otherwise. 1786bool Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl, 1787 bool &Redeclaration) { 1788 bool Invalid = false; 1789 1790 QualType T = NewVD->getType(); 1791 1792 if (T->isObjCInterfaceType()) { 1793 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 1794 Invalid = true; 1795 } 1796 1797 // The variable can not have an abstract class type. 1798 if (RequireNonAbstractType(NewVD->getLocation(), T, 1799 diag::err_abstract_type_in_decl, 1800 AbstractVariableType)) 1801 Invalid = true; 1802 1803 // Emit an error if an address space was applied to decl with local storage. 1804 // This includes arrays of objects with address space qualifiers, but not 1805 // automatic variables that point to other address spaces. 1806 // ISO/IEC TR 18037 S5.1.2 1807 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) { 1808 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 1809 Invalid = true; 1810 } 1811 1812 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 1813 && !NewVD->hasAttr<BlocksAttr>()) 1814 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 1815 1816 bool isIllegalVLA = T->isVariableArrayType() && NewVD->hasGlobalStorage(); 1817 bool isIllegalVM = T->isVariablyModifiedType() && NewVD->hasLinkage(); 1818 if (isIllegalVLA || isIllegalVM) { 1819 bool SizeIsNegative; 1820 QualType FixedTy = 1821 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 1822 if (!FixedTy.isNull()) { 1823 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 1824 NewVD->setType(FixedTy); 1825 } else if (T->isVariableArrayType()) { 1826 Invalid = true; 1827 1828 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 1829 // FIXME: This won't give the correct result for 1830 // int a[10][n]; 1831 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 1832 1833 if (NewVD->isFileVarDecl()) 1834 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 1835 << SizeRange; 1836 else if (NewVD->getStorageClass() == VarDecl::Static) 1837 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 1838 << SizeRange; 1839 else 1840 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 1841 << SizeRange; 1842 } else { 1843 Invalid = true; 1844 1845 if (NewVD->isFileVarDecl()) 1846 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 1847 else 1848 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 1849 } 1850 } 1851 1852 if (!PrevDecl && NewVD->isExternC(Context)) { 1853 // Since we did not find anything by this name and we're declaring 1854 // an extern "C" variable, look for a non-visible extern "C" 1855 // declaration with the same name. 1856 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 1857 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 1858 if (Pos != LocallyScopedExternalDecls.end()) 1859 PrevDecl = Pos->second; 1860 } 1861 1862 if (!Invalid && T->isVoidType() && !NewVD->hasExternalStorage()) { 1863 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 1864 << T; 1865 Invalid = true; 1866 } 1867 1868 if (PrevDecl) { 1869 Redeclaration = true; 1870 if (MergeVarDecl(NewVD, PrevDecl)) 1871 Invalid = true; 1872 } 1873 1874 return NewVD->isInvalidDecl() || Invalid; 1875} 1876 1877NamedDecl* 1878Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1879 QualType R, NamedDecl* PrevDecl, 1880 bool IsFunctionDefinition, 1881 bool& InvalidDecl, bool &Redeclaration) { 1882 assert(R.getTypePtr()->isFunctionType()); 1883 1884 DeclarationName Name = GetNameForDeclarator(D); 1885 FunctionDecl::StorageClass SC = FunctionDecl::None; 1886 switch (D.getDeclSpec().getStorageClassSpec()) { 1887 default: assert(0 && "Unknown storage class!"); 1888 case DeclSpec::SCS_auto: 1889 case DeclSpec::SCS_register: 1890 case DeclSpec::SCS_mutable: 1891 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 1892 diag::err_typecheck_sclass_func); 1893 InvalidDecl = true; 1894 break; 1895 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 1896 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 1897 case DeclSpec::SCS_static: { 1898 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 1899 // C99 6.7.1p5: 1900 // The declaration of an identifier for a function that has 1901 // block scope shall have no explicit storage-class specifier 1902 // other than extern 1903 // See also (C++ [dcl.stc]p4). 1904 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 1905 diag::err_static_block_func); 1906 SC = FunctionDecl::None; 1907 } else 1908 SC = FunctionDecl::Static; 1909 break; 1910 } 1911 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 1912 } 1913 1914 bool isInline = D.getDeclSpec().isInlineSpecified(); 1915 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1916 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 1917 1918 // Check that the return type is not an abstract class type. 1919 // For record types, this is done by the AbstractClassUsageDiagnoser once 1920 // the class has been completely parsed. 1921 if (!DC->isRecord() && 1922 RequireNonAbstractType(D.getIdentifierLoc(), 1923 R->getAsFunctionType()->getResultType(), 1924 diag::err_abstract_type_in_decl, 1925 AbstractReturnType)) 1926 InvalidDecl = true; 1927 1928 // Do not allow returning a objc interface by-value. 1929 if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) { 1930 Diag(D.getIdentifierLoc(), 1931 diag::err_object_cannot_be_passed_returned_by_value) << 0 1932 << R->getAsFunctionType()->getResultType(); 1933 InvalidDecl = true; 1934 } 1935 1936 bool isVirtualOkay = false; 1937 FunctionDecl *NewFD; 1938 if (D.getKind() == Declarator::DK_Constructor) { 1939 // This is a C++ constructor declaration. 1940 assert(DC->isRecord() && 1941 "Constructors can only be declared in a member context"); 1942 1943 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC); 1944 1945 // Create the new declaration 1946 NewFD = CXXConstructorDecl::Create(Context, 1947 cast<CXXRecordDecl>(DC), 1948 D.getIdentifierLoc(), Name, R, 1949 isExplicit, isInline, 1950 /*isImplicitlyDeclared=*/false); 1951 1952 if (InvalidDecl) 1953 NewFD->setInvalidDecl(); 1954 } else if (D.getKind() == Declarator::DK_Destructor) { 1955 // This is a C++ destructor declaration. 1956 if (DC->isRecord()) { 1957 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC); 1958 1959 NewFD = CXXDestructorDecl::Create(Context, 1960 cast<CXXRecordDecl>(DC), 1961 D.getIdentifierLoc(), Name, R, 1962 isInline, 1963 /*isImplicitlyDeclared=*/false); 1964 1965 if (InvalidDecl) 1966 NewFD->setInvalidDecl(); 1967 1968 isVirtualOkay = true; 1969 } else { 1970 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 1971 1972 // Create a FunctionDecl to satisfy the function definition parsing 1973 // code path. 1974 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 1975 Name, R, SC, isInline, 1976 /*hasPrototype=*/true, 1977 // FIXME: Move to DeclGroup... 1978 D.getDeclSpec().getSourceRange().getBegin()); 1979 InvalidDecl = true; 1980 NewFD->setInvalidDecl(); 1981 } 1982 } else if (D.getKind() == Declarator::DK_Conversion) { 1983 if (!DC->isRecord()) { 1984 Diag(D.getIdentifierLoc(), 1985 diag::err_conv_function_not_member); 1986 return 0; 1987 } else { 1988 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC); 1989 1990 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 1991 D.getIdentifierLoc(), Name, R, 1992 isInline, isExplicit); 1993 1994 if (InvalidDecl) 1995 NewFD->setInvalidDecl(); 1996 1997 isVirtualOkay = true; 1998 } 1999 } else if (DC->isRecord()) { 2000 // This is a C++ method declaration. 2001 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 2002 D.getIdentifierLoc(), Name, R, 2003 (SC == FunctionDecl::Static), isInline); 2004 2005 isVirtualOkay = (SC != FunctionDecl::Static); 2006 } else { 2007 // Determine whether the function was written with a 2008 // prototype. This true when: 2009 // - we're in C++ (where every function has a prototype), 2010 // - there is a prototype in the declarator, or 2011 // - the type R of the function is some kind of typedef or other reference 2012 // to a type name (which eventually refers to a function type). 2013 bool HasPrototype = 2014 getLangOptions().CPlusPlus || 2015 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) || 2016 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 2017 2018 NewFD = FunctionDecl::Create(Context, DC, 2019 D.getIdentifierLoc(), 2020 Name, R, SC, isInline, HasPrototype, 2021 // FIXME: Move to DeclGroup... 2022 D.getDeclSpec().getSourceRange().getBegin()); 2023 } 2024 2025 // Set the lexical context. If the declarator has a C++ 2026 // scope specifier, the lexical context will be different 2027 // from the semantic context. 2028 NewFD->setLexicalDeclContext(CurContext); 2029 2030 // C++ [dcl.fct.spec]p5: 2031 // The virtual specifier shall only be used in declarations of 2032 // nonstatic class member functions that appear within a 2033 // member-specification of a class declaration; see 10.3. 2034 // 2035 // FIXME: Checking the 'virtual' specifier is not sufficient. A 2036 // function is also virtual if it overrides an already virtual 2037 // function. This is important to do here because it's part of the 2038 // declaration. 2039 if (isVirtual && !InvalidDecl) { 2040 if (!isVirtualOkay) { 2041 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2042 diag::err_virtual_non_function); 2043 } else if (!CurContext->isRecord()) { 2044 // 'virtual' was specified outside of the class. 2045 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) 2046 << CodeModificationHint::CreateRemoval( 2047 SourceRange(D.getDeclSpec().getVirtualSpecLoc())); 2048 } else { 2049 // Okay: Add virtual to the method. 2050 cast<CXXMethodDecl>(NewFD)->setVirtual(); 2051 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC); 2052 CurClass->setAggregate(false); 2053 CurClass->setPOD(false); 2054 CurClass->setPolymorphic(true); 2055 CurClass->setHasTrivialConstructor(false); 2056 } 2057 } 2058 2059 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) && 2060 !CurContext->isRecord()) { 2061 // C++ [class.static]p1: 2062 // A data or function member of a class may be declared static 2063 // in a class definition, in which case it is a static member of 2064 // the class. 2065 2066 // Complain about the 'static' specifier if it's on an out-of-line 2067 // member function definition. 2068 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2069 diag::err_static_out_of_line) 2070 << CodeModificationHint::CreateRemoval( 2071 SourceRange(D.getDeclSpec().getStorageClassSpecLoc())); 2072 } 2073 2074 // Handle GNU asm-label extension (encoded as an attribute). 2075 if (Expr *E = (Expr*) D.getAsmLabel()) { 2076 // The parser guarantees this is a string. 2077 StringLiteral *SE = cast<StringLiteral>(E); 2078 NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(), 2079 SE->getByteLength()))); 2080 } 2081 2082 // Copy the parameter declarations from the declarator D to 2083 // the function declaration NewFD, if they are available. 2084 if (D.getNumTypeObjects() > 0) { 2085 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2086 2087 // Create Decl objects for each parameter, adding them to the 2088 // FunctionDecl. 2089 llvm::SmallVector<ParmVarDecl*, 16> Params; 2090 2091 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 2092 // function that takes no arguments, not a function that takes a 2093 // single void argument. 2094 // We let through "const void" here because Sema::GetTypeForDeclarator 2095 // already checks for that case. 2096 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2097 FTI.ArgInfo[0].Param && 2098 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) { 2099 // empty arg list, don't push any params. 2100 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>(); 2101 2102 // In C++, the empty parameter-type-list must be spelled "void"; a 2103 // typedef of void is not permitted. 2104 if (getLangOptions().CPlusPlus && 2105 Param->getType().getUnqualifiedType() != Context.VoidTy) { 2106 Diag(Param->getLocation(), diag::err_param_typedef_of_void); 2107 } 2108 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 2109 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 2110 Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>()); 2111 } 2112 2113 NewFD->setParams(Context, &Params[0], Params.size()); 2114 } else if (R->getAsTypedefType()) { 2115 // When we're declaring a function with a typedef, as in the 2116 // following example, we'll need to synthesize (unnamed) 2117 // parameters for use in the declaration. 2118 // 2119 // @code 2120 // typedef void fn(int); 2121 // fn f; 2122 // @endcode 2123 const FunctionProtoType *FT = R->getAsFunctionProtoType(); 2124 if (!FT) { 2125 // This is a typedef of a function with no prototype, so we 2126 // don't need to do anything. 2127 } else if ((FT->getNumArgs() == 0) || 2128 (FT->getNumArgs() == 1 && !FT->isVariadic() && 2129 FT->getArgType(0)->isVoidType())) { 2130 // This is a zero-argument function. We don't need to do anything. 2131 } else { 2132 // Synthesize a parameter for each argument type. 2133 llvm::SmallVector<ParmVarDecl*, 16> Params; 2134 for (FunctionProtoType::arg_type_iterator ArgType = FT->arg_type_begin(); 2135 ArgType != FT->arg_type_end(); ++ArgType) { 2136 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, 2137 SourceLocation(), 0, 2138 *ArgType, VarDecl::None, 2139 0); 2140 Param->setImplicit(); 2141 Params.push_back(Param); 2142 } 2143 2144 NewFD->setParams(Context, &Params[0], Params.size()); 2145 } 2146 } 2147 2148 // If name lookup finds a previous declaration that is not in the 2149 // same scope as the new declaration, this may still be an 2150 // acceptable redeclaration. 2151 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) && 2152 !(NewFD->hasLinkage() && 2153 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context))) 2154 PrevDecl = 0; 2155 2156 // Perform semantic checking on the function declaration. 2157 bool OverloadableAttrRequired = false; // FIXME: HACK! 2158 if (CheckFunctionDeclaration(NewFD, PrevDecl, Redeclaration, 2159 /*FIXME:*/OverloadableAttrRequired)) 2160 InvalidDecl = true; 2161 2162 if (D.getCXXScopeSpec().isSet() && !InvalidDecl) { 2163 // An out-of-line member function declaration must also be a 2164 // definition (C++ [dcl.meaning]p1). 2165 if (!IsFunctionDefinition) { 2166 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration) 2167 << D.getCXXScopeSpec().getRange(); 2168 InvalidDecl = true; 2169 } else if (!Redeclaration) { 2170 // The user tried to provide an out-of-line definition for a 2171 // function that is a member of a class or namespace, but there 2172 // was no such member function declared (C++ [class.mfct]p2, 2173 // C++ [namespace.memdef]p2). For example: 2174 // 2175 // class X { 2176 // void f() const; 2177 // }; 2178 // 2179 // void X::f() { } // ill-formed 2180 // 2181 // Complain about this problem, and attempt to suggest close 2182 // matches (e.g., those that differ only in cv-qualifiers and 2183 // whether the parameter types are references). 2184 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 2185 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange(); 2186 InvalidDecl = true; 2187 2188 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName, 2189 true); 2190 assert(!Prev.isAmbiguous() && 2191 "Cannot have an ambiguity in previous-declaration lookup"); 2192 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 2193 Func != FuncEnd; ++Func) { 2194 if (isa<FunctionDecl>(*Func) && 2195 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD)) 2196 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 2197 } 2198 2199 PrevDecl = 0; 2200 } 2201 } 2202 2203 // Handle attributes. We need to have merged decls when handling attributes 2204 // (for example to check for conflicts, etc). 2205 // FIXME: This needs to happen before we merge declarations. Then, 2206 // let attribute merging cope with attribute conflicts. 2207 ProcessDeclAttributes(NewFD, D); 2208 AddKnownFunctionAttributes(NewFD); 2209 2210 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) { 2211 // If a function name is overloadable in C, then every function 2212 // with that name must be marked "overloadable". 2213 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 2214 << Redeclaration << NewFD; 2215 if (PrevDecl) 2216 Diag(PrevDecl->getLocation(), 2217 diag::note_attribute_overloadable_prev_overload); 2218 NewFD->addAttr(::new (Context) OverloadableAttr()); 2219 } 2220 2221 // If this is a locally-scoped extern C function, update the 2222 // map of such names. 2223 if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context) 2224 && !InvalidDecl) 2225 RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S); 2226 2227 return NewFD; 2228} 2229 2230/// \brief Perform semantic checking of a new function declaration. 2231/// 2232/// Performs semantic analysis of the new function declaration 2233/// NewFD. This routine performs all semantic checking that does not 2234/// require the actual declarator involved in the declaration, and is 2235/// used both for the declaration of functions as they are parsed 2236/// (called via ActOnDeclarator) and for the declaration of functions 2237/// that have been instantiated via C++ template instantiation (called 2238/// via InstantiateDecl). 2239/// 2240/// \returns true if there was an error, false otherwise. 2241bool Sema::CheckFunctionDeclaration(FunctionDecl *NewFD, NamedDecl *&PrevDecl, 2242 bool &Redeclaration, 2243 bool &OverloadableAttrRequired) { 2244 bool InvalidDecl = false; 2245 2246 // Semantic checking for this function declaration (in isolation). 2247 if (getLangOptions().CPlusPlus) { 2248 // C++-specific checks. 2249 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) 2250 InvalidDecl = InvalidDecl || CheckConstructor(Constructor); 2251 else if (isa<CXXDestructorDecl>(NewFD)) { 2252 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent()); 2253 Record->setUserDeclaredDestructor(true); 2254 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 2255 // user-defined destructor. 2256 Record->setPOD(false); 2257 2258 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly- 2259 // declared destructor. 2260 Record->setHasTrivialDestructor(false); 2261 } else if (CXXConversionDecl *Conversion 2262 = dyn_cast<CXXConversionDecl>(NewFD)) 2263 ActOnConversionDeclarator(Conversion); 2264 2265 // Extra checking for C++ overloaded operators (C++ [over.oper]). 2266 if (NewFD->isOverloadedOperator() && 2267 CheckOverloadedOperatorDeclaration(NewFD)) 2268 InvalidDecl = true; 2269 } 2270 2271 // Check for a previous declaration of this name. 2272 if (!PrevDecl && NewFD->isExternC(Context)) { 2273 // Since we did not find anything by this name and we're declaring 2274 // an extern "C" function, look for a non-visible extern "C" 2275 // declaration with the same name. 2276 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2277 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 2278 if (Pos != LocallyScopedExternalDecls.end()) 2279 PrevDecl = Pos->second; 2280 } 2281 2282 // Merge or overload the declaration with an existing declaration of 2283 // the same name, if appropriate. 2284 if (PrevDecl) { 2285 // Determine whether NewFD is an overload of PrevDecl or 2286 // a declaration that requires merging. If it's an overload, 2287 // there's no more work to do here; we'll just add the new 2288 // function to the scope. 2289 OverloadedFunctionDecl::function_iterator MatchedDecl; 2290 2291 if (!getLangOptions().CPlusPlus && 2292 AllowOverloadingOfFunction(PrevDecl, Context)) { 2293 OverloadableAttrRequired = true; 2294 2295 // Functions marked "overloadable" must have a prototype (that 2296 // we can't get through declaration merging). 2297 if (!NewFD->getType()->getAsFunctionProtoType()) { 2298 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype) 2299 << NewFD; 2300 InvalidDecl = true; 2301 Redeclaration = true; 2302 2303 // Turn this into a variadic function with no parameters. 2304 QualType R = Context.getFunctionType( 2305 NewFD->getType()->getAsFunctionType()->getResultType(), 2306 0, 0, true, 0); 2307 NewFD->setType(R); 2308 } 2309 } 2310 2311 if (PrevDecl && 2312 (!AllowOverloadingOfFunction(PrevDecl, Context) || 2313 !IsOverload(NewFD, PrevDecl, MatchedDecl))) { 2314 Redeclaration = true; 2315 Decl *OldDecl = PrevDecl; 2316 2317 // If PrevDecl was an overloaded function, extract the 2318 // FunctionDecl that matched. 2319 if (isa<OverloadedFunctionDecl>(PrevDecl)) 2320 OldDecl = *MatchedDecl; 2321 2322 // NewFD and OldDecl represent declarations that need to be 2323 // merged. 2324 if (MergeFunctionDecl(NewFD, OldDecl)) 2325 InvalidDecl = true; 2326 2327 if (!InvalidDecl) 2328 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 2329 } 2330 } 2331 2332 if (getLangOptions().CPlusPlus && !CurContext->isRecord()) { 2333 // In C++, check default arguments now that we have merged decls. Unless 2334 // the lexical context is the class, because in this case this is done 2335 // during delayed parsing anyway. 2336 CheckCXXDefaultArguments(NewFD); 2337 } 2338 2339 return InvalidDecl || NewFD->isInvalidDecl(); 2340} 2341 2342bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 2343 // FIXME: Need strict checking. In C89, we need to check for 2344 // any assignment, increment, decrement, function-calls, or 2345 // commas outside of a sizeof. In C99, it's the same list, 2346 // except that the aforementioned are allowed in unevaluated 2347 // expressions. Everything else falls under the 2348 // "may accept other forms of constant expressions" exception. 2349 // (We never end up here for C++, so the constant expression 2350 // rules there don't matter.) 2351 if (Init->isConstantInitializer(Context)) 2352 return false; 2353 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 2354 << Init->getSourceRange(); 2355 return true; 2356} 2357 2358void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) { 2359 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false); 2360} 2361 2362/// AddInitializerToDecl - Adds the initializer Init to the 2363/// declaration dcl. If DirectInit is true, this is C++ direct 2364/// initialization rather than copy initialization. 2365void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) { 2366 Decl *RealDecl = dcl.getAs<Decl>(); 2367 // If there is no declaration, there was an error parsing it. Just ignore 2368 // the initializer. 2369 if (RealDecl == 0) 2370 return; 2371 2372 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 2373 // With declarators parsed the way they are, the parser cannot 2374 // distinguish between a normal initializer and a pure-specifier. 2375 // Thus this grotesque test. 2376 IntegerLiteral *IL; 2377 Expr *Init = static_cast<Expr *>(init.get()); 2378 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 2379 Context.getCanonicalType(IL->getType()) == Context.IntTy) { 2380 if (Method->isVirtual()) { 2381 Method->setPure(); 2382 2383 // A class is abstract if at least one function is pure virtual. 2384 cast<CXXRecordDecl>(CurContext)->setAbstract(true); 2385 } else if (!Method->isInvalidDecl()) { 2386 Diag(Method->getLocation(), diag::err_non_virtual_pure) 2387 << Method->getDeclName() << Init->getSourceRange(); 2388 Method->setInvalidDecl(); 2389 } 2390 } else { 2391 Diag(Method->getLocation(), diag::err_member_function_initialization) 2392 << Method->getDeclName() << Init->getSourceRange(); 2393 Method->setInvalidDecl(); 2394 } 2395 return; 2396 } 2397 2398 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 2399 if (!VDecl) { 2400 if (getLangOptions().CPlusPlus && 2401 RealDecl->getLexicalDeclContext()->isRecord() && 2402 isa<NamedDecl>(RealDecl)) 2403 Diag(RealDecl->getLocation(), diag::err_member_initialization) 2404 << cast<NamedDecl>(RealDecl)->getDeclName(); 2405 else 2406 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 2407 RealDecl->setInvalidDecl(); 2408 return; 2409 } 2410 2411 if (!VDecl->getType()->isArrayType() && 2412 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 2413 diag::err_typecheck_decl_incomplete_type)) { 2414 RealDecl->setInvalidDecl(); 2415 return; 2416 } 2417 2418 const VarDecl *Def = 0; 2419 if (VDecl->getDefinition(Def)) { 2420 Diag(VDecl->getLocation(), diag::err_redefinition) 2421 << VDecl->getDeclName(); 2422 Diag(Def->getLocation(), diag::note_previous_definition); 2423 VDecl->setInvalidDecl(); 2424 return; 2425 } 2426 2427 // Take ownership of the expression, now that we're sure we have somewhere 2428 // to put it. 2429 Expr *Init = static_cast<Expr *>(init.release()); 2430 assert(Init && "missing initializer"); 2431 2432 // Get the decls type and save a reference for later, since 2433 // CheckInitializerTypes may change it. 2434 QualType DclT = VDecl->getType(), SavT = DclT; 2435 if (VDecl->isBlockVarDecl()) { 2436 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 2437 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 2438 VDecl->setInvalidDecl(); 2439 } else if (!VDecl->isInvalidDecl()) { 2440 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 2441 VDecl->getDeclName(), DirectInit)) 2442 VDecl->setInvalidDecl(); 2443 2444 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 2445 // Don't check invalid declarations to avoid emitting useless diagnostics. 2446 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 2447 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4. 2448 CheckForConstantInitializer(Init, DclT); 2449 } 2450 } 2451 } else if (VDecl->isStaticDataMember() && 2452 VDecl->getLexicalDeclContext()->isRecord()) { 2453 // This is an in-class initialization for a static data member, e.g., 2454 // 2455 // struct S { 2456 // static const int value = 17; 2457 // }; 2458 2459 // Attach the initializer 2460 VDecl->setInit(Init); 2461 2462 // C++ [class.mem]p4: 2463 // A member-declarator can contain a constant-initializer only 2464 // if it declares a static member (9.4) of const integral or 2465 // const enumeration type, see 9.4.2. 2466 QualType T = VDecl->getType(); 2467 if (!T->isDependentType() && 2468 (!Context.getCanonicalType(T).isConstQualified() || 2469 !T->isIntegralType())) { 2470 Diag(VDecl->getLocation(), diag::err_member_initialization) 2471 << VDecl->getDeclName() << Init->getSourceRange(); 2472 VDecl->setInvalidDecl(); 2473 } else { 2474 // C++ [class.static.data]p4: 2475 // If a static data member is of const integral or const 2476 // enumeration type, its declaration in the class definition 2477 // can specify a constant-initializer which shall be an 2478 // integral constant expression (5.19). 2479 if (!Init->isTypeDependent() && 2480 !Init->getType()->isIntegralType()) { 2481 // We have a non-dependent, non-integral or enumeration type. 2482 Diag(Init->getSourceRange().getBegin(), 2483 diag::err_in_class_initializer_non_integral_type) 2484 << Init->getType() << Init->getSourceRange(); 2485 VDecl->setInvalidDecl(); 2486 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) { 2487 // Check whether the expression is a constant expression. 2488 llvm::APSInt Value; 2489 SourceLocation Loc; 2490 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) { 2491 Diag(Loc, diag::err_in_class_initializer_non_constant) 2492 << Init->getSourceRange(); 2493 VDecl->setInvalidDecl(); 2494 } else if (!VDecl->getType()->isDependentType()) 2495 ImpCastExprToType(Init, VDecl->getType()); 2496 } 2497 } 2498 } else if (VDecl->isFileVarDecl()) { 2499 if (VDecl->getStorageClass() == VarDecl::Extern) 2500 Diag(VDecl->getLocation(), diag::warn_extern_init); 2501 if (!VDecl->isInvalidDecl()) 2502 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 2503 VDecl->getDeclName(), DirectInit)) 2504 VDecl->setInvalidDecl(); 2505 2506 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 2507 // Don't check invalid declarations to avoid emitting useless diagnostics. 2508 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 2509 // C99 6.7.8p4. All file scoped initializers need to be constant. 2510 CheckForConstantInitializer(Init, DclT); 2511 } 2512 } 2513 // If the type changed, it means we had an incomplete type that was 2514 // completed by the initializer. For example: 2515 // int ary[] = { 1, 3, 5 }; 2516 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 2517 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 2518 VDecl->setType(DclT); 2519 Init->setType(DclT); 2520 } 2521 2522 // Attach the initializer to the decl. 2523 VDecl->setInit(Init); 2524 return; 2525} 2526 2527void Sema::ActOnUninitializedDecl(DeclPtrTy dcl) { 2528 Decl *RealDecl = dcl.getAs<Decl>(); 2529 2530 // If there is no declaration, there was an error parsing it. Just ignore it. 2531 if (RealDecl == 0) 2532 return; 2533 2534 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 2535 QualType Type = Var->getType(); 2536 // C++ [dcl.init.ref]p3: 2537 // The initializer can be omitted for a reference only in a 2538 // parameter declaration (8.3.5), in the declaration of a 2539 // function return type, in the declaration of a class member 2540 // within its class declaration (9.2), and where the extern 2541 // specifier is explicitly used. 2542 if (Type->isReferenceType() && !Var->hasExternalStorage()) { 2543 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 2544 << Var->getDeclName() 2545 << SourceRange(Var->getLocation(), Var->getLocation()); 2546 Var->setInvalidDecl(); 2547 return; 2548 } 2549 2550 // C++ [dcl.init]p9: 2551 // 2552 // If no initializer is specified for an object, and the object 2553 // is of (possibly cv-qualified) non-POD class type (or array 2554 // thereof), the object shall be default-initialized; if the 2555 // object is of const-qualified type, the underlying class type 2556 // shall have a user-declared default constructor. 2557 if (getLangOptions().CPlusPlus) { 2558 QualType InitType = Type; 2559 if (const ArrayType *Array = Context.getAsArrayType(Type)) 2560 InitType = Array->getElementType(); 2561 if (!Var->hasExternalStorage() && InitType->isRecordType()) { 2562 CXXRecordDecl *RD = 2563 cast<CXXRecordDecl>(InitType->getAsRecordType()->getDecl()); 2564 CXXConstructorDecl *Constructor = 0; 2565 if (!RequireCompleteType(Var->getLocation(), InitType, 2566 diag::err_invalid_incomplete_type_use)) 2567 Constructor 2568 = PerformInitializationByConstructor(InitType, 0, 0, 2569 Var->getLocation(), 2570 SourceRange(Var->getLocation(), 2571 Var->getLocation()), 2572 Var->getDeclName(), 2573 IK_Default); 2574 if (!Constructor) 2575 Var->setInvalidDecl(); 2576 else if (!RD->hasTrivialConstructor()) 2577 InitializeVarWithConstructor(Var, Constructor, InitType, 0, 0); 2578 } 2579 } 2580 2581#if 0 2582 // FIXME: Temporarily disabled because we are not properly parsing 2583 // linkage specifications on declarations, e.g., 2584 // 2585 // extern "C" const CGPoint CGPointerZero; 2586 // 2587 // C++ [dcl.init]p9: 2588 // 2589 // If no initializer is specified for an object, and the 2590 // object is of (possibly cv-qualified) non-POD class type (or 2591 // array thereof), the object shall be default-initialized; if 2592 // the object is of const-qualified type, the underlying class 2593 // type shall have a user-declared default 2594 // constructor. Otherwise, if no initializer is specified for 2595 // an object, the object and its subobjects, if any, have an 2596 // indeterminate initial value; if the object or any of its 2597 // subobjects are of const-qualified type, the program is 2598 // ill-formed. 2599 // 2600 // This isn't technically an error in C, so we don't diagnose it. 2601 // 2602 // FIXME: Actually perform the POD/user-defined default 2603 // constructor check. 2604 if (getLangOptions().CPlusPlus && 2605 Context.getCanonicalType(Type).isConstQualified() && 2606 !Var->hasExternalStorage()) 2607 Diag(Var->getLocation(), diag::err_const_var_requires_init) 2608 << Var->getName() 2609 << SourceRange(Var->getLocation(), Var->getLocation()); 2610#endif 2611 } 2612} 2613 2614Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, DeclPtrTy *Group, 2615 unsigned NumDecls) { 2616 llvm::SmallVector<Decl*, 8> Decls; 2617 2618 for (unsigned i = 0; i != NumDecls; ++i) 2619 if (Decl *D = Group[i].getAs<Decl>()) 2620 Decls.push_back(D); 2621 2622 // Perform semantic analysis that depends on having fully processed both 2623 // the declarator and initializer. 2624 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 2625 VarDecl *IDecl = dyn_cast<VarDecl>(Decls[i]); 2626 if (!IDecl) 2627 continue; 2628 QualType T = IDecl->getType(); 2629 2630 // Block scope. C99 6.7p7: If an identifier for an object is declared with 2631 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 2632 if (IDecl->isBlockVarDecl() && !IDecl->hasExternalStorage()) { 2633 if (!IDecl->isInvalidDecl() && 2634 RequireCompleteType(IDecl->getLocation(), T, 2635 diag::err_typecheck_decl_incomplete_type)) 2636 IDecl->setInvalidDecl(); 2637 } 2638 // File scope. C99 6.9.2p2: A declaration of an identifier for and 2639 // object that has file scope without an initializer, and without a 2640 // storage-class specifier or with the storage-class specifier "static", 2641 // constitutes a tentative definition. Note: A tentative definition with 2642 // external linkage is valid (C99 6.2.2p5). 2643 if (IDecl->isTentativeDefinition(Context)) { 2644 QualType CheckType = T; 2645 unsigned DiagID = diag::err_typecheck_decl_incomplete_type; 2646 2647 const IncompleteArrayType *ArrayT = Context.getAsIncompleteArrayType(T); 2648 if (ArrayT) { 2649 CheckType = ArrayT->getElementType(); 2650 DiagID = diag::err_illegal_decl_array_incomplete_type; 2651 } 2652 2653 if (IDecl->isInvalidDecl()) { 2654 // Do nothing with invalid declarations 2655 } else if ((ArrayT || IDecl->getStorageClass() == VarDecl::Static) && 2656 RequireCompleteType(IDecl->getLocation(), CheckType, DiagID)) { 2657 // C99 6.9.2p3: If the declaration of an identifier for an object is 2658 // a tentative definition and has internal linkage (C99 6.2.2p3), the 2659 // declared type shall not be an incomplete type. 2660 IDecl->setInvalidDecl(); 2661 } 2662 } 2663 } 2664 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, 2665 &Decls[0], Decls.size())); 2666} 2667 2668 2669/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 2670/// to introduce parameters into function prototype scope. 2671Sema::DeclPtrTy 2672Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 2673 const DeclSpec &DS = D.getDeclSpec(); 2674 2675 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 2676 VarDecl::StorageClass StorageClass = VarDecl::None; 2677 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 2678 StorageClass = VarDecl::Register; 2679 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 2680 Diag(DS.getStorageClassSpecLoc(), 2681 diag::err_invalid_storage_class_in_func_decl); 2682 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2683 } 2684 if (DS.isThreadSpecified()) { 2685 Diag(DS.getThreadSpecLoc(), 2686 diag::err_invalid_storage_class_in_func_decl); 2687 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2688 } 2689 DiagnoseFunctionSpecifiers(D); 2690 2691 // Check that there are no default arguments inside the type of this 2692 // parameter (C++ only). 2693 if (getLangOptions().CPlusPlus) 2694 CheckExtraCXXDefaultArguments(D); 2695 2696 // In this context, we *do not* check D.getInvalidType(). If the declarator 2697 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 2698 // though it will not reflect the user specified type. 2699 QualType parmDeclType = GetTypeForDeclarator(D, S); 2700 if (parmDeclType.isNull()) { 2701 D.setInvalidType(true); 2702 parmDeclType = Context.IntTy; 2703 } 2704 2705 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 2706 // Can this happen for params? We already checked that they don't conflict 2707 // among each other. Here they can only shadow globals, which is ok. 2708 IdentifierInfo *II = D.getIdentifier(); 2709 if (II) { 2710 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 2711 if (PrevDecl->isTemplateParameter()) { 2712 // Maybe we will complain about the shadowed template parameter. 2713 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 2714 // Just pretend that we didn't see the previous declaration. 2715 PrevDecl = 0; 2716 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) { 2717 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 2718 2719 // Recover by removing the name 2720 II = 0; 2721 D.SetIdentifier(0, D.getIdentifierLoc()); 2722 } 2723 } 2724 } 2725 2726 // Parameters can not be abstract class types. 2727 // For record types, this is done by the AbstractClassUsageDiagnoser once 2728 // the class has been completely parsed. 2729 if (!CurContext->isRecord() && 2730 RequireNonAbstractType(D.getIdentifierLoc(), parmDeclType, 2731 diag::err_abstract_type_in_decl, 2732 AbstractParamType)) 2733 D.setInvalidType(true); 2734 2735 QualType T = adjustParameterType(parmDeclType); 2736 2737 ParmVarDecl *New; 2738 if (T == parmDeclType) // parameter type did not need adjustment 2739 New = ParmVarDecl::Create(Context, CurContext, 2740 D.getIdentifierLoc(), II, 2741 parmDeclType, StorageClass, 2742 0); 2743 else // keep track of both the adjusted and unadjusted types 2744 New = OriginalParmVarDecl::Create(Context, CurContext, 2745 D.getIdentifierLoc(), II, T, 2746 parmDeclType, StorageClass, 0); 2747 2748 if (D.getInvalidType()) 2749 New->setInvalidDecl(); 2750 2751 // Parameter declarators cannot be interface types. All ObjC objects are 2752 // passed by reference. 2753 if (T->isObjCInterfaceType()) { 2754 Diag(D.getIdentifierLoc(), 2755 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 2756 New->setInvalidDecl(); 2757 } 2758 2759 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 2760 if (D.getCXXScopeSpec().isSet()) { 2761 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 2762 << D.getCXXScopeSpec().getRange(); 2763 New->setInvalidDecl(); 2764 } 2765 2766 // Add the parameter declaration into this scope. 2767 S->AddDecl(DeclPtrTy::make(New)); 2768 if (II) 2769 IdResolver.AddDecl(New); 2770 2771 ProcessDeclAttributes(New, D); 2772 return DeclPtrTy::make(New); 2773} 2774 2775void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 2776 SourceLocation LocAfterDecls) { 2777 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2778 "Not a function declarator!"); 2779 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2780 2781 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 2782 // for a K&R function. 2783 if (!FTI.hasPrototype) { 2784 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 2785 --i; 2786 if (FTI.ArgInfo[i].Param == 0) { 2787 std::string Code = " int "; 2788 Code += FTI.ArgInfo[i].Ident->getName(); 2789 Code += ";\n"; 2790 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 2791 << FTI.ArgInfo[i].Ident 2792 << CodeModificationHint::CreateInsertion(LocAfterDecls, Code); 2793 2794 // Implicitly declare the argument as type 'int' for lack of a better 2795 // type. 2796 DeclSpec DS; 2797 const char* PrevSpec; // unused 2798 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 2799 PrevSpec); 2800 Declarator ParamD(DS, Declarator::KNRTypeListContext); 2801 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 2802 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 2803 } 2804 } 2805 } 2806} 2807 2808Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 2809 Declarator &D) { 2810 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 2811 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2812 "Not a function declarator!"); 2813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2814 2815 if (FTI.hasPrototype) { 2816 // FIXME: Diagnose arguments without names in C. 2817 } 2818 2819 Scope *ParentScope = FnBodyScope->getParent(); 2820 2821 DeclPtrTy DP = ActOnDeclarator(ParentScope, D, /*IsFunctionDefinition=*/true); 2822 return ActOnStartOfFunctionDef(FnBodyScope, DP); 2823} 2824 2825Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { 2826 FunctionDecl *FD = cast<FunctionDecl>(D.getAs<Decl>()); 2827 2828 // See if this is a redefinition. 2829 const FunctionDecl *Definition; 2830 if (FD->getBody(Definition)) { 2831 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 2832 Diag(Definition->getLocation(), diag::note_previous_definition); 2833 } 2834 2835 // Builtin functions cannot be defined. 2836 if (unsigned BuiltinID = FD->getBuiltinID(Context)) { 2837 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2838 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 2839 FD->setInvalidDecl(); 2840 } 2841 } 2842 2843 // The return type of a function definition must be complete 2844 // (C99 6.9.1p3, C++ [dcl.fct]p6). 2845 QualType ResultType = FD->getResultType(); 2846 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 2847 RequireCompleteType(FD->getLocation(), ResultType, 2848 diag::err_func_def_incomplete_result)) 2849 FD->setInvalidDecl(); 2850 2851 // GNU warning -Wmissing-prototypes: 2852 // Warn if a global function is defined without a previous 2853 // prototype declaration. This warning is issued even if the 2854 // definition itself provides a prototype. The aim is to detect 2855 // global functions that fail to be declared in header files. 2856 if (!FD->isInvalidDecl() && FD->isGlobal() && !isa<CXXMethodDecl>(FD) && 2857 !FD->isMain()) { 2858 bool MissingPrototype = true; 2859 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 2860 Prev; Prev = Prev->getPreviousDeclaration()) { 2861 // Ignore any declarations that occur in function or method 2862 // scope, because they aren't visible from the header. 2863 if (Prev->getDeclContext()->isFunctionOrMethod()) 2864 continue; 2865 2866 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 2867 break; 2868 } 2869 2870 if (MissingPrototype) 2871 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 2872 } 2873 2874 PushDeclContext(FnBodyScope, FD); 2875 2876 // Check the validity of our function parameters 2877 CheckParmsForFunctionDef(FD); 2878 2879 // Introduce our parameters into the function scope 2880 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 2881 ParmVarDecl *Param = FD->getParamDecl(p); 2882 Param->setOwningFunction(FD); 2883 2884 // If this has an identifier, add it to the scope stack. 2885 if (Param->getIdentifier()) 2886 PushOnScopeChains(Param, FnBodyScope); 2887 } 2888 2889 // Checking attributes of current function definition 2890 // dllimport attribute. 2891 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) { 2892 // dllimport attribute cannot be applied to definition. 2893 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 2894 Diag(FD->getLocation(), 2895 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 2896 << "dllimport"; 2897 FD->setInvalidDecl(); 2898 return DeclPtrTy::make(FD); 2899 } else { 2900 // If a symbol previously declared dllimport is later defined, the 2901 // attribute is ignored in subsequent references, and a warning is 2902 // emitted. 2903 Diag(FD->getLocation(), 2904 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 2905 << FD->getNameAsCString() << "dllimport"; 2906 } 2907 } 2908 return DeclPtrTy::make(FD); 2909} 2910 2911static bool StatementCreatesScope(Stmt* S) { 2912 2913 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { 2914 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end(); 2915 I != E; ++I) { 2916 if (VarDecl *D = dyn_cast<VarDecl>(*I)) { 2917 if (D->getType()->isVariablyModifiedType() || 2918 D->hasAttr<CleanupAttr>()) 2919 return true; 2920 } else if (TypedefDecl *D = dyn_cast<TypedefDecl>(*I)) { 2921 if (D->getUnderlyingType()->isVariablyModifiedType()) 2922 return true; 2923 } 2924 } 2925 } 2926 return false; 2927} 2928 2929 2930void Sema::RecursiveCalcLabelScopes(llvm::DenseMap<Stmt*, void*>& LabelScopeMap, 2931 llvm::DenseMap<void*, Stmt*>& PopScopeMap, 2932 std::vector<void*>& ScopeStack, 2933 Stmt* CurStmt, 2934 Stmt* ParentCompoundStmt) { 2935 for (Stmt::child_iterator i = CurStmt->child_begin(); 2936 i != CurStmt->child_end(); ++i) { 2937 if (!*i) continue; 2938 if (StatementCreatesScope(*i)) { 2939 ScopeStack.push_back(*i); 2940 PopScopeMap[*i] = ParentCompoundStmt; 2941 } else if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(*i)) { 2942 ScopeStack.push_back(*i); 2943 PopScopeMap[*i] = AT->getTryBody(); 2944 } else if (ObjCAtCatchStmt *AC = dyn_cast<ObjCAtCatchStmt>(*i)) { 2945 ScopeStack.push_back(*i); 2946 PopScopeMap[*i] = AC->getCatchBody(); 2947 } else if (ObjCAtFinallyStmt *AF = dyn_cast<ObjCAtFinallyStmt>(*i)) { 2948 ScopeStack.push_back(*i); 2949 PopScopeMap[*i] = AF->getFinallyBody(); 2950 } else if (isa<LabelStmt>(CurStmt)) { 2951 LabelScopeMap[CurStmt] = ScopeStack.size() ? ScopeStack.back() : 0; 2952 } 2953 if (isa<DeclStmt>(*i)) continue; 2954 Stmt* CurCompound = isa<CompoundStmt>(*i) ? *i : ParentCompoundStmt; 2955 RecursiveCalcLabelScopes(LabelScopeMap, PopScopeMap, ScopeStack, 2956 *i, CurCompound); 2957 } 2958 while (ScopeStack.size() && PopScopeMap[ScopeStack.back()] == CurStmt) { 2959 ScopeStack.pop_back(); 2960 } 2961} 2962 2963void Sema::RecursiveCalcJumpScopes(llvm::DenseMap<Stmt*, void*>& LabelScopeMap, 2964 llvm::DenseMap<void*, Stmt*>& PopScopeMap, 2965 llvm::DenseMap<Stmt*, void*>& GotoScopeMap, 2966 std::vector<void*>& ScopeStack, 2967 Stmt* CurStmt) { 2968 for (Stmt::child_iterator i = CurStmt->child_begin(); 2969 i != CurStmt->child_end(); ++i) { 2970 if (!*i) continue; 2971 if (StatementCreatesScope(*i)) { 2972 ScopeStack.push_back(*i); 2973 } else if (GotoStmt* GS = dyn_cast<GotoStmt>(*i)) { 2974 void* LScope = LabelScopeMap[GS->getLabel()]; 2975 if (LScope) { 2976 bool foundScopeInStack = false; 2977 for (unsigned i = ScopeStack.size(); i > 0; --i) { 2978 if (LScope == ScopeStack[i-1]) { 2979 foundScopeInStack = true; 2980 break; 2981 } 2982 } 2983 if (!foundScopeInStack) { 2984 Diag(GS->getSourceRange().getBegin(), diag::err_goto_into_scope); 2985 } 2986 } 2987 } 2988 if (isa<DeclStmt>(*i)) continue; 2989 RecursiveCalcJumpScopes(LabelScopeMap, PopScopeMap, GotoScopeMap, 2990 ScopeStack, *i); 2991 } 2992 while (ScopeStack.size() && PopScopeMap[ScopeStack.back()] == CurStmt) { 2993 ScopeStack.pop_back(); 2994 } 2995} 2996 2997Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) { 2998 Decl *dcl = D.getAs<Decl>(); 2999 Stmt *Body = static_cast<Stmt*>(BodyArg.release()); 3000 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 3001 FD->setBody(cast<CompoundStmt>(Body)); 3002 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 3003 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 3004 assert(MD == getCurMethodDecl() && "Method parsing confused"); 3005 MD->setBody(cast<CompoundStmt>(Body)); 3006 } else { 3007 Body->Destroy(Context); 3008 return DeclPtrTy(); 3009 } 3010 PopDeclContext(); 3011 // Verify and clean out per-function state. 3012 3013 bool HaveLabels = !LabelMap.empty(); 3014 // Check goto/label use. 3015 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 3016 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 3017 // Verify that we have no forward references left. If so, there was a goto 3018 // or address of a label taken, but no definition of it. Label fwd 3019 // definitions are indicated with a null substmt. 3020 if (I->second->getSubStmt() == 0) { 3021 LabelStmt *L = I->second; 3022 // Emit error. 3023 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 3024 3025 // At this point, we have gotos that use the bogus label. Stitch it into 3026 // the function body so that they aren't leaked and that the AST is well 3027 // formed. 3028 if (Body) { 3029#if 0 3030 // FIXME: Why do this? Having a 'push_back' in CompoundStmt is ugly, 3031 // and the AST is malformed anyway. We should just blow away 'L'. 3032 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 3033 cast<CompoundStmt>(Body)->push_back(L); 3034#else 3035 L->Destroy(Context); 3036#endif 3037 } else { 3038 // The whole function wasn't parsed correctly, just delete this. 3039 L->Destroy(Context); 3040 } 3041 } 3042 } 3043 LabelMap.clear(); 3044 3045 if (!Body) return D; 3046 3047 if (HaveLabels) { 3048 llvm::DenseMap<Stmt*, void*> LabelScopeMap; 3049 llvm::DenseMap<void*, Stmt*> PopScopeMap; 3050 llvm::DenseMap<Stmt*, void*> GotoScopeMap; 3051 std::vector<void*> ScopeStack; 3052 RecursiveCalcLabelScopes(LabelScopeMap, PopScopeMap, ScopeStack, Body, Body); 3053 RecursiveCalcJumpScopes(LabelScopeMap, PopScopeMap, GotoScopeMap, ScopeStack, Body); 3054 } 3055 3056 return D; 3057} 3058 3059/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 3060/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 3061NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 3062 IdentifierInfo &II, Scope *S) { 3063 // Before we produce a declaration for an implicitly defined 3064 // function, see whether there was a locally-scoped declaration of 3065 // this name as a function or variable. If so, use that 3066 // (non-visible) declaration, and complain about it. 3067 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3068 = LocallyScopedExternalDecls.find(&II); 3069 if (Pos != LocallyScopedExternalDecls.end()) { 3070 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 3071 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 3072 return Pos->second; 3073 } 3074 3075 // Extension in C99. Legal in C90, but warn about it. 3076 if (getLangOptions().C99) 3077 Diag(Loc, diag::ext_implicit_function_decl) << &II; 3078 else 3079 Diag(Loc, diag::warn_implicit_function_decl) << &II; 3080 3081 // FIXME: handle stuff like: 3082 // void foo() { extern float X(); } 3083 // void bar() { X(); } <-- implicit decl for X in another scope. 3084 3085 // Set a Declarator for the implicit definition: int foo(); 3086 const char *Dummy; 3087 DeclSpec DS; 3088 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 3089 Error = Error; // Silence warning. 3090 assert(!Error && "Error setting up implicit decl!"); 3091 Declarator D(DS, Declarator::BlockContext); 3092 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 3093 0, 0, 0, Loc, D), 3094 SourceLocation()); 3095 D.SetIdentifier(&II, Loc); 3096 3097 // Insert this function into translation-unit scope. 3098 3099 DeclContext *PrevDC = CurContext; 3100 CurContext = Context.getTranslationUnitDecl(); 3101 3102 FunctionDecl *FD = 3103 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D, DeclPtrTy()).getAs<Decl>()); 3104 FD->setImplicit(); 3105 3106 CurContext = PrevDC; 3107 3108 AddKnownFunctionAttributes(FD); 3109 3110 return FD; 3111} 3112 3113/// \brief Adds any function attributes that we know a priori based on 3114/// the declaration of this function. 3115/// 3116/// These attributes can apply both to implicitly-declared builtins 3117/// (like __builtin___printf_chk) or to library-declared functions 3118/// like NSLog or printf. 3119void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 3120 if (FD->isInvalidDecl()) 3121 return; 3122 3123 // If this is a built-in function, map its builtin attributes to 3124 // actual attributes. 3125 if (unsigned BuiltinID = FD->getBuiltinID(Context)) { 3126 // Handle printf-formatting attributes. 3127 unsigned FormatIdx; 3128 bool HasVAListArg; 3129 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 3130 if (!FD->getAttr<FormatAttr>()) 3131 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1, 3132 FormatIdx + 2)); 3133 } 3134 3135 // Mark const if we don't care about errno and that is the only 3136 // thing preventing the function from being const. This allows 3137 // IRgen to use LLVM intrinsics for such functions. 3138 if (!getLangOptions().MathErrno && 3139 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 3140 if (!FD->getAttr<ConstAttr>()) 3141 FD->addAttr(::new (Context) ConstAttr()); 3142 } 3143 } 3144 3145 IdentifierInfo *Name = FD->getIdentifier(); 3146 if (!Name) 3147 return; 3148 if ((!getLangOptions().CPlusPlus && 3149 FD->getDeclContext()->isTranslationUnit()) || 3150 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 3151 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 3152 LinkageSpecDecl::lang_c)) { 3153 // Okay: this could be a libc/libm/Objective-C function we know 3154 // about. 3155 } else 3156 return; 3157 3158 unsigned KnownID; 3159 for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID) 3160 if (KnownFunctionIDs[KnownID] == Name) 3161 break; 3162 3163 switch (KnownID) { 3164 case id_NSLog: 3165 case id_NSLogv: 3166 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 3167 // FIXME: We known better than our headers. 3168 const_cast<FormatAttr *>(Format)->setType("printf"); 3169 } else 3170 FD->addAttr(::new (Context) FormatAttr("printf", 1, 2)); 3171 break; 3172 3173 case id_asprintf: 3174 case id_vasprintf: 3175 if (!FD->getAttr<FormatAttr>()) 3176 FD->addAttr(::new (Context) FormatAttr("printf", 2, 3)); 3177 break; 3178 3179 default: 3180 // Unknown function or known function without any attributes to 3181 // add. Do nothing. 3182 break; 3183 } 3184} 3185 3186TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T) { 3187 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 3188 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 3189 3190 // Scope manipulation handled by caller. 3191 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 3192 D.getIdentifierLoc(), 3193 D.getIdentifier(), 3194 T); 3195 3196 if (TagType *TT = dyn_cast<TagType>(T)) { 3197 TagDecl *TD = TT->getDecl(); 3198 3199 // If the TagDecl that the TypedefDecl points to is an anonymous decl 3200 // keep track of the TypedefDecl. 3201 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 3202 TD->setTypedefForAnonDecl(NewTD); 3203 } 3204 3205 if (D.getInvalidType()) 3206 NewTD->setInvalidDecl(); 3207 return NewTD; 3208} 3209 3210/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 3211/// former case, Name will be non-null. In the later case, Name will be null. 3212/// TagSpec indicates what kind of tag this is. TK indicates whether this is a 3213/// reference/declaration/definition of a tag. 3214Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK, 3215 SourceLocation KWLoc, const CXXScopeSpec &SS, 3216 IdentifierInfo *Name, SourceLocation NameLoc, 3217 AttributeList *Attr, AccessSpecifier AS) { 3218 // If this is not a definition, it must have a name. 3219 assert((Name != 0 || TK == TK_Definition) && 3220 "Nameless record must be a definition!"); 3221 3222 TagDecl::TagKind Kind; 3223 switch (TagSpec) { 3224 default: assert(0 && "Unknown tag type!"); 3225 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 3226 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 3227 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 3228 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 3229 } 3230 3231 DeclContext *SearchDC = CurContext; 3232 DeclContext *DC = CurContext; 3233 NamedDecl *PrevDecl = 0; 3234 3235 bool Invalid = false; 3236 3237 if (Name && SS.isNotEmpty()) { 3238 // We have a nested-name tag ('struct foo::bar'). 3239 3240 // Check for invalid 'foo::'. 3241 if (SS.isInvalid()) { 3242 Name = 0; 3243 goto CreateNewDecl; 3244 } 3245 3246 // FIXME: RequireCompleteDeclContext(SS)? 3247 DC = computeDeclContext(SS); 3248 SearchDC = DC; 3249 // Look-up name inside 'foo::'. 3250 PrevDecl = dyn_cast_or_null<TagDecl>( 3251 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl()); 3252 3253 // A tag 'foo::bar' must already exist. 3254 if (PrevDecl == 0) { 3255 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange(); 3256 Name = 0; 3257 goto CreateNewDecl; 3258 } 3259 } else if (Name) { 3260 // If this is a named struct, check to see if there was a previous forward 3261 // declaration or definition. 3262 // FIXME: We're looking into outer scopes here, even when we 3263 // shouldn't be. Doing so can result in ambiguities that we 3264 // shouldn't be diagnosing. 3265 LookupResult R = LookupName(S, Name, LookupTagName, 3266 /*RedeclarationOnly=*/(TK != TK_Reference)); 3267 if (R.isAmbiguous()) { 3268 DiagnoseAmbiguousLookup(R, Name, NameLoc); 3269 // FIXME: This is not best way to recover from case like: 3270 // 3271 // struct S s; 3272 // 3273 // causes needless "incomplete type" error later. 3274 Name = 0; 3275 PrevDecl = 0; 3276 Invalid = true; 3277 } 3278 else 3279 PrevDecl = R; 3280 3281 if (!getLangOptions().CPlusPlus && TK != TK_Reference) { 3282 // FIXME: This makes sure that we ignore the contexts associated 3283 // with C structs, unions, and enums when looking for a matching 3284 // tag declaration or definition. See the similar lookup tweak 3285 // in Sema::LookupName; is there a better way to deal with this? 3286 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 3287 SearchDC = SearchDC->getParent(); 3288 } 3289 } 3290 3291 if (PrevDecl && PrevDecl->isTemplateParameter()) { 3292 // Maybe we will complain about the shadowed template parameter. 3293 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 3294 // Just pretend that we didn't see the previous declaration. 3295 PrevDecl = 0; 3296 } 3297 3298 if (PrevDecl) { 3299 // Check whether the previous declaration is usable. 3300 (void)DiagnoseUseOfDecl(PrevDecl, NameLoc); 3301 3302 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 3303 // If this is a use of a previous tag, or if the tag is already declared 3304 // in the same scope (so that the definition/declaration completes or 3305 // rementions the tag), reuse the decl. 3306 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) { 3307 // Make sure that this wasn't declared as an enum and now used as a 3308 // struct or something similar. 3309 if (PrevTagDecl->getTagKind() != Kind) { 3310 bool SafeToContinue 3311 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum && 3312 Kind != TagDecl::TK_enum); 3313 if (SafeToContinue) 3314 Diag(KWLoc, diag::err_use_with_wrong_tag) 3315 << Name 3316 << CodeModificationHint::CreateReplacement(SourceRange(KWLoc), 3317 PrevTagDecl->getKindName()); 3318 else 3319 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 3320 Diag(PrevDecl->getLocation(), diag::note_previous_use); 3321 3322 if (SafeToContinue) 3323 Kind = PrevTagDecl->getTagKind(); 3324 else { 3325 // Recover by making this an anonymous redefinition. 3326 Name = 0; 3327 PrevDecl = 0; 3328 Invalid = true; 3329 } 3330 } 3331 3332 if (!Invalid) { 3333 // If this is a use, just return the declaration we found. 3334 3335 // FIXME: In the future, return a variant or some other clue 3336 // for the consumer of this Decl to know it doesn't own it. 3337 // For our current ASTs this shouldn't be a problem, but will 3338 // need to be changed with DeclGroups. 3339 if (TK == TK_Reference) 3340 return DeclPtrTy::make(PrevDecl); 3341 3342 // Diagnose attempts to redefine a tag. 3343 if (TK == TK_Definition) { 3344 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) { 3345 Diag(NameLoc, diag::err_redefinition) << Name; 3346 Diag(Def->getLocation(), diag::note_previous_definition); 3347 // If this is a redefinition, recover by making this 3348 // struct be anonymous, which will make any later 3349 // references get the previous definition. 3350 Name = 0; 3351 PrevDecl = 0; 3352 Invalid = true; 3353 } else { 3354 // If the type is currently being defined, complain 3355 // about a nested redefinition. 3356 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 3357 if (Tag->isBeingDefined()) { 3358 Diag(NameLoc, diag::err_nested_redefinition) << Name; 3359 Diag(PrevTagDecl->getLocation(), 3360 diag::note_previous_definition); 3361 Name = 0; 3362 PrevDecl = 0; 3363 Invalid = true; 3364 } 3365 } 3366 3367 // Okay, this is definition of a previously declared or referenced 3368 // tag PrevDecl. We're going to create a new Decl for it. 3369 } 3370 } 3371 // If we get here we have (another) forward declaration or we 3372 // have a definition. Just create a new decl. 3373 } else { 3374 // If we get here, this is a definition of a new tag type in a nested 3375 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 3376 // new decl/type. We set PrevDecl to NULL so that the entities 3377 // have distinct types. 3378 PrevDecl = 0; 3379 } 3380 // If we get here, we're going to create a new Decl. If PrevDecl 3381 // is non-NULL, it's a definition of the tag declared by 3382 // PrevDecl. If it's NULL, we have a new definition. 3383 } else { 3384 // PrevDecl is a namespace, template, or anything else 3385 // that lives in the IDNS_Tag identifier namespace. 3386 if (isDeclInScope(PrevDecl, SearchDC, S)) { 3387 // The tag name clashes with a namespace name, issue an error and 3388 // recover by making this tag be anonymous. 3389 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 3390 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3391 Name = 0; 3392 PrevDecl = 0; 3393 Invalid = true; 3394 } else { 3395 // The existing declaration isn't relevant to us; we're in a 3396 // new scope, so clear out the previous declaration. 3397 PrevDecl = 0; 3398 } 3399 } 3400 } else if (TK == TK_Reference && SS.isEmpty() && Name && 3401 (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) { 3402 // C.scope.pdecl]p5: 3403 // -- for an elaborated-type-specifier of the form 3404 // 3405 // class-key identifier 3406 // 3407 // if the elaborated-type-specifier is used in the 3408 // decl-specifier-seq or parameter-declaration-clause of a 3409 // function defined in namespace scope, the identifier is 3410 // declared as a class-name in the namespace that contains 3411 // the declaration; otherwise, except as a friend 3412 // declaration, the identifier is declared in the smallest 3413 // non-class, non-function-prototype scope that contains the 3414 // declaration. 3415 // 3416 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 3417 // C structs and unions. 3418 // 3419 // GNU C also supports this behavior as part of its incomplete 3420 // enum types extension, while GNU C++ does not. 3421 // 3422 // Find the context where we'll be declaring the tag. 3423 // FIXME: We would like to maintain the current DeclContext as the 3424 // lexical context, 3425 while (SearchDC->isRecord()) 3426 SearchDC = SearchDC->getParent(); 3427 3428 // Find the scope where we'll be declaring the tag. 3429 while (S->isClassScope() || 3430 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) || 3431 ((S->getFlags() & Scope::DeclScope) == 0) || 3432 (S->getEntity() && 3433 ((DeclContext *)S->getEntity())->isTransparentContext())) 3434 S = S->getParent(); 3435 } 3436 3437CreateNewDecl: 3438 3439 // If there is an identifier, use the location of the identifier as the 3440 // location of the decl, otherwise use the location of the struct/union 3441 // keyword. 3442 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 3443 3444 // Otherwise, create a new declaration. If there is a previous 3445 // declaration of the same entity, the two will be linked via 3446 // PrevDecl. 3447 TagDecl *New; 3448 3449 if (Kind == TagDecl::TK_enum) { 3450 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 3451 // enum X { A, B, C } D; D should chain to X. 3452 New = EnumDecl::Create(Context, SearchDC, Loc, Name, 3453 cast_or_null<EnumDecl>(PrevDecl)); 3454 // If this is an undefined enum, warn. 3455 if (TK != TK_Definition && !Invalid) { 3456 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum 3457 : diag::ext_forward_ref_enum; 3458 Diag(Loc, DK); 3459 } 3460 } else { 3461 // struct/union/class 3462 3463 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 3464 // struct X { int A; } D; D should chain to X. 3465 if (getLangOptions().CPlusPlus) 3466 // FIXME: Look for a way to use RecordDecl for simple structs. 3467 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, 3468 cast_or_null<CXXRecordDecl>(PrevDecl)); 3469 else 3470 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, 3471 cast_or_null<RecordDecl>(PrevDecl)); 3472 } 3473 3474 if (Kind != TagDecl::TK_enum) { 3475 // Handle #pragma pack: if the #pragma pack stack has non-default 3476 // alignment, make up a packed attribute for this decl. These 3477 // attributes are checked when the ASTContext lays out the 3478 // structure. 3479 // 3480 // It is important for implementing the correct semantics that this 3481 // happen here (in act on tag decl). The #pragma pack stack is 3482 // maintained as a result of parser callbacks which can occur at 3483 // many points during the parsing of a struct declaration (because 3484 // the #pragma tokens are effectively skipped over during the 3485 // parsing of the struct). 3486 if (unsigned Alignment = getPragmaPackAlignment()) 3487 New->addAttr(::new (Context) PackedAttr(Alignment * 8)); 3488 } 3489 3490 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) { 3491 // C++ [dcl.typedef]p3: 3492 // [...] Similarly, in a given scope, a class or enumeration 3493 // shall not be declared with the same name as a typedef-name 3494 // that is declared in that scope and refers to a type other 3495 // than the class or enumeration itself. 3496 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true); 3497 TypedefDecl *PrevTypedef = 0; 3498 if (Lookup.getKind() == LookupResult::Found) 3499 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl()); 3500 3501 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) && 3502 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) != 3503 Context.getCanonicalType(Context.getTypeDeclType(New))) { 3504 Diag(Loc, diag::err_tag_definition_of_typedef) 3505 << Context.getTypeDeclType(New) 3506 << PrevTypedef->getUnderlyingType(); 3507 Diag(PrevTypedef->getLocation(), diag::note_previous_definition); 3508 Invalid = true; 3509 } 3510 } 3511 3512 if (Invalid) 3513 New->setInvalidDecl(); 3514 3515 if (Attr) 3516 ProcessDeclAttributeList(New, Attr); 3517 3518 // If we're declaring or defining a tag in function prototype scope 3519 // in C, note that this type can only be used within the function. 3520 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 3521 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 3522 3523 // Set the lexical context. If the tag has a C++ scope specifier, the 3524 // lexical context will be different from the semantic context. 3525 New->setLexicalDeclContext(CurContext); 3526 3527 // Set the access specifier. 3528 SetMemberAccessSpecifier(New, PrevDecl, AS); 3529 3530 if (TK == TK_Definition) 3531 New->startDefinition(); 3532 3533 // If this has an identifier, add it to the scope stack. 3534 if (Name) { 3535 S = getNonFieldDeclScope(S); 3536 PushOnScopeChains(New, S); 3537 } else { 3538 CurContext->addDecl(Context, New); 3539 } 3540 3541 return DeclPtrTy::make(New); 3542} 3543 3544void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) { 3545 AdjustDeclIfTemplate(TagD); 3546 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 3547 3548 // Enter the tag context. 3549 PushDeclContext(S, Tag); 3550 3551 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) { 3552 FieldCollector->StartClass(); 3553 3554 if (Record->getIdentifier()) { 3555 // C++ [class]p2: 3556 // [...] The class-name is also inserted into the scope of the 3557 // class itself; this is known as the injected-class-name. For 3558 // purposes of access checking, the injected-class-name is treated 3559 // as if it were a public member name. 3560 CXXRecordDecl *InjectedClassName 3561 = CXXRecordDecl::Create(Context, Record->getTagKind(), 3562 CurContext, Record->getLocation(), 3563 Record->getIdentifier(), Record); 3564 InjectedClassName->setImplicit(); 3565 InjectedClassName->setAccess(AS_public); 3566 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 3567 InjectedClassName->setDescribedClassTemplate(Template); 3568 PushOnScopeChains(InjectedClassName, S); 3569 assert(InjectedClassName->isInjectedClassName() && 3570 "Broken injected-class-name"); 3571 } 3572 } 3573} 3574 3575void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD) { 3576 AdjustDeclIfTemplate(TagD); 3577 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 3578 3579 if (isa<CXXRecordDecl>(Tag)) 3580 FieldCollector->FinishClass(); 3581 3582 // Exit this scope of this tag's definition. 3583 PopDeclContext(); 3584 3585 // Notify the consumer that we've defined a tag. 3586 Consumer.HandleTagDeclDefinition(Tag); 3587} 3588 3589bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 3590 QualType FieldTy, const Expr *BitWidth) { 3591 // C99 6.7.2.1p4 - verify the field type. 3592 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3593 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) { 3594 // Handle incomplete types with specific error. 3595 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 3596 return true; 3597 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 3598 << FieldName << FieldTy << BitWidth->getSourceRange(); 3599 } 3600 3601 // If the bit-width is type- or value-dependent, don't try to check 3602 // it now. 3603 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 3604 return false; 3605 3606 llvm::APSInt Value; 3607 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 3608 return true; 3609 3610 // Zero-width bitfield is ok for anonymous field. 3611 if (Value == 0 && FieldName) 3612 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 3613 3614 if (Value.isSigned() && Value.isNegative()) 3615 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 3616 << FieldName << Value.toString(10); 3617 3618 if (!FieldTy->isDependentType()) { 3619 uint64_t TypeSize = Context.getTypeSize(FieldTy); 3620 // FIXME: We won't need the 0 size once we check that the field type is valid. 3621 if (TypeSize && Value.getZExtValue() > TypeSize) 3622 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 3623 << FieldName << (unsigned)TypeSize; 3624 } 3625 3626 return false; 3627} 3628 3629/// ActOnField - Each field of a struct/union/class is passed into this in order 3630/// to create a FieldDecl object for it. 3631Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD, 3632 SourceLocation DeclStart, 3633 Declarator &D, ExprTy *BitfieldWidth) { 3634 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()), 3635 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 3636 AS_public); 3637 return DeclPtrTy::make(Res); 3638} 3639 3640/// HandleField - Analyze a field of a C struct or a C++ data member. 3641/// 3642FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 3643 SourceLocation DeclStart, 3644 Declarator &D, Expr *BitWidth, 3645 AccessSpecifier AS) { 3646 IdentifierInfo *II = D.getIdentifier(); 3647 SourceLocation Loc = DeclStart; 3648 if (II) Loc = D.getIdentifierLoc(); 3649 3650 QualType T = GetTypeForDeclarator(D, S); 3651 if (getLangOptions().CPlusPlus) 3652 CheckExtraCXXDefaultArguments(D); 3653 3654 DiagnoseFunctionSpecifiers(D); 3655 3656 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true); 3657 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 3658 PrevDecl = 0; 3659 3660 FieldDecl *NewFD 3661 = CheckFieldDecl(II, T, Record, Loc, 3662 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable, 3663 BitWidth, AS, PrevDecl, &D); 3664 if (NewFD->isInvalidDecl() && PrevDecl) { 3665 // Don't introduce NewFD into scope; there's already something 3666 // with the same name in the same scope. 3667 } else if (II) { 3668 PushOnScopeChains(NewFD, S); 3669 } else 3670 Record->addDecl(Context, NewFD); 3671 3672 return NewFD; 3673} 3674 3675/// \brief Build a new FieldDecl and check its well-formedness. 3676/// 3677/// This routine builds a new FieldDecl given the fields name, type, 3678/// record, etc. \p PrevDecl should refer to any previous declaration 3679/// with the same name and in the same scope as the field to be 3680/// created. 3681/// 3682/// \returns a new FieldDecl. 3683/// 3684/// \todo The Declarator argument is a hack. It will be removed once 3685FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 3686 RecordDecl *Record, SourceLocation Loc, 3687 bool Mutable, Expr *BitWidth, 3688 AccessSpecifier AS, NamedDecl *PrevDecl, 3689 Declarator *D) { 3690 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3691 bool InvalidDecl = false; 3692 3693 // If we receive a broken type, recover by assuming 'int' and 3694 // marking this declaration as invalid. 3695 if (T.isNull()) { 3696 InvalidDecl = true; 3697 T = Context.IntTy; 3698 } 3699 3700 // C99 6.7.2.1p8: A member of a structure or union may have any type other 3701 // than a variably modified type. 3702 if (T->isVariablyModifiedType()) { 3703 bool SizeIsNegative; 3704 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 3705 SizeIsNegative); 3706 if (!FixedTy.isNull()) { 3707 Diag(Loc, diag::warn_illegal_constant_array_size); 3708 T = FixedTy; 3709 } else { 3710 if (SizeIsNegative) 3711 Diag(Loc, diag::err_typecheck_negative_array_size); 3712 else 3713 Diag(Loc, diag::err_typecheck_field_variable_size); 3714 T = Context.IntTy; 3715 InvalidDecl = true; 3716 } 3717 } 3718 3719 // Fields can not have abstract class types 3720 if (RequireNonAbstractType(Loc, T, diag::err_abstract_type_in_decl, 3721 AbstractFieldType)) 3722 InvalidDecl = true; 3723 3724 // If this is declared as a bit-field, check the bit-field. 3725 if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) { 3726 InvalidDecl = true; 3727 DeleteExpr(BitWidth); 3728 BitWidth = 0; 3729 } 3730 3731 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth, 3732 Mutable); 3733 3734 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 3735 Diag(Loc, diag::err_duplicate_member) << II; 3736 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3737 NewFD->setInvalidDecl(); 3738 Record->setInvalidDecl(); 3739 } 3740 3741 if (getLangOptions().CPlusPlus && !T->isPODType()) 3742 cast<CXXRecordDecl>(Record)->setPOD(false); 3743 3744 // FIXME: We need to pass in the attributes given an AST 3745 // representation, not a parser representation. 3746 if (D) 3747 ProcessDeclAttributes(NewFD, *D); 3748 3749 if (T.isObjCGCWeak()) 3750 Diag(Loc, diag::warn_attribute_weak_on_field); 3751 3752 if (InvalidDecl) 3753 NewFD->setInvalidDecl(); 3754 3755 NewFD->setAccess(AS); 3756 3757 // C++ [dcl.init.aggr]p1: 3758 // An aggregate is an array or a class (clause 9) with [...] no 3759 // private or protected non-static data members (clause 11). 3760 // A POD must be an aggregate. 3761 if (getLangOptions().CPlusPlus && 3762 (AS == AS_private || AS == AS_protected)) { 3763 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 3764 CXXRecord->setAggregate(false); 3765 CXXRecord->setPOD(false); 3766 } 3767 3768 return NewFD; 3769} 3770 3771/// TranslateIvarVisibility - Translate visibility from a token ID to an 3772/// AST enum value. 3773static ObjCIvarDecl::AccessControl 3774TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 3775 switch (ivarVisibility) { 3776 default: assert(0 && "Unknown visitibility kind"); 3777 case tok::objc_private: return ObjCIvarDecl::Private; 3778 case tok::objc_public: return ObjCIvarDecl::Public; 3779 case tok::objc_protected: return ObjCIvarDecl::Protected; 3780 case tok::objc_package: return ObjCIvarDecl::Package; 3781 } 3782} 3783 3784/// ActOnIvar - Each ivar field of an objective-c class is passed into this 3785/// in order to create an IvarDecl object for it. 3786Sema::DeclPtrTy Sema::ActOnIvar(Scope *S, 3787 SourceLocation DeclStart, 3788 Declarator &D, ExprTy *BitfieldWidth, 3789 tok::ObjCKeywordKind Visibility) { 3790 3791 IdentifierInfo *II = D.getIdentifier(); 3792 Expr *BitWidth = (Expr*)BitfieldWidth; 3793 SourceLocation Loc = DeclStart; 3794 if (II) Loc = D.getIdentifierLoc(); 3795 3796 // FIXME: Unnamed fields can be handled in various different ways, for 3797 // example, unnamed unions inject all members into the struct namespace! 3798 3799 QualType T = GetTypeForDeclarator(D, S); 3800 bool InvalidDecl = false; 3801 if (T.isNull()) { 3802 InvalidDecl = true; 3803 T = Context.IntTy; 3804 } 3805 3806 if (BitWidth) { 3807 // 6.7.2.1p3, 6.7.2.1p4 3808 if (VerifyBitField(Loc, II, T, BitWidth)) { 3809 InvalidDecl = true; 3810 DeleteExpr(BitWidth); 3811 BitWidth = 0; 3812 } 3813 } else { 3814 // Not a bitfield. 3815 3816 // validate II. 3817 3818 } 3819 3820 // C99 6.7.2.1p8: A member of a structure or union may have any type other 3821 // than a variably modified type. 3822 if (T->isVariablyModifiedType()) { 3823 Diag(Loc, diag::err_typecheck_ivar_variable_size); 3824 InvalidDecl = true; 3825 } 3826 3827 // Get the visibility (access control) for this ivar. 3828 ObjCIvarDecl::AccessControl ac = 3829 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 3830 : ObjCIvarDecl::None; 3831 3832 // Construct the decl. 3833 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, CurContext, Loc, II, T,ac, 3834 (Expr *)BitfieldWidth); 3835 3836 if (II) { 3837 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true); 3838 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S) 3839 && !isa<TagDecl>(PrevDecl)) { 3840 Diag(Loc, diag::err_duplicate_member) << II; 3841 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3842 NewID->setInvalidDecl(); 3843 } 3844 } 3845 3846 // Process attributes attached to the ivar. 3847 ProcessDeclAttributes(NewID, D); 3848 3849 if (D.getInvalidType() || InvalidDecl) 3850 NewID->setInvalidDecl(); 3851 3852 if (II) { 3853 // FIXME: When interfaces are DeclContexts, we'll need to add 3854 // these to the interface. 3855 S->AddDecl(DeclPtrTy::make(NewID)); 3856 IdResolver.AddDecl(NewID); 3857 } 3858 3859 return DeclPtrTy::make(NewID); 3860} 3861 3862void Sema::ActOnFields(Scope* S, 3863 SourceLocation RecLoc, DeclPtrTy RecDecl, 3864 DeclPtrTy *Fields, unsigned NumFields, 3865 SourceLocation LBrac, SourceLocation RBrac, 3866 AttributeList *Attr) { 3867 Decl *EnclosingDecl = RecDecl.getAs<Decl>(); 3868 assert(EnclosingDecl && "missing record or interface decl"); 3869 3870 // If the decl this is being inserted into is invalid, then it may be a 3871 // redeclaration or some other bogus case. Don't try to add fields to it. 3872 if (EnclosingDecl->isInvalidDecl()) { 3873 // FIXME: Deallocate fields? 3874 return; 3875 } 3876 3877 3878 // Verify that all the fields are okay. 3879 unsigned NumNamedMembers = 0; 3880 llvm::SmallVector<FieldDecl*, 32> RecFields; 3881 3882 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 3883 for (unsigned i = 0; i != NumFields; ++i) { 3884 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>()); 3885 3886 // Get the type for the field. 3887 Type *FDTy = FD->getType().getTypePtr(); 3888 3889 if (!FD->isAnonymousStructOrUnion()) { 3890 // Remember all fields written by the user. 3891 RecFields.push_back(FD); 3892 } 3893 3894 // If the field is already invalid for some reason, don't emit more 3895 // diagnostics about it. 3896 if (FD->isInvalidDecl()) 3897 continue; 3898 3899 // C99 6.7.2.1p2: 3900 // A structure or union shall not contain a member with 3901 // incomplete or function type (hence, a structure shall not 3902 // contain an instance of itself, but may contain a pointer to 3903 // an instance of itself), except that the last member of a 3904 // structure with more than one named member may have incomplete 3905 // array type; such a structure (and any union containing, 3906 // possibly recursively, a member that is such a structure) 3907 // shall not be a member of a structure or an element of an 3908 // array. 3909 if (FDTy->isFunctionType()) { 3910 // Field declared as a function. 3911 Diag(FD->getLocation(), diag::err_field_declared_as_function) 3912 << FD->getDeclName(); 3913 FD->setInvalidDecl(); 3914 EnclosingDecl->setInvalidDecl(); 3915 continue; 3916 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 3917 Record && Record->isStruct()) { 3918 // Flexible array member. 3919 if (NumNamedMembers < 1) { 3920 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 3921 << FD->getDeclName(); 3922 FD->setInvalidDecl(); 3923 EnclosingDecl->setInvalidDecl(); 3924 continue; 3925 } 3926 // Okay, we have a legal flexible array member at the end of the struct. 3927 if (Record) 3928 Record->setHasFlexibleArrayMember(true); 3929 } else if (!FDTy->isDependentType() && 3930 RequireCompleteType(FD->getLocation(), FD->getType(), 3931 diag::err_field_incomplete)) { 3932 // Incomplete type 3933 FD->setInvalidDecl(); 3934 EnclosingDecl->setInvalidDecl(); 3935 continue; 3936 } else if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 3937 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 3938 // If this is a member of a union, then entire union becomes "flexible". 3939 if (Record && Record->isUnion()) { 3940 Record->setHasFlexibleArrayMember(true); 3941 } else { 3942 // If this is a struct/class and this is not the last element, reject 3943 // it. Note that GCC supports variable sized arrays in the middle of 3944 // structures. 3945 if (i != NumFields-1) 3946 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 3947 << FD->getDeclName(); 3948 else { 3949 // We support flexible arrays at the end of structs in 3950 // other structs as an extension. 3951 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 3952 << FD->getDeclName(); 3953 if (Record) 3954 Record->setHasFlexibleArrayMember(true); 3955 } 3956 } 3957 } 3958 } else if (FDTy->isObjCInterfaceType()) { 3959 /// A field cannot be an Objective-c object 3960 Diag(FD->getLocation(), diag::err_statically_allocated_object); 3961 FD->setInvalidDecl(); 3962 EnclosingDecl->setInvalidDecl(); 3963 continue; 3964 } 3965 // Keep track of the number of named members. 3966 if (FD->getIdentifier()) 3967 ++NumNamedMembers; 3968 } 3969 3970 // Okay, we successfully defined 'Record'. 3971 if (Record) { 3972 Record->completeDefinition(Context); 3973 } else { 3974 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 3975 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 3976 ID->setIVarList(ClsFields, RecFields.size(), Context); 3977 ID->setLocEnd(RBrac); 3978 3979 // Must enforce the rule that ivars in the base classes may not be 3980 // duplicates. 3981 if (ID->getSuperClass()) { 3982 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 3983 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 3984 ObjCIvarDecl* Ivar = (*IVI); 3985 IdentifierInfo *II = Ivar->getIdentifier(); 3986 ObjCIvarDecl* prevIvar = 3987 ID->getSuperClass()->lookupInstanceVariable(Context, II); 3988 if (prevIvar) { 3989 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3990 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3991 } 3992 } 3993 } 3994 } else if (ObjCImplementationDecl *IMPDecl = 3995 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 3996 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 3997 IMPDecl->setIVarList(ClsFields, RecFields.size(), Context); 3998 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 3999 } 4000 } 4001 4002 if (Attr) 4003 ProcessDeclAttributeList(Record, Attr); 4004} 4005 4006EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 4007 EnumConstantDecl *LastEnumConst, 4008 SourceLocation IdLoc, 4009 IdentifierInfo *Id, 4010 ExprArg val) { 4011 Expr *Val = (Expr *)val.get(); 4012 4013 llvm::APSInt EnumVal(32); 4014 QualType EltTy; 4015 if (Val && !Val->isTypeDependent()) { 4016 // Make sure to promote the operand type to int. 4017 UsualUnaryConversions(Val); 4018 if (Val != val.get()) { 4019 val.release(); 4020 val = Val; 4021 } 4022 4023 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 4024 SourceLocation ExpLoc; 4025 if (!Val->isValueDependent() && 4026 VerifyIntegerConstantExpression(Val, &EnumVal)) { 4027 Val = 0; 4028 } else { 4029 EltTy = Val->getType(); 4030 } 4031 } 4032 4033 if (!Val) { 4034 if (LastEnumConst) { 4035 // Assign the last value + 1. 4036 EnumVal = LastEnumConst->getInitVal(); 4037 ++EnumVal; 4038 4039 // Check for overflow on increment. 4040 if (EnumVal < LastEnumConst->getInitVal()) 4041 Diag(IdLoc, diag::warn_enum_value_overflow); 4042 4043 EltTy = LastEnumConst->getType(); 4044 } else { 4045 // First value, set to zero. 4046 EltTy = Context.IntTy; 4047 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 4048 } 4049 } 4050 4051 val.release(); 4052 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 4053 Val, EnumVal); 4054} 4055 4056 4057Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl, 4058 DeclPtrTy lastEnumConst, 4059 SourceLocation IdLoc, 4060 IdentifierInfo *Id, 4061 SourceLocation EqualLoc, ExprTy *val) { 4062 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>()); 4063 EnumConstantDecl *LastEnumConst = 4064 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>()); 4065 Expr *Val = static_cast<Expr*>(val); 4066 4067 // The scope passed in may not be a decl scope. Zip up the scope tree until 4068 // we find one that is. 4069 S = getNonFieldDeclScope(S); 4070 4071 // Verify that there isn't already something declared with this name in this 4072 // scope. 4073 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName); 4074 if (PrevDecl && PrevDecl->isTemplateParameter()) { 4075 // Maybe we will complain about the shadowed template parameter. 4076 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 4077 // Just pretend that we didn't see the previous declaration. 4078 PrevDecl = 0; 4079 } 4080 4081 if (PrevDecl) { 4082 // When in C++, we may get a TagDecl with the same name; in this case the 4083 // enum constant will 'hide' the tag. 4084 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 4085 "Received TagDecl when not in C++!"); 4086 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 4087 if (isa<EnumConstantDecl>(PrevDecl)) 4088 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 4089 else 4090 Diag(IdLoc, diag::err_redefinition) << Id; 4091 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4092 if (Val) Val->Destroy(Context); 4093 return DeclPtrTy(); 4094 } 4095 } 4096 4097 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 4098 IdLoc, Id, Owned(Val)); 4099 4100 // Register this decl in the current scope stack. 4101 if (New) 4102 PushOnScopeChains(New, S); 4103 4104 return DeclPtrTy::make(New); 4105} 4106 4107// FIXME: For consistency with ActOnFields(), we should have the parser 4108// pass in the source location for the left/right braces. 4109void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclPtrTy EnumDeclX, 4110 DeclPtrTy *Elements, unsigned NumElements) { 4111 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>()); 4112 QualType EnumType = Context.getTypeDeclType(Enum); 4113 4114 // TODO: If the result value doesn't fit in an int, it must be a long or long 4115 // long value. ISO C does not support this, but GCC does as an extension, 4116 // emit a warning. 4117 unsigned IntWidth = Context.Target.getIntWidth(); 4118 4119 // Verify that all the values are okay, compute the size of the values, and 4120 // reverse the list. 4121 unsigned NumNegativeBits = 0; 4122 unsigned NumPositiveBits = 0; 4123 4124 // Keep track of whether all elements have type int. 4125 bool AllElementsInt = true; 4126 4127 for (unsigned i = 0; i != NumElements; ++i) { 4128 EnumConstantDecl *ECD = 4129 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 4130 if (!ECD) continue; // Already issued a diagnostic. 4131 4132 // If the enum value doesn't fit in an int, emit an extension warning. 4133 const llvm::APSInt &InitVal = ECD->getInitVal(); 4134 assert(InitVal.getBitWidth() >= IntWidth && 4135 "Should have promoted value to int"); 4136 if (InitVal.getBitWidth() > IntWidth) { 4137 llvm::APSInt V(InitVal); 4138 V.trunc(IntWidth); 4139 V.extend(InitVal.getBitWidth()); 4140 if (V != InitVal) 4141 Diag(ECD->getLocation(), diag::ext_enum_value_not_int) 4142 << InitVal.toString(10); 4143 } 4144 4145 // Keep track of the size of positive and negative values. 4146 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 4147 NumPositiveBits = std::max(NumPositiveBits, 4148 (unsigned)InitVal.getActiveBits()); 4149 else 4150 NumNegativeBits = std::max(NumNegativeBits, 4151 (unsigned)InitVal.getMinSignedBits()); 4152 4153 // Keep track of whether every enum element has type int (very commmon). 4154 if (AllElementsInt) 4155 AllElementsInt = ECD->getType() == Context.IntTy; 4156 } 4157 4158 // Figure out the type that should be used for this enum. 4159 // FIXME: Support attribute(packed) on enums and -fshort-enums. 4160 QualType BestType; 4161 unsigned BestWidth; 4162 4163 if (NumNegativeBits) { 4164 // If there is a negative value, figure out the smallest integer type (of 4165 // int/long/longlong) that fits. 4166 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 4167 BestType = Context.IntTy; 4168 BestWidth = IntWidth; 4169 } else { 4170 BestWidth = Context.Target.getLongWidth(); 4171 4172 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 4173 BestType = Context.LongTy; 4174 else { 4175 BestWidth = Context.Target.getLongLongWidth(); 4176 4177 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 4178 Diag(Enum->getLocation(), diag::warn_enum_too_large); 4179 BestType = Context.LongLongTy; 4180 } 4181 } 4182 } else { 4183 // If there is no negative value, figure out which of uint, ulong, ulonglong 4184 // fits. 4185 if (NumPositiveBits <= IntWidth) { 4186 BestType = Context.UnsignedIntTy; 4187 BestWidth = IntWidth; 4188 } else if (NumPositiveBits <= 4189 (BestWidth = Context.Target.getLongWidth())) { 4190 BestType = Context.UnsignedLongTy; 4191 } else { 4192 BestWidth = Context.Target.getLongLongWidth(); 4193 assert(NumPositiveBits <= BestWidth && 4194 "How could an initializer get larger than ULL?"); 4195 BestType = Context.UnsignedLongLongTy; 4196 } 4197 } 4198 4199 // Loop over all of the enumerator constants, changing their types to match 4200 // the type of the enum if needed. 4201 for (unsigned i = 0; i != NumElements; ++i) { 4202 EnumConstantDecl *ECD = 4203 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 4204 if (!ECD) continue; // Already issued a diagnostic. 4205 4206 // Standard C says the enumerators have int type, but we allow, as an 4207 // extension, the enumerators to be larger than int size. If each 4208 // enumerator value fits in an int, type it as an int, otherwise type it the 4209 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 4210 // that X has type 'int', not 'unsigned'. 4211 if (ECD->getType() == Context.IntTy) { 4212 // Make sure the init value is signed. 4213 llvm::APSInt IV = ECD->getInitVal(); 4214 IV.setIsSigned(true); 4215 ECD->setInitVal(IV); 4216 4217 if (getLangOptions().CPlusPlus) 4218 // C++ [dcl.enum]p4: Following the closing brace of an 4219 // enum-specifier, each enumerator has the type of its 4220 // enumeration. 4221 ECD->setType(EnumType); 4222 continue; // Already int type. 4223 } 4224 4225 // Determine whether the value fits into an int. 4226 llvm::APSInt InitVal = ECD->getInitVal(); 4227 bool FitsInInt; 4228 if (InitVal.isUnsigned() || !InitVal.isNegative()) 4229 FitsInInt = InitVal.getActiveBits() < IntWidth; 4230 else 4231 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 4232 4233 // If it fits into an integer type, force it. Otherwise force it to match 4234 // the enum decl type. 4235 QualType NewTy; 4236 unsigned NewWidth; 4237 bool NewSign; 4238 if (FitsInInt) { 4239 NewTy = Context.IntTy; 4240 NewWidth = IntWidth; 4241 NewSign = true; 4242 } else if (ECD->getType() == BestType) { 4243 // Already the right type! 4244 if (getLangOptions().CPlusPlus) 4245 // C++ [dcl.enum]p4: Following the closing brace of an 4246 // enum-specifier, each enumerator has the type of its 4247 // enumeration. 4248 ECD->setType(EnumType); 4249 continue; 4250 } else { 4251 NewTy = BestType; 4252 NewWidth = BestWidth; 4253 NewSign = BestType->isSignedIntegerType(); 4254 } 4255 4256 // Adjust the APSInt value. 4257 InitVal.extOrTrunc(NewWidth); 4258 InitVal.setIsSigned(NewSign); 4259 ECD->setInitVal(InitVal); 4260 4261 // Adjust the Expr initializer and type. 4262 if (ECD->getInitExpr()) 4263 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(), 4264 /*isLvalue=*/false)); 4265 if (getLangOptions().CPlusPlus) 4266 // C++ [dcl.enum]p4: Following the closing brace of an 4267 // enum-specifier, each enumerator has the type of its 4268 // enumeration. 4269 ECD->setType(EnumType); 4270 else 4271 ECD->setType(NewTy); 4272 } 4273 4274 Enum->completeDefinition(Context, BestType); 4275} 4276 4277Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 4278 ExprArg expr) { 4279 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release()); 4280 4281 return DeclPtrTy::make(FileScopeAsmDecl::Create(Context, CurContext, 4282 Loc, AsmString)); 4283} 4284 4285