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