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