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