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