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