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