SemaDecl.cpp revision 79e6bd379773447a74cc3e579d9081e4c5cb6d63
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/CXXFieldCollector.h" 18#include "clang/Sema/Scope.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "TypeLocBuilder.h" 21#include "clang/AST/APValue.h" 22#include "clang/AST/ASTConsumer.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/CXXInheritance.h" 25#include "clang/AST/DeclCXX.h" 26#include "clang/AST/DeclObjC.h" 27#include "clang/AST/DeclTemplate.h" 28#include "clang/AST/EvaluatedExprVisitor.h" 29#include "clang/AST/ExprCXX.h" 30#include "clang/AST/StmtCXX.h" 31#include "clang/AST/CharUnits.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/ParsedTemplate.h" 34#include "clang/Parse/ParseDiagnostic.h" 35#include "clang/Basic/PartialDiagnostic.h" 36#include "clang/Basic/SourceManager.h" 37#include "clang/Basic/TargetInfo.h" 38// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 39#include "clang/Lex/Preprocessor.h" 40#include "clang/Lex/HeaderSearch.h" 41#include "llvm/ADT/Triple.h" 42#include <algorithm> 43#include <cstring> 44#include <functional> 45using namespace clang; 46using namespace sema; 47 48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 49 if (OwnedType) { 50 Decl *Group[2] = { OwnedType, Ptr }; 51 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 52 } 53 54 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 55} 56 57/// \brief If the identifier refers to a type name within this scope, 58/// return the declaration of that type. 59/// 60/// This routine performs ordinary name lookup of the identifier II 61/// within the given scope, with optional C++ scope specifier SS, to 62/// determine whether the name refers to a type. If so, returns an 63/// opaque pointer (actually a QualType) corresponding to that 64/// type. Otherwise, returns NULL. 65/// 66/// If name lookup results in an ambiguity, this routine will complain 67/// and then return NULL. 68ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 69 Scope *S, CXXScopeSpec *SS, 70 bool isClassName, bool HasTrailingDot, 71 ParsedType ObjectTypePtr, 72 bool WantNontrivialTypeSourceInfo) { 73 // Determine where we will perform name lookup. 74 DeclContext *LookupCtx = 0; 75 if (ObjectTypePtr) { 76 QualType ObjectType = ObjectTypePtr.get(); 77 if (ObjectType->isRecordType()) 78 LookupCtx = computeDeclContext(ObjectType); 79 } else if (SS && SS->isNotEmpty()) { 80 LookupCtx = computeDeclContext(*SS, false); 81 82 if (!LookupCtx) { 83 if (isDependentScopeSpecifier(*SS)) { 84 // C++ [temp.res]p3: 85 // A qualified-id that refers to a type and in which the 86 // nested-name-specifier depends on a template-parameter (14.6.2) 87 // shall be prefixed by the keyword typename to indicate that the 88 // qualified-id denotes a type, forming an 89 // elaborated-type-specifier (7.1.5.3). 90 // 91 // We therefore do not perform any name lookup if the result would 92 // refer to a member of an unknown specialization. 93 if (!isClassName) 94 return ParsedType(); 95 96 // We know from the grammar that this name refers to a type, 97 // so build a dependent node to describe the type. 98 if (WantNontrivialTypeSourceInfo) 99 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 100 101 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 102 QualType T = 103 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 104 II, NameLoc); 105 106 return ParsedType::make(T); 107 } 108 109 return ParsedType(); 110 } 111 112 if (!LookupCtx->isDependentContext() && 113 RequireCompleteDeclContext(*SS, LookupCtx)) 114 return ParsedType(); 115 } 116 117 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 118 // lookup for class-names. 119 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 120 LookupOrdinaryName; 121 LookupResult Result(*this, &II, NameLoc, Kind); 122 if (LookupCtx) { 123 // Perform "qualified" name lookup into the declaration context we 124 // computed, which is either the type of the base of a member access 125 // expression or the declaration context associated with a prior 126 // nested-name-specifier. 127 LookupQualifiedName(Result, LookupCtx); 128 129 if (ObjectTypePtr && Result.empty()) { 130 // C++ [basic.lookup.classref]p3: 131 // If the unqualified-id is ~type-name, the type-name is looked up 132 // in the context of the entire postfix-expression. If the type T of 133 // the object expression is of a class type C, the type-name is also 134 // looked up in the scope of class C. At least one of the lookups shall 135 // find a name that refers to (possibly cv-qualified) T. 136 LookupName(Result, S); 137 } 138 } else { 139 // Perform unqualified name lookup. 140 LookupName(Result, S); 141 } 142 143 NamedDecl *IIDecl = 0; 144 switch (Result.getResultKind()) { 145 case LookupResult::NotFound: 146 case LookupResult::NotFoundInCurrentInstantiation: 147 case LookupResult::FoundOverloaded: 148 case LookupResult::FoundUnresolvedValue: 149 Result.suppressDiagnostics(); 150 return ParsedType(); 151 152 case LookupResult::Ambiguous: 153 // Recover from type-hiding ambiguities by hiding the type. We'll 154 // do the lookup again when looking for an object, and we can 155 // diagnose the error then. If we don't do this, then the error 156 // about hiding the type will be immediately followed by an error 157 // that only makes sense if the identifier was treated like a type. 158 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 159 Result.suppressDiagnostics(); 160 return ParsedType(); 161 } 162 163 // Look to see if we have a type anywhere in the list of results. 164 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 165 Res != ResEnd; ++Res) { 166 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 167 if (!IIDecl || 168 (*Res)->getLocation().getRawEncoding() < 169 IIDecl->getLocation().getRawEncoding()) 170 IIDecl = *Res; 171 } 172 } 173 174 if (!IIDecl) { 175 // None of the entities we found is a type, so there is no way 176 // to even assume that the result is a type. In this case, don't 177 // complain about the ambiguity. The parser will either try to 178 // perform this lookup again (e.g., as an object name), which 179 // will produce the ambiguity, or will complain that it expected 180 // a type name. 181 Result.suppressDiagnostics(); 182 return ParsedType(); 183 } 184 185 // We found a type within the ambiguous lookup; diagnose the 186 // ambiguity and then return that type. This might be the right 187 // answer, or it might not be, but it suppresses any attempt to 188 // perform the name lookup again. 189 break; 190 191 case LookupResult::Found: 192 IIDecl = Result.getFoundDecl(); 193 break; 194 } 195 196 assert(IIDecl && "Didn't find decl"); 197 198 QualType T; 199 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 200 DiagnoseUseOfDecl(IIDecl, NameLoc); 201 202 if (T.isNull()) 203 T = Context.getTypeDeclType(TD); 204 205 if (SS && SS->isNotEmpty()) { 206 if (WantNontrivialTypeSourceInfo) { 207 // Construct a type with type-source information. 208 TypeLocBuilder Builder; 209 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 210 211 T = getElaboratedType(ETK_None, *SS, T); 212 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 213 ElabTL.setKeywordLoc(SourceLocation()); 214 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 215 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 216 } else { 217 T = getElaboratedType(ETK_None, *SS, T); 218 } 219 } 220 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 221 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 222 if (!HasTrailingDot) 223 T = Context.getObjCInterfaceType(IDecl); 224 } 225 226 if (T.isNull()) { 227 // If it's not plausibly a type, suppress diagnostics. 228 Result.suppressDiagnostics(); 229 return ParsedType(); 230 } 231 return ParsedType::make(T); 232} 233 234/// isTagName() - This method is called *for error recovery purposes only* 235/// to determine if the specified name is a valid tag name ("struct foo"). If 236/// so, this returns the TST for the tag corresponding to it (TST_enum, 237/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 238/// where the user forgot to specify the tag. 239DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 240 // Do a tag name lookup in this scope. 241 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 242 LookupName(R, S, false); 243 R.suppressDiagnostics(); 244 if (R.getResultKind() == LookupResult::Found) 245 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 246 switch (TD->getTagKind()) { 247 default: return DeclSpec::TST_unspecified; 248 case TTK_Struct: return DeclSpec::TST_struct; 249 case TTK_Union: return DeclSpec::TST_union; 250 case TTK_Class: return DeclSpec::TST_class; 251 case TTK_Enum: return DeclSpec::TST_enum; 252 } 253 } 254 255 return DeclSpec::TST_unspecified; 256} 257 258/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 259/// if a CXXScopeSpec's type is equal to the type of one of the base classes 260/// then downgrade the missing typename error to a warning. 261/// This is needed for MSVC compatibility; Example: 262/// @code 263/// template<class T> class A { 264/// public: 265/// typedef int TYPE; 266/// }; 267/// template<class T> class B : public A<T> { 268/// public: 269/// A<T>::TYPE a; // no typename required because A<T> is a base class. 270/// }; 271/// @endcode 272bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS) { 273 if (CurContext->isRecord()) { 274 const Type *Ty = SS->getScopeRep()->getAsType(); 275 276 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 277 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 278 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 279 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 280 return true; 281 } 282 return false; 283} 284 285bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 286 SourceLocation IILoc, 287 Scope *S, 288 CXXScopeSpec *SS, 289 ParsedType &SuggestedType) { 290 // We don't have anything to suggest (yet). 291 SuggestedType = ParsedType(); 292 293 // There may have been a typo in the name of the type. Look up typo 294 // results, in case we have something that we can suggest. 295 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc), 296 LookupOrdinaryName, S, SS, NULL, 297 false, CTC_Type)) { 298 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 299 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 300 301 if (Corrected.isKeyword()) { 302 // We corrected to a keyword. 303 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 304 Diag(IILoc, diag::err_unknown_typename_suggest) 305 << &II << CorrectedQuotedStr; 306 return true; 307 } else { 308 NamedDecl *Result = Corrected.getCorrectionDecl(); 309 if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 310 !Result->isInvalidDecl()) { 311 // We found a similarly-named type or interface; suggest that. 312 if (!SS || !SS->isSet()) 313 Diag(IILoc, diag::err_unknown_typename_suggest) 314 << &II << CorrectedQuotedStr 315 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 316 else if (DeclContext *DC = computeDeclContext(*SS, false)) 317 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 318 << &II << DC << CorrectedQuotedStr << SS->getRange() 319 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 320 else 321 llvm_unreachable("could not have corrected a typo here"); 322 323 Diag(Result->getLocation(), diag::note_previous_decl) 324 << CorrectedQuotedStr; 325 326 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 327 false, false, ParsedType(), 328 /*NonTrivialTypeSourceInfo=*/true); 329 return true; 330 } 331 } 332 } 333 334 if (getLangOptions().CPlusPlus) { 335 // See if II is a class template that the user forgot to pass arguments to. 336 UnqualifiedId Name; 337 Name.setIdentifier(&II, IILoc); 338 CXXScopeSpec EmptySS; 339 TemplateTy TemplateResult; 340 bool MemberOfUnknownSpecialization; 341 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 342 Name, ParsedType(), true, TemplateResult, 343 MemberOfUnknownSpecialization) == TNK_Type_template) { 344 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 345 Diag(IILoc, diag::err_template_missing_args) << TplName; 346 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 347 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 348 << TplDecl->getTemplateParameters()->getSourceRange(); 349 } 350 return true; 351 } 352 } 353 354 // FIXME: Should we move the logic that tries to recover from a missing tag 355 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 356 357 if (!SS || (!SS->isSet() && !SS->isInvalid())) 358 Diag(IILoc, diag::err_unknown_typename) << &II; 359 else if (DeclContext *DC = computeDeclContext(*SS, false)) 360 Diag(IILoc, diag::err_typename_nested_not_found) 361 << &II << DC << SS->getRange(); 362 else if (isDependentScopeSpecifier(*SS)) { 363 unsigned DiagID = diag::err_typename_missing; 364 if (getLangOptions().Microsoft && isMicrosoftMissingTypename(SS)) 365 DiagID = diag::warn_typename_missing; 366 367 Diag(SS->getRange().getBegin(), DiagID) 368 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 369 << SourceRange(SS->getRange().getBegin(), IILoc) 370 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 371 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc).get(); 372 } else { 373 assert(SS && SS->isInvalid() && 374 "Invalid scope specifier has already been diagnosed"); 375 } 376 377 return true; 378} 379 380/// \brief Determine whether the given result set contains either a type name 381/// or 382static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 383 bool CheckTemplate = R.getSema().getLangOptions().CPlusPlus && 384 NextToken.is(tok::less); 385 386 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 387 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 388 return true; 389 390 if (CheckTemplate && isa<TemplateDecl>(*I)) 391 return true; 392 } 393 394 return false; 395} 396 397Sema::NameClassification Sema::ClassifyName(Scope *S, 398 CXXScopeSpec &SS, 399 IdentifierInfo *&Name, 400 SourceLocation NameLoc, 401 const Token &NextToken) { 402 DeclarationNameInfo NameInfo(Name, NameLoc); 403 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 404 405 if (NextToken.is(tok::coloncolon)) { 406 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 407 QualType(), false, SS, 0, false); 408 409 } 410 411 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 412 LookupParsedName(Result, S, &SS, !CurMethod); 413 414 // Perform lookup for Objective-C instance variables (including automatically 415 // synthesized instance variables), if we're in an Objective-C method. 416 // FIXME: This lookup really, really needs to be folded in to the normal 417 // unqualified lookup mechanism. 418 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 419 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 420 if (E.get() || E.isInvalid()) 421 return E; 422 423 // Synthesize ivars lazily. 424 if (getLangOptions().ObjCDefaultSynthProperties && 425 getLangOptions().ObjCNonFragileABI2) { 426 if (SynthesizeProvisionalIvar(Result, Name, NameLoc)) { 427 if (const ObjCPropertyDecl *Property = 428 canSynthesizeProvisionalIvar(Name)) { 429 Diag(NameLoc, diag::warn_synthesized_ivar_access) << Name; 430 Diag(Property->getLocation(), diag::note_property_declare); 431 } 432 433 // FIXME: This is strange. Shouldn't we just take the ivar returned 434 // from SynthesizeProvisionalIvar and continue with that? 435 E = LookupInObjCMethod(Result, S, Name, true); 436 if (E.get() || E.isInvalid()) 437 return E; 438 } 439 } 440 } 441 442 bool SecondTry = false; 443 bool IsFilteredTemplateName = false; 444 445Corrected: 446 switch (Result.getResultKind()) { 447 case LookupResult::NotFound: 448 // If an unqualified-id is followed by a '(', then we have a function 449 // call. 450 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 451 // In C++, this is an ADL-only call. 452 // FIXME: Reference? 453 if (getLangOptions().CPlusPlus) 454 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 455 456 // C90 6.3.2.2: 457 // If the expression that precedes the parenthesized argument list in a 458 // function call consists solely of an identifier, and if no 459 // declaration is visible for this identifier, the identifier is 460 // implicitly declared exactly as if, in the innermost block containing 461 // the function call, the declaration 462 // 463 // extern int identifier (); 464 // 465 // appeared. 466 // 467 // We also allow this in C99 as an extension. 468 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 469 Result.addDecl(D); 470 Result.resolveKind(); 471 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 472 } 473 } 474 475 // In C, we first see whether there is a tag type by the same name, in 476 // which case it's likely that the user just forget to write "enum", 477 // "struct", or "union". 478 if (!getLangOptions().CPlusPlus && !SecondTry) { 479 Result.clear(LookupTagName); 480 LookupParsedName(Result, S, &SS); 481 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 482 const char *TagName = 0; 483 const char *FixItTagName = 0; 484 switch (Tag->getTagKind()) { 485 case TTK_Class: 486 TagName = "class"; 487 FixItTagName = "class "; 488 break; 489 490 case TTK_Enum: 491 TagName = "enum"; 492 FixItTagName = "enum "; 493 break; 494 495 case TTK_Struct: 496 TagName = "struct"; 497 FixItTagName = "struct "; 498 break; 499 500 case TTK_Union: 501 TagName = "union"; 502 FixItTagName = "union "; 503 break; 504 } 505 506 Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 507 << Name << TagName << getLangOptions().CPlusPlus 508 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 509 break; 510 } 511 512 Result.clear(LookupOrdinaryName); 513 } 514 515 // Perform typo correction to determine if there is another name that is 516 // close to this name. 517 if (!SecondTry) { 518 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 519 Result.getLookupKind(), S, &SS)) { 520 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 521 unsigned QualifiedDiag = diag::err_no_member_suggest; 522 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 523 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 524 525 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 526 NamedDecl *UnderlyingFirstDecl 527 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 528 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 529 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 530 UnqualifiedDiag = diag::err_no_template_suggest; 531 QualifiedDiag = diag::err_no_member_template_suggest; 532 } else if (UnderlyingFirstDecl && 533 (isa<TypeDecl>(UnderlyingFirstDecl) || 534 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 535 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 536 UnqualifiedDiag = diag::err_unknown_typename_suggest; 537 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 538 } 539 540 if (Corrected.getCorrectionSpecifier()) 541 SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), SourceRange(NameLoc)); 542 543 if (SS.isEmpty()) 544 Diag(NameLoc, UnqualifiedDiag) 545 << Name << CorrectedQuotedStr 546 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 547 else 548 Diag(NameLoc, QualifiedDiag) 549 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 550 << SS.getRange() 551 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 552 553 // Update the name, so that the caller has the new name. 554 Name = Corrected.getCorrectionAsIdentifierInfo(); 555 556 // Also update the LookupResult... 557 // FIXME: This should probably go away at some point 558 Result.clear(); 559 Result.setLookupName(Corrected.getCorrection()); 560 if (FirstDecl) Result.addDecl(FirstDecl); 561 562 // Typo correction corrected to a keyword. 563 if (Corrected.isKeyword()) 564 return Corrected.getCorrectionAsIdentifierInfo(); 565 566 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 567 << CorrectedQuotedStr; 568 569 // If we found an Objective-C instance variable, let 570 // LookupInObjCMethod build the appropriate expression to 571 // reference the ivar. 572 // FIXME: This is a gross hack. 573 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 574 Result.clear(); 575 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 576 return move(E); 577 } 578 579 goto Corrected; 580 } 581 } 582 583 // We failed to correct; just fall through and let the parser deal with it. 584 Result.suppressDiagnostics(); 585 return NameClassification::Unknown(); 586 587 case LookupResult::NotFoundInCurrentInstantiation: 588 // We performed name lookup into the current instantiation, and there were 589 // dependent bases, so we treat this result the same way as any other 590 // dependent nested-name-specifier. 591 592 // C++ [temp.res]p2: 593 // A name used in a template declaration or definition and that is 594 // dependent on a template-parameter is assumed not to name a type 595 // unless the applicable name lookup finds a type name or the name is 596 // qualified by the keyword typename. 597 // 598 // FIXME: If the next token is '<', we might want to ask the parser to 599 // perform some heroics to see if we actually have a 600 // template-argument-list, which would indicate a missing 'template' 601 // keyword here. 602 return BuildDependentDeclRefExpr(SS, NameInfo, /*TemplateArgs=*/0); 603 604 case LookupResult::Found: 605 case LookupResult::FoundOverloaded: 606 case LookupResult::FoundUnresolvedValue: 607 break; 608 609 case LookupResult::Ambiguous: 610 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 611 hasAnyAcceptableTemplateNames(Result)) { 612 // C++ [temp.local]p3: 613 // A lookup that finds an injected-class-name (10.2) can result in an 614 // ambiguity in certain cases (for example, if it is found in more than 615 // one base class). If all of the injected-class-names that are found 616 // refer to specializations of the same class template, and if the name 617 // is followed by a template-argument-list, the reference refers to the 618 // class template itself and not a specialization thereof, and is not 619 // ambiguous. 620 // 621 // This filtering can make an ambiguous result into an unambiguous one, 622 // so try again after filtering out template names. 623 FilterAcceptableTemplateNames(Result); 624 if (!Result.isAmbiguous()) { 625 IsFilteredTemplateName = true; 626 break; 627 } 628 } 629 630 // Diagnose the ambiguity and return an error. 631 return NameClassification::Error(); 632 } 633 634 if (getLangOptions().CPlusPlus && NextToken.is(tok::less) && 635 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 636 // C++ [temp.names]p3: 637 // After name lookup (3.4) finds that a name is a template-name or that 638 // an operator-function-id or a literal- operator-id refers to a set of 639 // overloaded functions any member of which is a function template if 640 // this is followed by a <, the < is always taken as the delimiter of a 641 // template-argument-list and never as the less-than operator. 642 if (!IsFilteredTemplateName) 643 FilterAcceptableTemplateNames(Result); 644 645 if (!Result.empty()) { 646 bool IsFunctionTemplate; 647 TemplateName Template; 648 if (Result.end() - Result.begin() > 1) { 649 IsFunctionTemplate = true; 650 Template = Context.getOverloadedTemplateName(Result.begin(), 651 Result.end()); 652 } else { 653 TemplateDecl *TD 654 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 655 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 656 657 if (SS.isSet() && !SS.isInvalid()) 658 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 659 /*TemplateKeyword=*/false, 660 TD); 661 else 662 Template = TemplateName(TD); 663 } 664 665 if (IsFunctionTemplate) { 666 // Function templates always go through overload resolution, at which 667 // point we'll perform the various checks (e.g., accessibility) we need 668 // to based on which function we selected. 669 Result.suppressDiagnostics(); 670 671 return NameClassification::FunctionTemplate(Template); 672 } 673 674 return NameClassification::TypeTemplate(Template); 675 } 676 } 677 678 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 679 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 680 DiagnoseUseOfDecl(Type, NameLoc); 681 QualType T = Context.getTypeDeclType(Type); 682 return ParsedType::make(T); 683 } 684 685 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 686 if (!Class) { 687 // FIXME: It's unfortunate that we don't have a Type node for handling this. 688 if (ObjCCompatibleAliasDecl *Alias 689 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 690 Class = Alias->getClassInterface(); 691 } 692 693 if (Class) { 694 DiagnoseUseOfDecl(Class, NameLoc); 695 696 if (NextToken.is(tok::period)) { 697 // Interface. <something> is parsed as a property reference expression. 698 // Just return "unknown" as a fall-through for now. 699 Result.suppressDiagnostics(); 700 return NameClassification::Unknown(); 701 } 702 703 QualType T = Context.getObjCInterfaceType(Class); 704 return ParsedType::make(T); 705 } 706 707 if (!Result.empty() && (*Result.begin())->isCXXClassMember()) 708 return BuildPossibleImplicitMemberExpr(SS, Result, 0); 709 710 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 711 return BuildDeclarationNameExpr(SS, Result, ADL); 712} 713 714// Determines the context to return to after temporarily entering a 715// context. This depends in an unnecessarily complicated way on the 716// exact ordering of callbacks from the parser. 717DeclContext *Sema::getContainingDC(DeclContext *DC) { 718 719 // Functions defined inline within classes aren't parsed until we've 720 // finished parsing the top-level class, so the top-level class is 721 // the context we'll need to return to. 722 if (isa<FunctionDecl>(DC)) { 723 DC = DC->getLexicalParent(); 724 725 // A function not defined within a class will always return to its 726 // lexical context. 727 if (!isa<CXXRecordDecl>(DC)) 728 return DC; 729 730 // A C++ inline method/friend is parsed *after* the topmost class 731 // it was declared in is fully parsed ("complete"); the topmost 732 // class is the context we need to return to. 733 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 734 DC = RD; 735 736 // Return the declaration context of the topmost class the inline method is 737 // declared in. 738 return DC; 739 } 740 741 // ObjCMethodDecls are parsed (for some reason) outside the context 742 // of the class. 743 if (isa<ObjCMethodDecl>(DC)) 744 return DC->getLexicalParent()->getLexicalParent(); 745 746 return DC->getLexicalParent(); 747} 748 749void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 750 assert(getContainingDC(DC) == CurContext && 751 "The next DeclContext should be lexically contained in the current one."); 752 CurContext = DC; 753 S->setEntity(DC); 754} 755 756void Sema::PopDeclContext() { 757 assert(CurContext && "DeclContext imbalance!"); 758 759 CurContext = getContainingDC(CurContext); 760 assert(CurContext && "Popped translation unit!"); 761} 762 763/// EnterDeclaratorContext - Used when we must lookup names in the context 764/// of a declarator's nested name specifier. 765/// 766void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 767 // C++0x [basic.lookup.unqual]p13: 768 // A name used in the definition of a static data member of class 769 // X (after the qualified-id of the static member) is looked up as 770 // if the name was used in a member function of X. 771 // C++0x [basic.lookup.unqual]p14: 772 // If a variable member of a namespace is defined outside of the 773 // scope of its namespace then any name used in the definition of 774 // the variable member (after the declarator-id) is looked up as 775 // if the definition of the variable member occurred in its 776 // namespace. 777 // Both of these imply that we should push a scope whose context 778 // is the semantic context of the declaration. We can't use 779 // PushDeclContext here because that context is not necessarily 780 // lexically contained in the current context. Fortunately, 781 // the containing scope should have the appropriate information. 782 783 assert(!S->getEntity() && "scope already has entity"); 784 785#ifndef NDEBUG 786 Scope *Ancestor = S->getParent(); 787 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 788 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 789#endif 790 791 CurContext = DC; 792 S->setEntity(DC); 793} 794 795void Sema::ExitDeclaratorContext(Scope *S) { 796 assert(S->getEntity() == CurContext && "Context imbalance!"); 797 798 // Switch back to the lexical context. The safety of this is 799 // enforced by an assert in EnterDeclaratorContext. 800 Scope *Ancestor = S->getParent(); 801 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 802 CurContext = (DeclContext*) Ancestor->getEntity(); 803 804 // We don't need to do anything with the scope, which is going to 805 // disappear. 806} 807 808/// \brief Determine whether we allow overloading of the function 809/// PrevDecl with another declaration. 810/// 811/// This routine determines whether overloading is possible, not 812/// whether some new function is actually an overload. It will return 813/// true in C++ (where we can always provide overloads) or, as an 814/// extension, in C when the previous function is already an 815/// overloaded function declaration or has the "overloadable" 816/// attribute. 817static bool AllowOverloadingOfFunction(LookupResult &Previous, 818 ASTContext &Context) { 819 if (Context.getLangOptions().CPlusPlus) 820 return true; 821 822 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 823 return true; 824 825 return (Previous.getResultKind() == LookupResult::Found 826 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 827} 828 829/// Add this decl to the scope shadowed decl chains. 830void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 831 // Move up the scope chain until we find the nearest enclosing 832 // non-transparent context. The declaration will be introduced into this 833 // scope. 834 while (S->getEntity() && 835 ((DeclContext *)S->getEntity())->isTransparentContext()) 836 S = S->getParent(); 837 838 // Add scoped declarations into their context, so that they can be 839 // found later. Declarations without a context won't be inserted 840 // into any context. 841 if (AddToContext) 842 CurContext->addDecl(D); 843 844 // Out-of-line definitions shouldn't be pushed into scope in C++. 845 // Out-of-line variable and function definitions shouldn't even in C. 846 if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 847 D->isOutOfLine()) 848 return; 849 850 // Template instantiations should also not be pushed into scope. 851 if (isa<FunctionDecl>(D) && 852 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 853 return; 854 855 // If this replaces anything in the current scope, 856 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 857 IEnd = IdResolver.end(); 858 for (; I != IEnd; ++I) { 859 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 860 S->RemoveDecl(*I); 861 IdResolver.RemoveDecl(*I); 862 863 // Should only need to replace one decl. 864 break; 865 } 866 } 867 868 S->AddDecl(D); 869 870 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 871 // Implicitly-generated labels may end up getting generated in an order that 872 // isn't strictly lexical, which breaks name lookup. Be careful to insert 873 // the label at the appropriate place in the identifier chain. 874 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 875 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 876 if (IDC == CurContext) { 877 if (!S->isDeclScope(*I)) 878 continue; 879 } else if (IDC->Encloses(CurContext)) 880 break; 881 } 882 883 IdResolver.InsertDeclAfter(I, D); 884 } else { 885 IdResolver.AddDecl(D); 886 } 887} 888 889bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 890 bool ExplicitInstantiationOrSpecialization) { 891 return IdResolver.isDeclInScope(D, Ctx, Context, S, 892 ExplicitInstantiationOrSpecialization); 893} 894 895Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 896 DeclContext *TargetDC = DC->getPrimaryContext(); 897 do { 898 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 899 if (ScopeDC->getPrimaryContext() == TargetDC) 900 return S; 901 } while ((S = S->getParent())); 902 903 return 0; 904} 905 906static bool isOutOfScopePreviousDeclaration(NamedDecl *, 907 DeclContext*, 908 ASTContext&); 909 910/// Filters out lookup results that don't fall within the given scope 911/// as determined by isDeclInScope. 912void Sema::FilterLookupForScope(LookupResult &R, 913 DeclContext *Ctx, Scope *S, 914 bool ConsiderLinkage, 915 bool ExplicitInstantiationOrSpecialization) { 916 LookupResult::Filter F = R.makeFilter(); 917 while (F.hasNext()) { 918 NamedDecl *D = F.next(); 919 920 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 921 continue; 922 923 if (ConsiderLinkage && 924 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 925 continue; 926 927 F.erase(); 928 } 929 930 F.done(); 931} 932 933static bool isUsingDecl(NamedDecl *D) { 934 return isa<UsingShadowDecl>(D) || 935 isa<UnresolvedUsingTypenameDecl>(D) || 936 isa<UnresolvedUsingValueDecl>(D); 937} 938 939/// Removes using shadow declarations from the lookup results. 940static void RemoveUsingDecls(LookupResult &R) { 941 LookupResult::Filter F = R.makeFilter(); 942 while (F.hasNext()) 943 if (isUsingDecl(F.next())) 944 F.erase(); 945 946 F.done(); 947} 948 949/// \brief Check for this common pattern: 950/// @code 951/// class S { 952/// S(const S&); // DO NOT IMPLEMENT 953/// void operator=(const S&); // DO NOT IMPLEMENT 954/// }; 955/// @endcode 956static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 957 // FIXME: Should check for private access too but access is set after we get 958 // the decl here. 959 if (D->doesThisDeclarationHaveABody()) 960 return false; 961 962 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 963 return CD->isCopyConstructor(); 964 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 965 return Method->isCopyAssignmentOperator(); 966 return false; 967} 968 969bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 970 assert(D); 971 972 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 973 return false; 974 975 // Ignore class templates. 976 if (D->getDeclContext()->isDependentContext() || 977 D->getLexicalDeclContext()->isDependentContext()) 978 return false; 979 980 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 981 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 982 return false; 983 984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 985 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 986 return false; 987 } else { 988 // 'static inline' functions are used in headers; don't warn. 989 if (FD->getStorageClass() == SC_Static && 990 FD->isInlineSpecified()) 991 return false; 992 } 993 994 if (FD->doesThisDeclarationHaveABody() && 995 Context.DeclMustBeEmitted(FD)) 996 return false; 997 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 998 if (!VD->isFileVarDecl() || 999 VD->getType().isConstant(Context) || 1000 Context.DeclMustBeEmitted(VD)) 1001 return false; 1002 1003 if (VD->isStaticDataMember() && 1004 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1005 return false; 1006 1007 } else { 1008 return false; 1009 } 1010 1011 // Only warn for unused decls internal to the translation unit. 1012 if (D->getLinkage() == ExternalLinkage) 1013 return false; 1014 1015 return true; 1016} 1017 1018void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1019 if (!D) 1020 return; 1021 1022 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1023 const FunctionDecl *First = FD->getFirstDeclaration(); 1024 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1025 return; // First should already be in the vector. 1026 } 1027 1028 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1029 const VarDecl *First = VD->getFirstDeclaration(); 1030 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1031 return; // First should already be in the vector. 1032 } 1033 1034 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1035 UnusedFileScopedDecls.push_back(D); 1036 } 1037 1038static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1039 if (D->isInvalidDecl()) 1040 return false; 1041 1042 if (D->isUsed() || D->hasAttr<UnusedAttr>()) 1043 return false; 1044 1045 if (isa<LabelDecl>(D)) 1046 return true; 1047 1048 // White-list anything that isn't a local variable. 1049 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1050 !D->getDeclContext()->isFunctionOrMethod()) 1051 return false; 1052 1053 // Types of valid local variables should be complete, so this should succeed. 1054 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1055 1056 // White-list anything with an __attribute__((unused)) type. 1057 QualType Ty = VD->getType(); 1058 1059 // Only look at the outermost level of typedef. 1060 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 1061 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1062 return false; 1063 } 1064 1065 // If we failed to complete the type for some reason, or if the type is 1066 // dependent, don't diagnose the variable. 1067 if (Ty->isIncompleteType() || Ty->isDependentType()) 1068 return false; 1069 1070 if (const TagType *TT = Ty->getAs<TagType>()) { 1071 const TagDecl *Tag = TT->getDecl(); 1072 if (Tag->hasAttr<UnusedAttr>()) 1073 return false; 1074 1075 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1076 // FIXME: Checking for the presence of a user-declared constructor 1077 // isn't completely accurate; we'd prefer to check that the initializer 1078 // has no side effects. 1079 if (RD->hasUserDeclaredConstructor() || !RD->hasTrivialDestructor()) 1080 return false; 1081 } 1082 } 1083 1084 // TODO: __attribute__((unused)) templates? 1085 } 1086 1087 return true; 1088} 1089 1090/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1091/// unless they are marked attr(unused). 1092void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1093 if (!ShouldDiagnoseUnusedDecl(D)) 1094 return; 1095 1096 unsigned DiagID; 1097 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1098 DiagID = diag::warn_unused_exception_param; 1099 else if (isa<LabelDecl>(D)) 1100 DiagID = diag::warn_unused_label; 1101 else 1102 DiagID = diag::warn_unused_variable; 1103 1104 Diag(D->getLocation(), DiagID) << D->getDeclName(); 1105} 1106 1107static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1108 // Verify that we have no forward references left. If so, there was a goto 1109 // or address of a label taken, but no definition of it. Label fwd 1110 // definitions are indicated with a null substmt. 1111 if (L->getStmt() == 0) 1112 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1113} 1114 1115void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1116 if (S->decl_empty()) return; 1117 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1118 "Scope shouldn't contain decls!"); 1119 1120 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1121 I != E; ++I) { 1122 Decl *TmpD = (*I); 1123 assert(TmpD && "This decl didn't get pushed??"); 1124 1125 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1126 NamedDecl *D = cast<NamedDecl>(TmpD); 1127 1128 if (!D->getDeclName()) continue; 1129 1130 // Diagnose unused variables in this scope. 1131 if (!S->hasErrorOccurred()) 1132 DiagnoseUnusedDecl(D); 1133 1134 // If this was a forward reference to a label, verify it was defined. 1135 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1136 CheckPoppedLabel(LD, *this); 1137 1138 // Remove this name from our lexical scope. 1139 IdResolver.RemoveDecl(D); 1140 } 1141} 1142 1143/// \brief Look for an Objective-C class in the translation unit. 1144/// 1145/// \param Id The name of the Objective-C class we're looking for. If 1146/// typo-correction fixes this name, the Id will be updated 1147/// to the fixed name. 1148/// 1149/// \param IdLoc The location of the name in the translation unit. 1150/// 1151/// \param TypoCorrection If true, this routine will attempt typo correction 1152/// if there is no class with the given name. 1153/// 1154/// \returns The declaration of the named Objective-C class, or NULL if the 1155/// class could not be found. 1156ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1157 SourceLocation IdLoc, 1158 bool DoTypoCorrection) { 1159 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1160 // creation from this context. 1161 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1162 1163 if (!IDecl && DoTypoCorrection) { 1164 // Perform typo correction at the given location, but only if we 1165 // find an Objective-C class name. 1166 TypoCorrection C; 1167 if ((C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1168 TUScope, NULL, NULL, false, CTC_NoKeywords)) && 1169 (IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 1170 Diag(IdLoc, diag::err_undef_interface_suggest) 1171 << Id << IDecl->getDeclName() 1172 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1173 Diag(IDecl->getLocation(), diag::note_previous_decl) 1174 << IDecl->getDeclName(); 1175 1176 Id = IDecl->getIdentifier(); 1177 } 1178 } 1179 1180 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1181} 1182 1183/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1184/// from S, where a non-field would be declared. This routine copes 1185/// with the difference between C and C++ scoping rules in structs and 1186/// unions. For example, the following code is well-formed in C but 1187/// ill-formed in C++: 1188/// @code 1189/// struct S6 { 1190/// enum { BAR } e; 1191/// }; 1192/// 1193/// void test_S6() { 1194/// struct S6 a; 1195/// a.e = BAR; 1196/// } 1197/// @endcode 1198/// For the declaration of BAR, this routine will return a different 1199/// scope. The scope S will be the scope of the unnamed enumeration 1200/// within S6. In C++, this routine will return the scope associated 1201/// with S6, because the enumeration's scope is a transparent 1202/// context but structures can contain non-field names. In C, this 1203/// routine will return the translation unit scope, since the 1204/// enumeration's scope is a transparent context and structures cannot 1205/// contain non-field names. 1206Scope *Sema::getNonFieldDeclScope(Scope *S) { 1207 while (((S->getFlags() & Scope::DeclScope) == 0) || 1208 (S->getEntity() && 1209 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1210 (S->isClassScope() && !getLangOptions().CPlusPlus)) 1211 S = S->getParent(); 1212 return S; 1213} 1214 1215/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1216/// file scope. lazily create a decl for it. ForRedeclaration is true 1217/// if we're creating this built-in in anticipation of redeclaring the 1218/// built-in. 1219NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1220 Scope *S, bool ForRedeclaration, 1221 SourceLocation Loc) { 1222 Builtin::ID BID = (Builtin::ID)bid; 1223 1224 ASTContext::GetBuiltinTypeError Error; 1225 QualType R = Context.GetBuiltinType(BID, Error); 1226 switch (Error) { 1227 case ASTContext::GE_None: 1228 // Okay 1229 break; 1230 1231 case ASTContext::GE_Missing_stdio: 1232 if (ForRedeclaration) 1233 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1234 << Context.BuiltinInfo.GetName(BID); 1235 return 0; 1236 1237 case ASTContext::GE_Missing_setjmp: 1238 if (ForRedeclaration) 1239 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1240 << Context.BuiltinInfo.GetName(BID); 1241 return 0; 1242 } 1243 1244 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1245 Diag(Loc, diag::ext_implicit_lib_function_decl) 1246 << Context.BuiltinInfo.GetName(BID) 1247 << R; 1248 if (Context.BuiltinInfo.getHeaderName(BID) && 1249 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1250 != Diagnostic::Ignored) 1251 Diag(Loc, diag::note_please_include_header) 1252 << Context.BuiltinInfo.getHeaderName(BID) 1253 << Context.BuiltinInfo.GetName(BID); 1254 } 1255 1256 FunctionDecl *New = FunctionDecl::Create(Context, 1257 Context.getTranslationUnitDecl(), 1258 Loc, Loc, II, R, /*TInfo=*/0, 1259 SC_Extern, 1260 SC_None, false, 1261 /*hasPrototype=*/true); 1262 New->setImplicit(); 1263 1264 // Create Decl objects for each parameter, adding them to the 1265 // FunctionDecl. 1266 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1267 llvm::SmallVector<ParmVarDecl*, 16> Params; 1268 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1269 ParmVarDecl *parm = 1270 ParmVarDecl::Create(Context, New, SourceLocation(), 1271 SourceLocation(), 0, 1272 FT->getArgType(i), /*TInfo=*/0, 1273 SC_None, SC_None, 0); 1274 parm->setScopeInfo(0, i); 1275 Params.push_back(parm); 1276 } 1277 New->setParams(Params.data(), Params.size()); 1278 } 1279 1280 AddKnownFunctionAttributes(New); 1281 1282 // TUScope is the translation-unit scope to insert this function into. 1283 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1284 // relate Scopes to DeclContexts, and probably eliminate CurContext 1285 // entirely, but we're not there yet. 1286 DeclContext *SavedContext = CurContext; 1287 CurContext = Context.getTranslationUnitDecl(); 1288 PushOnScopeChains(New, TUScope); 1289 CurContext = SavedContext; 1290 return New; 1291} 1292 1293/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1294/// same name and scope as a previous declaration 'Old'. Figure out 1295/// how to resolve this situation, merging decls or emitting 1296/// diagnostics as appropriate. If there was an error, set New to be invalid. 1297/// 1298void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1299 // If the new decl is known invalid already, don't bother doing any 1300 // merging checks. 1301 if (New->isInvalidDecl()) return; 1302 1303 // Allow multiple definitions for ObjC built-in typedefs. 1304 // FIXME: Verify the underlying types are equivalent! 1305 if (getLangOptions().ObjC1) { 1306 const IdentifierInfo *TypeID = New->getIdentifier(); 1307 switch (TypeID->getLength()) { 1308 default: break; 1309 case 2: 1310 if (!TypeID->isStr("id")) 1311 break; 1312 Context.ObjCIdRedefinitionType = New->getUnderlyingType(); 1313 // Install the built-in type for 'id', ignoring the current definition. 1314 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1315 return; 1316 case 5: 1317 if (!TypeID->isStr("Class")) 1318 break; 1319 Context.ObjCClassRedefinitionType = New->getUnderlyingType(); 1320 // Install the built-in type for 'Class', ignoring the current definition. 1321 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1322 return; 1323 case 3: 1324 if (!TypeID->isStr("SEL")) 1325 break; 1326 Context.ObjCSelRedefinitionType = New->getUnderlyingType(); 1327 // Install the built-in type for 'SEL', ignoring the current definition. 1328 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1329 return; 1330 case 8: 1331 if (!TypeID->isStr("Protocol")) 1332 break; 1333 Context.setObjCProtoType(New->getUnderlyingType()); 1334 return; 1335 } 1336 // Fall through - the typedef name was not a builtin type. 1337 } 1338 1339 // Verify the old decl was also a type. 1340 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1341 if (!Old) { 1342 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1343 << New->getDeclName(); 1344 1345 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1346 if (OldD->getLocation().isValid()) 1347 Diag(OldD->getLocation(), diag::note_previous_definition); 1348 1349 return New->setInvalidDecl(); 1350 } 1351 1352 // If the old declaration is invalid, just give up here. 1353 if (Old->isInvalidDecl()) 1354 return New->setInvalidDecl(); 1355 1356 // Determine the "old" type we'll use for checking and diagnostics. 1357 QualType OldType; 1358 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1359 OldType = OldTypedef->getUnderlyingType(); 1360 else 1361 OldType = Context.getTypeDeclType(Old); 1362 1363 // If the typedef types are not identical, reject them in all languages and 1364 // with any extensions enabled. 1365 1366 if (OldType != New->getUnderlyingType() && 1367 Context.getCanonicalType(OldType) != 1368 Context.getCanonicalType(New->getUnderlyingType())) { 1369 int Kind = 0; 1370 if (isa<TypeAliasDecl>(Old)) 1371 Kind = 1; 1372 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1373 << Kind << New->getUnderlyingType() << OldType; 1374 if (Old->getLocation().isValid()) 1375 Diag(Old->getLocation(), diag::note_previous_definition); 1376 return New->setInvalidDecl(); 1377 } 1378 1379 // The types match. Link up the redeclaration chain if the old 1380 // declaration was a typedef. 1381 // FIXME: this is a potential source of weirdness if the type 1382 // spellings don't match exactly. 1383 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1384 New->setPreviousDeclaration(Typedef); 1385 1386 if (getLangOptions().Microsoft) 1387 return; 1388 1389 if (getLangOptions().CPlusPlus) { 1390 // C++ [dcl.typedef]p2: 1391 // In a given non-class scope, a typedef specifier can be used to 1392 // redefine the name of any type declared in that scope to refer 1393 // to the type to which it already refers. 1394 if (!isa<CXXRecordDecl>(CurContext)) 1395 return; 1396 1397 // C++0x [dcl.typedef]p4: 1398 // In a given class scope, a typedef specifier can be used to redefine 1399 // any class-name declared in that scope that is not also a typedef-name 1400 // to refer to the type to which it already refers. 1401 // 1402 // This wording came in via DR424, which was a correction to the 1403 // wording in DR56, which accidentally banned code like: 1404 // 1405 // struct S { 1406 // typedef struct A { } A; 1407 // }; 1408 // 1409 // in the C++03 standard. We implement the C++0x semantics, which 1410 // allow the above but disallow 1411 // 1412 // struct S { 1413 // typedef int I; 1414 // typedef int I; 1415 // }; 1416 // 1417 // since that was the intent of DR56. 1418 if (!isa<TypedefNameDecl>(Old)) 1419 return; 1420 1421 Diag(New->getLocation(), diag::err_redefinition) 1422 << New->getDeclName(); 1423 Diag(Old->getLocation(), diag::note_previous_definition); 1424 return New->setInvalidDecl(); 1425 } 1426 1427 // If we have a redefinition of a typedef in C, emit a warning. This warning 1428 // is normally mapped to an error, but can be controlled with 1429 // -Wtypedef-redefinition. If either the original or the redefinition is 1430 // in a system header, don't emit this for compatibility with GCC. 1431 if (getDiagnostics().getSuppressSystemWarnings() && 1432 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1433 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1434 return; 1435 1436 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1437 << New->getDeclName(); 1438 Diag(Old->getLocation(), diag::note_previous_definition); 1439 return; 1440} 1441 1442/// DeclhasAttr - returns true if decl Declaration already has the target 1443/// attribute. 1444static bool 1445DeclHasAttr(const Decl *D, const Attr *A) { 1446 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1447 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1448 if ((*i)->getKind() == A->getKind()) { 1449 // FIXME: Don't hardcode this check 1450 if (OA && isa<OwnershipAttr>(*i)) 1451 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1452 return true; 1453 } 1454 1455 return false; 1456} 1457 1458/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1459static void mergeDeclAttributes(Decl *newDecl, const Decl *oldDecl, 1460 ASTContext &C) { 1461 if (!oldDecl->hasAttrs()) 1462 return; 1463 1464 bool foundAny = newDecl->hasAttrs(); 1465 1466 // Ensure that any moving of objects within the allocated map is done before 1467 // we process them. 1468 if (!foundAny) newDecl->setAttrs(AttrVec()); 1469 1470 for (specific_attr_iterator<InheritableAttr> 1471 i = oldDecl->specific_attr_begin<InheritableAttr>(), 1472 e = oldDecl->specific_attr_end<InheritableAttr>(); i != e; ++i) { 1473 if (!DeclHasAttr(newDecl, *i)) { 1474 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(C)); 1475 newAttr->setInherited(true); 1476 newDecl->addAttr(newAttr); 1477 foundAny = true; 1478 } 1479 } 1480 1481 if (!foundAny) newDecl->dropAttrs(); 1482} 1483 1484/// mergeParamDeclAttributes - Copy attributes from the old parameter 1485/// to the new one. 1486static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1487 const ParmVarDecl *oldDecl, 1488 ASTContext &C) { 1489 if (!oldDecl->hasAttrs()) 1490 return; 1491 1492 bool foundAny = newDecl->hasAttrs(); 1493 1494 // Ensure that any moving of objects within the allocated map is 1495 // done before we process them. 1496 if (!foundAny) newDecl->setAttrs(AttrVec()); 1497 1498 for (specific_attr_iterator<InheritableParamAttr> 1499 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1500 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1501 if (!DeclHasAttr(newDecl, *i)) { 1502 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1503 newAttr->setInherited(true); 1504 newDecl->addAttr(newAttr); 1505 foundAny = true; 1506 } 1507 } 1508 1509 if (!foundAny) newDecl->dropAttrs(); 1510} 1511 1512namespace { 1513 1514/// Used in MergeFunctionDecl to keep track of function parameters in 1515/// C. 1516struct GNUCompatibleParamWarning { 1517 ParmVarDecl *OldParm; 1518 ParmVarDecl *NewParm; 1519 QualType PromotedType; 1520}; 1521 1522} 1523 1524/// getSpecialMember - get the special member enum for a method. 1525Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1526 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1527 if (Ctor->isDefaultConstructor()) 1528 return Sema::CXXDefaultConstructor; 1529 1530 if (Ctor->isCopyConstructor()) 1531 return Sema::CXXCopyConstructor; 1532 1533 if (Ctor->isMoveConstructor()) 1534 return Sema::CXXMoveConstructor; 1535 } else if (isa<CXXDestructorDecl>(MD)) { 1536 return Sema::CXXDestructor; 1537 } else if (MD->isCopyAssignmentOperator()) { 1538 return Sema::CXXCopyAssignment; 1539 } 1540 1541 return Sema::CXXInvalid; 1542} 1543 1544/// canRedefineFunction - checks if a function can be redefined. Currently, 1545/// only extern inline functions can be redefined, and even then only in 1546/// GNU89 mode. 1547static bool canRedefineFunction(const FunctionDecl *FD, 1548 const LangOptions& LangOpts) { 1549 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 1550 !LangOpts.CPlusPlus && 1551 FD->isInlineSpecified() && 1552 FD->getStorageClass() == SC_Extern); 1553} 1554 1555/// MergeFunctionDecl - We just parsed a function 'New' from 1556/// declarator D which has the same name and scope as a previous 1557/// declaration 'Old'. Figure out how to resolve this situation, 1558/// merging decls or emitting diagnostics as appropriate. 1559/// 1560/// In C++, New and Old must be declarations that are not 1561/// overloaded. Use IsOverload to determine whether New and Old are 1562/// overloaded, and to select the Old declaration that New should be 1563/// merged with. 1564/// 1565/// Returns true if there was an error, false otherwise. 1566bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 1567 // Verify the old decl was also a function. 1568 FunctionDecl *Old = 0; 1569 if (FunctionTemplateDecl *OldFunctionTemplate 1570 = dyn_cast<FunctionTemplateDecl>(OldD)) 1571 Old = OldFunctionTemplate->getTemplatedDecl(); 1572 else 1573 Old = dyn_cast<FunctionDecl>(OldD); 1574 if (!Old) { 1575 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 1576 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 1577 Diag(Shadow->getTargetDecl()->getLocation(), 1578 diag::note_using_decl_target); 1579 Diag(Shadow->getUsingDecl()->getLocation(), 1580 diag::note_using_decl) << 0; 1581 return true; 1582 } 1583 1584 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1585 << New->getDeclName(); 1586 Diag(OldD->getLocation(), diag::note_previous_definition); 1587 return true; 1588 } 1589 1590 // Determine whether the previous declaration was a definition, 1591 // implicit declaration, or a declaration. 1592 diag::kind PrevDiag; 1593 if (Old->isThisDeclarationADefinition()) 1594 PrevDiag = diag::note_previous_definition; 1595 else if (Old->isImplicit()) 1596 PrevDiag = diag::note_previous_implicit_declaration; 1597 else 1598 PrevDiag = diag::note_previous_declaration; 1599 1600 QualType OldQType = Context.getCanonicalType(Old->getType()); 1601 QualType NewQType = Context.getCanonicalType(New->getType()); 1602 1603 // Don't complain about this if we're in GNU89 mode and the old function 1604 // is an extern inline function. 1605 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 1606 New->getStorageClass() == SC_Static && 1607 Old->getStorageClass() != SC_Static && 1608 !canRedefineFunction(Old, getLangOptions())) { 1609 if (getLangOptions().Microsoft) { 1610 Diag(New->getLocation(), diag::warn_static_non_static) << New; 1611 Diag(Old->getLocation(), PrevDiag); 1612 } else { 1613 Diag(New->getLocation(), diag::err_static_non_static) << New; 1614 Diag(Old->getLocation(), PrevDiag); 1615 return true; 1616 } 1617 } 1618 1619 // If a function is first declared with a calling convention, but is 1620 // later declared or defined without one, the second decl assumes the 1621 // calling convention of the first. 1622 // 1623 // For the new decl, we have to look at the NON-canonical type to tell the 1624 // difference between a function that really doesn't have a calling 1625 // convention and one that is declared cdecl. That's because in 1626 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 1627 // because it is the default calling convention. 1628 // 1629 // Note also that we DO NOT return at this point, because we still have 1630 // other tests to run. 1631 const FunctionType *OldType = cast<FunctionType>(OldQType); 1632 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 1633 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 1634 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 1635 bool RequiresAdjustment = false; 1636 if (OldTypeInfo.getCC() != CC_Default && 1637 NewTypeInfo.getCC() == CC_Default) { 1638 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 1639 RequiresAdjustment = true; 1640 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 1641 NewTypeInfo.getCC())) { 1642 // Calling conventions really aren't compatible, so complain. 1643 Diag(New->getLocation(), diag::err_cconv_change) 1644 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 1645 << (OldTypeInfo.getCC() == CC_Default) 1646 << (OldTypeInfo.getCC() == CC_Default ? "" : 1647 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 1648 Diag(Old->getLocation(), diag::note_previous_declaration); 1649 return true; 1650 } 1651 1652 // FIXME: diagnose the other way around? 1653 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 1654 NewTypeInfo = NewTypeInfo.withNoReturn(true); 1655 RequiresAdjustment = true; 1656 } 1657 1658 // Merge regparm attribute. 1659 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 1660 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 1661 if (NewTypeInfo.getHasRegParm()) { 1662 Diag(New->getLocation(), diag::err_regparm_mismatch) 1663 << NewType->getRegParmType() 1664 << OldType->getRegParmType(); 1665 Diag(Old->getLocation(), diag::note_previous_declaration); 1666 return true; 1667 } 1668 1669 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 1670 RequiresAdjustment = true; 1671 } 1672 1673 if (RequiresAdjustment) { 1674 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 1675 New->setType(QualType(NewType, 0)); 1676 NewQType = Context.getCanonicalType(New->getType()); 1677 } 1678 1679 if (getLangOptions().CPlusPlus) { 1680 // (C++98 13.1p2): 1681 // Certain function declarations cannot be overloaded: 1682 // -- Function declarations that differ only in the return type 1683 // cannot be overloaded. 1684 QualType OldReturnType = OldType->getResultType(); 1685 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 1686 QualType ResQT; 1687 if (OldReturnType != NewReturnType) { 1688 if (NewReturnType->isObjCObjectPointerType() 1689 && OldReturnType->isObjCObjectPointerType()) 1690 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 1691 if (ResQT.isNull()) { 1692 if (New->isCXXClassMember() && New->isOutOfLine()) 1693 Diag(New->getLocation(), 1694 diag::err_member_def_does_not_match_ret_type) << New; 1695 else 1696 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 1697 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1698 return true; 1699 } 1700 else 1701 NewQType = ResQT; 1702 } 1703 1704 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1705 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1706 if (OldMethod && NewMethod) { 1707 // Preserve triviality. 1708 NewMethod->setTrivial(OldMethod->isTrivial()); 1709 1710 bool isFriend = NewMethod->getFriendObjectKind(); 1711 1712 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) { 1713 // -- Member function declarations with the same name and the 1714 // same parameter types cannot be overloaded if any of them 1715 // is a static member function declaration. 1716 if (OldMethod->isStatic() || NewMethod->isStatic()) { 1717 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 1718 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1719 return true; 1720 } 1721 1722 // C++ [class.mem]p1: 1723 // [...] A member shall not be declared twice in the 1724 // member-specification, except that a nested class or member 1725 // class template can be declared and then later defined. 1726 unsigned NewDiag; 1727 if (isa<CXXConstructorDecl>(OldMethod)) 1728 NewDiag = diag::err_constructor_redeclared; 1729 else if (isa<CXXDestructorDecl>(NewMethod)) 1730 NewDiag = diag::err_destructor_redeclared; 1731 else if (isa<CXXConversionDecl>(NewMethod)) 1732 NewDiag = diag::err_conv_function_redeclared; 1733 else 1734 NewDiag = diag::err_member_redeclared; 1735 1736 Diag(New->getLocation(), NewDiag); 1737 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1738 1739 // Complain if this is an explicit declaration of a special 1740 // member that was initially declared implicitly. 1741 // 1742 // As an exception, it's okay to befriend such methods in order 1743 // to permit the implicit constructor/destructor/operator calls. 1744 } else if (OldMethod->isImplicit()) { 1745 if (isFriend) { 1746 NewMethod->setImplicit(); 1747 } else { 1748 Diag(NewMethod->getLocation(), 1749 diag::err_definition_of_implicitly_declared_member) 1750 << New << getSpecialMember(OldMethod); 1751 return true; 1752 } 1753 } else if (OldMethod->isExplicitlyDefaulted()) { 1754 Diag(NewMethod->getLocation(), 1755 diag::err_definition_of_explicitly_defaulted_member) 1756 << getSpecialMember(OldMethod); 1757 return true; 1758 } 1759 } 1760 1761 // (C++98 8.3.5p3): 1762 // All declarations for a function shall agree exactly in both the 1763 // return type and the parameter-type-list. 1764 // We also want to respect all the extended bits except noreturn. 1765 1766 // noreturn should now match unless the old type info didn't have it. 1767 QualType OldQTypeForComparison = OldQType; 1768 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 1769 assert(OldQType == QualType(OldType, 0)); 1770 const FunctionType *OldTypeForComparison 1771 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 1772 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 1773 assert(OldQTypeForComparison.isCanonical()); 1774 } 1775 1776 if (OldQTypeForComparison == NewQType) 1777 return MergeCompatibleFunctionDecls(New, Old); 1778 1779 // Fall through for conflicting redeclarations and redefinitions. 1780 } 1781 1782 // C: Function types need to be compatible, not identical. This handles 1783 // duplicate function decls like "void f(int); void f(enum X);" properly. 1784 if (!getLangOptions().CPlusPlus && 1785 Context.typesAreCompatible(OldQType, NewQType)) { 1786 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 1787 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 1788 const FunctionProtoType *OldProto = 0; 1789 if (isa<FunctionNoProtoType>(NewFuncType) && 1790 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 1791 // The old declaration provided a function prototype, but the 1792 // new declaration does not. Merge in the prototype. 1793 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 1794 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 1795 OldProto->arg_type_end()); 1796 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 1797 ParamTypes.data(), ParamTypes.size(), 1798 OldProto->getExtProtoInfo()); 1799 New->setType(NewQType); 1800 New->setHasInheritedPrototype(); 1801 1802 // Synthesize a parameter for each argument type. 1803 llvm::SmallVector<ParmVarDecl*, 16> Params; 1804 for (FunctionProtoType::arg_type_iterator 1805 ParamType = OldProto->arg_type_begin(), 1806 ParamEnd = OldProto->arg_type_end(); 1807 ParamType != ParamEnd; ++ParamType) { 1808 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 1809 SourceLocation(), 1810 SourceLocation(), 0, 1811 *ParamType, /*TInfo=*/0, 1812 SC_None, SC_None, 1813 0); 1814 Param->setScopeInfo(0, Params.size()); 1815 Param->setImplicit(); 1816 Params.push_back(Param); 1817 } 1818 1819 New->setParams(Params.data(), Params.size()); 1820 } 1821 1822 return MergeCompatibleFunctionDecls(New, Old); 1823 } 1824 1825 // GNU C permits a K&R definition to follow a prototype declaration 1826 // if the declared types of the parameters in the K&R definition 1827 // match the types in the prototype declaration, even when the 1828 // promoted types of the parameters from the K&R definition differ 1829 // from the types in the prototype. GCC then keeps the types from 1830 // the prototype. 1831 // 1832 // If a variadic prototype is followed by a non-variadic K&R definition, 1833 // the K&R definition becomes variadic. This is sort of an edge case, but 1834 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 1835 // C99 6.9.1p8. 1836 if (!getLangOptions().CPlusPlus && 1837 Old->hasPrototype() && !New->hasPrototype() && 1838 New->getType()->getAs<FunctionProtoType>() && 1839 Old->getNumParams() == New->getNumParams()) { 1840 llvm::SmallVector<QualType, 16> ArgTypes; 1841 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 1842 const FunctionProtoType *OldProto 1843 = Old->getType()->getAs<FunctionProtoType>(); 1844 const FunctionProtoType *NewProto 1845 = New->getType()->getAs<FunctionProtoType>(); 1846 1847 // Determine whether this is the GNU C extension. 1848 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 1849 NewProto->getResultType()); 1850 bool LooseCompatible = !MergedReturn.isNull(); 1851 for (unsigned Idx = 0, End = Old->getNumParams(); 1852 LooseCompatible && Idx != End; ++Idx) { 1853 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 1854 ParmVarDecl *NewParm = New->getParamDecl(Idx); 1855 if (Context.typesAreCompatible(OldParm->getType(), 1856 NewProto->getArgType(Idx))) { 1857 ArgTypes.push_back(NewParm->getType()); 1858 } else if (Context.typesAreCompatible(OldParm->getType(), 1859 NewParm->getType(), 1860 /*CompareUnqualified=*/true)) { 1861 GNUCompatibleParamWarning Warn 1862 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 1863 Warnings.push_back(Warn); 1864 ArgTypes.push_back(NewParm->getType()); 1865 } else 1866 LooseCompatible = false; 1867 } 1868 1869 if (LooseCompatible) { 1870 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 1871 Diag(Warnings[Warn].NewParm->getLocation(), 1872 diag::ext_param_promoted_not_compatible_with_prototype) 1873 << Warnings[Warn].PromotedType 1874 << Warnings[Warn].OldParm->getType(); 1875 if (Warnings[Warn].OldParm->getLocation().isValid()) 1876 Diag(Warnings[Warn].OldParm->getLocation(), 1877 diag::note_previous_declaration); 1878 } 1879 1880 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 1881 ArgTypes.size(), 1882 OldProto->getExtProtoInfo())); 1883 return MergeCompatibleFunctionDecls(New, Old); 1884 } 1885 1886 // Fall through to diagnose conflicting types. 1887 } 1888 1889 // A function that has already been declared has been redeclared or defined 1890 // with a different type- show appropriate diagnostic 1891 if (unsigned BuiltinID = Old->getBuiltinID()) { 1892 // The user has declared a builtin function with an incompatible 1893 // signature. 1894 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 1895 // The function the user is redeclaring is a library-defined 1896 // function like 'malloc' or 'printf'. Warn about the 1897 // redeclaration, then pretend that we don't know about this 1898 // library built-in. 1899 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 1900 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 1901 << Old << Old->getType(); 1902 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 1903 Old->setInvalidDecl(); 1904 return false; 1905 } 1906 1907 PrevDiag = diag::note_previous_builtin_declaration; 1908 } 1909 1910 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 1911 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 1912 return true; 1913} 1914 1915/// \brief Completes the merge of two function declarations that are 1916/// known to be compatible. 1917/// 1918/// This routine handles the merging of attributes and other 1919/// properties of function declarations form the old declaration to 1920/// the new declaration, once we know that New is in fact a 1921/// redeclaration of Old. 1922/// 1923/// \returns false 1924bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 1925 // Merge the attributes 1926 mergeDeclAttributes(New, Old, Context); 1927 1928 // Merge the storage class. 1929 if (Old->getStorageClass() != SC_Extern && 1930 Old->getStorageClass() != SC_None) 1931 New->setStorageClass(Old->getStorageClass()); 1932 1933 // Merge "pure" flag. 1934 if (Old->isPure()) 1935 New->setPure(); 1936 1937 // Merge attributes from the parameters. These can mismatch with K&R 1938 // declarations. 1939 if (New->getNumParams() == Old->getNumParams()) 1940 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 1941 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 1942 Context); 1943 1944 if (getLangOptions().CPlusPlus) 1945 return MergeCXXFunctionDecl(New, Old); 1946 1947 return false; 1948} 1949 1950 1951void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 1952 const ObjCMethodDecl *oldMethod) { 1953 // Merge the attributes. 1954 mergeDeclAttributes(newMethod, oldMethod, Context); 1955 1956 // Merge attributes from the parameters. 1957 for (ObjCMethodDecl::param_iterator oi = oldMethod->param_begin(), 1958 ni = newMethod->param_begin(), ne = newMethod->param_end(); 1959 ni != ne; ++ni, ++oi) 1960 mergeParamDeclAttributes(*ni, *oi, Context); 1961 1962 CheckObjCMethodOverride(newMethod, oldMethod, true); 1963} 1964 1965/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 1966/// scope as a previous declaration 'Old'. Figure out how to merge their types, 1967/// emitting diagnostics as appropriate. 1968/// 1969/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 1970/// to here in AddInitializerToDecl and AddCXXDirectInitializerToDecl. We can't 1971/// check them before the initializer is attached. 1972/// 1973void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 1974 if (New->isInvalidDecl() || Old->isInvalidDecl()) 1975 return; 1976 1977 QualType MergedT; 1978 if (getLangOptions().CPlusPlus) { 1979 AutoType *AT = New->getType()->getContainedAutoType(); 1980 if (AT && !AT->isDeduced()) { 1981 // We don't know what the new type is until the initializer is attached. 1982 return; 1983 } else if (Context.hasSameType(New->getType(), Old->getType())) { 1984 // These could still be something that needs exception specs checked. 1985 return MergeVarDeclExceptionSpecs(New, Old); 1986 } 1987 // C++ [basic.link]p10: 1988 // [...] the types specified by all declarations referring to a given 1989 // object or function shall be identical, except that declarations for an 1990 // array object can specify array types that differ by the presence or 1991 // absence of a major array bound (8.3.4). 1992 else if (Old->getType()->isIncompleteArrayType() && 1993 New->getType()->isArrayType()) { 1994 CanQual<ArrayType> OldArray 1995 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 1996 CanQual<ArrayType> NewArray 1997 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 1998 if (OldArray->getElementType() == NewArray->getElementType()) 1999 MergedT = New->getType(); 2000 } else if (Old->getType()->isArrayType() && 2001 New->getType()->isIncompleteArrayType()) { 2002 CanQual<ArrayType> OldArray 2003 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 2004 CanQual<ArrayType> NewArray 2005 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 2006 if (OldArray->getElementType() == NewArray->getElementType()) 2007 MergedT = Old->getType(); 2008 } else if (New->getType()->isObjCObjectPointerType() 2009 && Old->getType()->isObjCObjectPointerType()) { 2010 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2011 Old->getType()); 2012 } 2013 } else { 2014 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2015 } 2016 if (MergedT.isNull()) { 2017 Diag(New->getLocation(), diag::err_redefinition_different_type) 2018 << New->getDeclName(); 2019 Diag(Old->getLocation(), diag::note_previous_definition); 2020 return New->setInvalidDecl(); 2021 } 2022 New->setType(MergedT); 2023} 2024 2025/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2026/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2027/// situation, merging decls or emitting diagnostics as appropriate. 2028/// 2029/// Tentative definition rules (C99 6.9.2p2) are checked by 2030/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2031/// definitions here, since the initializer hasn't been attached. 2032/// 2033void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2034 // If the new decl is already invalid, don't do any other checking. 2035 if (New->isInvalidDecl()) 2036 return; 2037 2038 // Verify the old decl was also a variable. 2039 VarDecl *Old = 0; 2040 if (!Previous.isSingleResult() || 2041 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2042 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2043 << New->getDeclName(); 2044 Diag(Previous.getRepresentativeDecl()->getLocation(), 2045 diag::note_previous_definition); 2046 return New->setInvalidDecl(); 2047 } 2048 2049 // C++ [class.mem]p1: 2050 // A member shall not be declared twice in the member-specification [...] 2051 // 2052 // Here, we need only consider static data members. 2053 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2054 Diag(New->getLocation(), diag::err_duplicate_member) 2055 << New->getIdentifier(); 2056 Diag(Old->getLocation(), diag::note_previous_declaration); 2057 New->setInvalidDecl(); 2058 } 2059 2060 mergeDeclAttributes(New, Old, Context); 2061 // Warn if an already-declared variable is made a weak_import in a subsequent declaration 2062 if (New->getAttr<WeakImportAttr>() && 2063 Old->getStorageClass() == SC_None && 2064 !Old->getAttr<WeakImportAttr>()) { 2065 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2066 Diag(Old->getLocation(), diag::note_previous_definition); 2067 // Remove weak_import attribute on new declaration. 2068 New->dropAttr<WeakImportAttr>(); 2069 } 2070 2071 // Merge the types. 2072 MergeVarDeclTypes(New, Old); 2073 if (New->isInvalidDecl()) 2074 return; 2075 2076 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2077 if (New->getStorageClass() == SC_Static && 2078 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2079 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2080 Diag(Old->getLocation(), diag::note_previous_definition); 2081 return New->setInvalidDecl(); 2082 } 2083 // C99 6.2.2p4: 2084 // For an identifier declared with the storage-class specifier 2085 // extern in a scope in which a prior declaration of that 2086 // identifier is visible,23) if the prior declaration specifies 2087 // internal or external linkage, the linkage of the identifier at 2088 // the later declaration is the same as the linkage specified at 2089 // the prior declaration. If no prior declaration is visible, or 2090 // if the prior declaration specifies no linkage, then the 2091 // identifier has external linkage. 2092 if (New->hasExternalStorage() && Old->hasLinkage()) 2093 /* Okay */; 2094 else if (New->getStorageClass() != SC_Static && 2095 Old->getStorageClass() == SC_Static) { 2096 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2097 Diag(Old->getLocation(), diag::note_previous_definition); 2098 return New->setInvalidDecl(); 2099 } 2100 2101 // Check if extern is followed by non-extern and vice-versa. 2102 if (New->hasExternalStorage() && 2103 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2104 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2105 Diag(Old->getLocation(), diag::note_previous_definition); 2106 return New->setInvalidDecl(); 2107 } 2108 if (Old->hasExternalStorage() && 2109 !New->hasLinkage() && New->isLocalVarDecl()) { 2110 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2111 Diag(Old->getLocation(), diag::note_previous_definition); 2112 return New->setInvalidDecl(); 2113 } 2114 2115 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2116 2117 // FIXME: The test for external storage here seems wrong? We still 2118 // need to check for mismatches. 2119 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2120 // Don't complain about out-of-line definitions of static members. 2121 !(Old->getLexicalDeclContext()->isRecord() && 2122 !New->getLexicalDeclContext()->isRecord())) { 2123 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2124 Diag(Old->getLocation(), diag::note_previous_definition); 2125 return New->setInvalidDecl(); 2126 } 2127 2128 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2129 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2130 Diag(Old->getLocation(), diag::note_previous_definition); 2131 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2132 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2133 Diag(Old->getLocation(), diag::note_previous_definition); 2134 } 2135 2136 // C++ doesn't have tentative definitions, so go right ahead and check here. 2137 const VarDecl *Def; 2138 if (getLangOptions().CPlusPlus && 2139 New->isThisDeclarationADefinition() == VarDecl::Definition && 2140 (Def = Old->getDefinition())) { 2141 Diag(New->getLocation(), diag::err_redefinition) 2142 << New->getDeclName(); 2143 Diag(Def->getLocation(), diag::note_previous_definition); 2144 New->setInvalidDecl(); 2145 return; 2146 } 2147 // c99 6.2.2 P4. 2148 // For an identifier declared with the storage-class specifier extern in a 2149 // scope in which a prior declaration of that identifier is visible, if 2150 // the prior declaration specifies internal or external linkage, the linkage 2151 // of the identifier at the later declaration is the same as the linkage 2152 // specified at the prior declaration. 2153 // FIXME. revisit this code. 2154 if (New->hasExternalStorage() && 2155 Old->getLinkage() == InternalLinkage && 2156 New->getDeclContext() == Old->getDeclContext()) 2157 New->setStorageClass(Old->getStorageClass()); 2158 2159 // Keep a chain of previous declarations. 2160 New->setPreviousDeclaration(Old); 2161 2162 // Inherit access appropriately. 2163 New->setAccess(Old->getAccess()); 2164} 2165 2166/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2167/// no declarator (e.g. "struct foo;") is parsed. 2168Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2169 DeclSpec &DS) { 2170 return ParsedFreeStandingDeclSpec(S, AS, DS, 2171 MultiTemplateParamsArg(*this, 0, 0)); 2172} 2173 2174/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2175/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2176/// parameters to cope with template friend declarations. 2177Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2178 DeclSpec &DS, 2179 MultiTemplateParamsArg TemplateParams) { 2180 Decl *TagD = 0; 2181 TagDecl *Tag = 0; 2182 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2183 DS.getTypeSpecType() == DeclSpec::TST_struct || 2184 DS.getTypeSpecType() == DeclSpec::TST_union || 2185 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2186 TagD = DS.getRepAsDecl(); 2187 2188 if (!TagD) // We probably had an error 2189 return 0; 2190 2191 // Note that the above type specs guarantee that the 2192 // type rep is a Decl, whereas in many of the others 2193 // it's a Type. 2194 Tag = dyn_cast<TagDecl>(TagD); 2195 } 2196 2197 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2198 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2199 // or incomplete types shall not be restrict-qualified." 2200 if (TypeQuals & DeclSpec::TQ_restrict) 2201 Diag(DS.getRestrictSpecLoc(), 2202 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2203 << DS.getSourceRange(); 2204 } 2205 2206 if (DS.isFriendSpecified()) { 2207 // If we're dealing with a decl but not a TagDecl, assume that 2208 // whatever routines created it handled the friendship aspect. 2209 if (TagD && !Tag) 2210 return 0; 2211 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2212 } 2213 2214 // Track whether we warned about the fact that there aren't any 2215 // declarators. 2216 bool emittedWarning = false; 2217 2218 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2219 ProcessDeclAttributeList(S, Record, DS.getAttributes().getList()); 2220 2221 if (!Record->getDeclName() && Record->isDefinition() && 2222 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2223 if (getLangOptions().CPlusPlus || 2224 Record->getDeclContext()->isRecord()) 2225 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2226 2227 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2228 << DS.getSourceRange(); 2229 emittedWarning = true; 2230 } 2231 } 2232 2233 // Check for Microsoft C extension: anonymous struct. 2234 if (getLangOptions().Microsoft && !getLangOptions().CPlusPlus && 2235 CurContext->isRecord() && 2236 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2237 // Handle 2 kinds of anonymous struct: 2238 // struct STRUCT; 2239 // and 2240 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2241 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2242 if ((Record && Record->getDeclName() && !Record->isDefinition()) || 2243 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2244 DS.getRepAsType().get()->isStructureType())) { 2245 Diag(DS.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct) 2246 << DS.getSourceRange(); 2247 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2248 } 2249 } 2250 2251 if (getLangOptions().CPlusPlus && 2252 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2253 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2254 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2255 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2256 Diag(Enum->getLocation(), diag::ext_no_declarators) 2257 << DS.getSourceRange(); 2258 emittedWarning = true; 2259 } 2260 2261 // Skip all the checks below if we have a type error. 2262 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2263 2264 if (!DS.isMissingDeclaratorOk()) { 2265 // Warn about typedefs of enums without names, since this is an 2266 // extension in both Microsoft and GNU. 2267 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2268 Tag && isa<EnumDecl>(Tag)) { 2269 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 2270 << DS.getSourceRange(); 2271 return Tag; 2272 } 2273 2274 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 2275 << DS.getSourceRange(); 2276 emittedWarning = true; 2277 } 2278 2279 // We're going to complain about a bunch of spurious specifiers; 2280 // only do this if we're declaring a tag, because otherwise we 2281 // should be getting diag::ext_no_declarators. 2282 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2283 return TagD; 2284 2285 // Note that a linkage-specification sets a storage class, but 2286 // 'extern "C" struct foo;' is actually valid and not theoretically 2287 // useless. 2288 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2289 if (!DS.isExternInLinkageSpec()) 2290 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2291 << DeclSpec::getSpecifierName(scs); 2292 2293 if (DS.isThreadSpecified()) 2294 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2295 if (DS.getTypeQualifiers()) { 2296 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2297 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2298 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2299 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2300 // Restrict is covered above. 2301 } 2302 if (DS.isInlineSpecified()) 2303 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2304 if (DS.isVirtualSpecified()) 2305 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2306 if (DS.isExplicitSpecified()) 2307 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2308 2309 // FIXME: Warn on useless attributes 2310 2311 return TagD; 2312} 2313 2314/// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec. 2315/// builds a statement for it and returns it so it is evaluated. 2316StmtResult Sema::ActOnVlaStmt(const DeclSpec &DS) { 2317 StmtResult R; 2318 if (DS.getTypeSpecType() == DeclSpec::TST_typeofExpr) { 2319 Expr *Exp = DS.getRepAsExpr(); 2320 QualType Ty = Exp->getType(); 2321 if (Ty->isPointerType()) { 2322 do 2323 Ty = Ty->getAs<PointerType>()->getPointeeType(); 2324 while (Ty->isPointerType()); 2325 } 2326 if (Ty->isVariableArrayType()) { 2327 R = ActOnExprStmt(MakeFullExpr(Exp)); 2328 } 2329 } 2330 return R; 2331} 2332 2333/// We are trying to inject an anonymous member into the given scope; 2334/// check if there's an existing declaration that can't be overloaded. 2335/// 2336/// \return true if this is a forbidden redeclaration 2337static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2338 Scope *S, 2339 DeclContext *Owner, 2340 DeclarationName Name, 2341 SourceLocation NameLoc, 2342 unsigned diagnostic) { 2343 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2344 Sema::ForRedeclaration); 2345 if (!SemaRef.LookupName(R, S)) return false; 2346 2347 if (R.getAsSingle<TagDecl>()) 2348 return false; 2349 2350 // Pick a representative declaration. 2351 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2352 assert(PrevDecl && "Expected a non-null Decl"); 2353 2354 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2355 return false; 2356 2357 SemaRef.Diag(NameLoc, diagnostic) << Name; 2358 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2359 2360 return true; 2361} 2362 2363/// InjectAnonymousStructOrUnionMembers - Inject the members of the 2364/// anonymous struct or union AnonRecord into the owning context Owner 2365/// and scope S. This routine will be invoked just after we realize 2366/// that an unnamed union or struct is actually an anonymous union or 2367/// struct, e.g., 2368/// 2369/// @code 2370/// union { 2371/// int i; 2372/// float f; 2373/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2374/// // f into the surrounding scope.x 2375/// @endcode 2376/// 2377/// This routine is recursive, injecting the names of nested anonymous 2378/// structs/unions into the owning context and scope as well. 2379static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2380 DeclContext *Owner, 2381 RecordDecl *AnonRecord, 2382 AccessSpecifier AS, 2383 llvm::SmallVector<NamedDecl*, 2> &Chaining, 2384 bool MSAnonStruct) { 2385 unsigned diagKind 2386 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2387 : diag::err_anonymous_struct_member_redecl; 2388 2389 bool Invalid = false; 2390 2391 // Look every FieldDecl and IndirectFieldDecl with a name. 2392 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2393 DEnd = AnonRecord->decls_end(); 2394 D != DEnd; ++D) { 2395 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2396 cast<NamedDecl>(*D)->getDeclName()) { 2397 ValueDecl *VD = cast<ValueDecl>(*D); 2398 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2399 VD->getLocation(), diagKind)) { 2400 // C++ [class.union]p2: 2401 // The names of the members of an anonymous union shall be 2402 // distinct from the names of any other entity in the 2403 // scope in which the anonymous union is declared. 2404 Invalid = true; 2405 } else { 2406 // C++ [class.union]p2: 2407 // For the purpose of name lookup, after the anonymous union 2408 // definition, the members of the anonymous union are 2409 // considered to have been defined in the scope in which the 2410 // anonymous union is declared. 2411 unsigned OldChainingSize = Chaining.size(); 2412 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 2413 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 2414 PE = IF->chain_end(); PI != PE; ++PI) 2415 Chaining.push_back(*PI); 2416 else 2417 Chaining.push_back(VD); 2418 2419 assert(Chaining.size() >= 2); 2420 NamedDecl **NamedChain = 2421 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 2422 for (unsigned i = 0; i < Chaining.size(); i++) 2423 NamedChain[i] = Chaining[i]; 2424 2425 IndirectFieldDecl* IndirectField = 2426 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 2427 VD->getIdentifier(), VD->getType(), 2428 NamedChain, Chaining.size()); 2429 2430 IndirectField->setAccess(AS); 2431 IndirectField->setImplicit(); 2432 SemaRef.PushOnScopeChains(IndirectField, S); 2433 2434 // That includes picking up the appropriate access specifier. 2435 if (AS != AS_none) IndirectField->setAccess(AS); 2436 2437 Chaining.resize(OldChainingSize); 2438 } 2439 } 2440 } 2441 2442 return Invalid; 2443} 2444 2445/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 2446/// a VarDecl::StorageClass. Any error reporting is up to the caller: 2447/// illegal input values are mapped to SC_None. 2448static StorageClass 2449StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2450 switch (StorageClassSpec) { 2451 case DeclSpec::SCS_unspecified: return SC_None; 2452 case DeclSpec::SCS_extern: return SC_Extern; 2453 case DeclSpec::SCS_static: return SC_Static; 2454 case DeclSpec::SCS_auto: return SC_Auto; 2455 case DeclSpec::SCS_register: return SC_Register; 2456 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2457 // Illegal SCSs map to None: error reporting is up to the caller. 2458 case DeclSpec::SCS_mutable: // Fall through. 2459 case DeclSpec::SCS_typedef: return SC_None; 2460 } 2461 llvm_unreachable("unknown storage class specifier"); 2462} 2463 2464/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 2465/// a StorageClass. Any error reporting is up to the caller: 2466/// illegal input values are mapped to SC_None. 2467static StorageClass 2468StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 2469 switch (StorageClassSpec) { 2470 case DeclSpec::SCS_unspecified: return SC_None; 2471 case DeclSpec::SCS_extern: return SC_Extern; 2472 case DeclSpec::SCS_static: return SC_Static; 2473 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 2474 // Illegal SCSs map to None: error reporting is up to the caller. 2475 case DeclSpec::SCS_auto: // Fall through. 2476 case DeclSpec::SCS_mutable: // Fall through. 2477 case DeclSpec::SCS_register: // Fall through. 2478 case DeclSpec::SCS_typedef: return SC_None; 2479 } 2480 llvm_unreachable("unknown storage class specifier"); 2481} 2482 2483/// BuildAnonymousStructOrUnion - Handle the declaration of an 2484/// anonymous structure or union. Anonymous unions are a C++ feature 2485/// (C++ [class.union]) and a GNU C extension; anonymous structures 2486/// are a GNU C and GNU C++ extension. 2487Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2488 AccessSpecifier AS, 2489 RecordDecl *Record) { 2490 DeclContext *Owner = Record->getDeclContext(); 2491 2492 // Diagnose whether this anonymous struct/union is an extension. 2493 if (Record->isUnion() && !getLangOptions().CPlusPlus) 2494 Diag(Record->getLocation(), diag::ext_anonymous_union); 2495 else if (!Record->isUnion()) 2496 Diag(Record->getLocation(), diag::ext_anonymous_struct); 2497 2498 // C and C++ require different kinds of checks for anonymous 2499 // structs/unions. 2500 bool Invalid = false; 2501 if (getLangOptions().CPlusPlus) { 2502 const char* PrevSpec = 0; 2503 unsigned DiagID; 2504 // C++ [class.union]p3: 2505 // Anonymous unions declared in a named namespace or in the 2506 // global namespace shall be declared static. 2507 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 2508 (isa<TranslationUnitDecl>(Owner) || 2509 (isa<NamespaceDecl>(Owner) && 2510 cast<NamespaceDecl>(Owner)->getDeclName()))) { 2511 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 2512 Invalid = true; 2513 2514 // Recover by adding 'static'. 2515 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 2516 PrevSpec, DiagID, getLangOptions()); 2517 } 2518 // C++ [class.union]p3: 2519 // A storage class is not allowed in a declaration of an 2520 // anonymous union in a class scope. 2521 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 2522 isa<RecordDecl>(Owner)) { 2523 Diag(DS.getStorageClassSpecLoc(), 2524 diag::err_anonymous_union_with_storage_spec); 2525 Invalid = true; 2526 2527 // Recover by removing the storage specifier. 2528 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 2529 PrevSpec, DiagID, getLangOptions()); 2530 } 2531 2532 // Ignore const/volatile/restrict qualifiers. 2533 if (DS.getTypeQualifiers()) { 2534 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2535 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2536 << Record->isUnion() << 0 2537 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 2538 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2539 Diag(DS.getVolatileSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2540 << Record->isUnion() << 1 2541 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 2542 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 2543 Diag(DS.getRestrictSpecLoc(), diag::ext_anonymous_struct_union_qualified) 2544 << Record->isUnion() << 2 2545 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 2546 2547 DS.ClearTypeQualifiers(); 2548 } 2549 2550 // C++ [class.union]p2: 2551 // The member-specification of an anonymous union shall only 2552 // define non-static data members. [Note: nested types and 2553 // functions cannot be declared within an anonymous union. ] 2554 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 2555 MemEnd = Record->decls_end(); 2556 Mem != MemEnd; ++Mem) { 2557 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 2558 // C++ [class.union]p3: 2559 // An anonymous union shall not have private or protected 2560 // members (clause 11). 2561 assert(FD->getAccess() != AS_none); 2562 if (FD->getAccess() != AS_public) { 2563 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 2564 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 2565 Invalid = true; 2566 } 2567 2568 // C++ [class.union]p1 2569 // An object of a class with a non-trivial constructor, a non-trivial 2570 // copy constructor, a non-trivial destructor, or a non-trivial copy 2571 // assignment operator cannot be a member of a union, nor can an 2572 // array of such objects. 2573 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(FD)) 2574 Invalid = true; 2575 } else if ((*Mem)->isImplicit()) { 2576 // Any implicit members are fine. 2577 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 2578 // This is a type that showed up in an 2579 // elaborated-type-specifier inside the anonymous struct or 2580 // union, but which actually declares a type outside of the 2581 // anonymous struct or union. It's okay. 2582 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 2583 if (!MemRecord->isAnonymousStructOrUnion() && 2584 MemRecord->getDeclName()) { 2585 // Visual C++ allows type definition in anonymous struct or union. 2586 if (getLangOptions().Microsoft) 2587 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 2588 << (int)Record->isUnion(); 2589 else { 2590 // This is a nested type declaration. 2591 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 2592 << (int)Record->isUnion(); 2593 Invalid = true; 2594 } 2595 } 2596 } else if (isa<AccessSpecDecl>(*Mem)) { 2597 // Any access specifier is fine. 2598 } else { 2599 // We have something that isn't a non-static data 2600 // member. Complain about it. 2601 unsigned DK = diag::err_anonymous_record_bad_member; 2602 if (isa<TypeDecl>(*Mem)) 2603 DK = diag::err_anonymous_record_with_type; 2604 else if (isa<FunctionDecl>(*Mem)) 2605 DK = diag::err_anonymous_record_with_function; 2606 else if (isa<VarDecl>(*Mem)) 2607 DK = diag::err_anonymous_record_with_static; 2608 2609 // Visual C++ allows type definition in anonymous struct or union. 2610 if (getLangOptions().Microsoft && 2611 DK == diag::err_anonymous_record_with_type) 2612 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 2613 << (int)Record->isUnion(); 2614 else { 2615 Diag((*Mem)->getLocation(), DK) 2616 << (int)Record->isUnion(); 2617 Invalid = true; 2618 } 2619 } 2620 } 2621 } 2622 2623 if (!Record->isUnion() && !Owner->isRecord()) { 2624 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 2625 << (int)getLangOptions().CPlusPlus; 2626 Invalid = true; 2627 } 2628 2629 // Mock up a declarator. 2630 Declarator Dc(DS, Declarator::MemberContext); 2631 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2632 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 2633 2634 // Create a declaration for this anonymous struct/union. 2635 NamedDecl *Anon = 0; 2636 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 2637 Anon = FieldDecl::Create(Context, OwningClass, 2638 DS.getSourceRange().getBegin(), 2639 Record->getLocation(), 2640 /*IdentifierInfo=*/0, 2641 Context.getTypeDeclType(Record), 2642 TInfo, 2643 /*BitWidth=*/0, /*Mutable=*/false, 2644 /*HasInit=*/false); 2645 Anon->setAccess(AS); 2646 if (getLangOptions().CPlusPlus) 2647 FieldCollector->Add(cast<FieldDecl>(Anon)); 2648 } else { 2649 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 2650 assert(SCSpec != DeclSpec::SCS_typedef && 2651 "Parser allowed 'typedef' as storage class VarDecl."); 2652 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 2653 if (SCSpec == DeclSpec::SCS_mutable) { 2654 // mutable can only appear on non-static class members, so it's always 2655 // an error here 2656 Diag(Record->getLocation(), diag::err_mutable_nonmember); 2657 Invalid = true; 2658 SC = SC_None; 2659 } 2660 SCSpec = DS.getStorageClassSpecAsWritten(); 2661 VarDecl::StorageClass SCAsWritten 2662 = StorageClassSpecToVarDeclStorageClass(SCSpec); 2663 2664 Anon = VarDecl::Create(Context, Owner, 2665 DS.getSourceRange().getBegin(), 2666 Record->getLocation(), /*IdentifierInfo=*/0, 2667 Context.getTypeDeclType(Record), 2668 TInfo, SC, SCAsWritten); 2669 } 2670 Anon->setImplicit(); 2671 2672 // Add the anonymous struct/union object to the current 2673 // context. We'll be referencing this object when we refer to one of 2674 // its members. 2675 Owner->addDecl(Anon); 2676 2677 // Inject the members of the anonymous struct/union into the owning 2678 // context and into the identifier resolver chain for name lookup 2679 // purposes. 2680 llvm::SmallVector<NamedDecl*, 2> Chain; 2681 Chain.push_back(Anon); 2682 2683 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 2684 Chain, false)) 2685 Invalid = true; 2686 2687 // Mark this as an anonymous struct/union type. Note that we do not 2688 // do this until after we have already checked and injected the 2689 // members of this anonymous struct/union type, because otherwise 2690 // the members could be injected twice: once by DeclContext when it 2691 // builds its lookup table, and once by 2692 // InjectAnonymousStructOrUnionMembers. 2693 Record->setAnonymousStructOrUnion(true); 2694 2695 if (Invalid) 2696 Anon->setInvalidDecl(); 2697 2698 return Anon; 2699} 2700 2701/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 2702/// Microsoft C anonymous structure. 2703/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 2704/// Example: 2705/// 2706/// struct A { int a; }; 2707/// struct B { struct A; int b; }; 2708/// 2709/// void foo() { 2710/// B var; 2711/// var.a = 3; 2712/// } 2713/// 2714Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2715 RecordDecl *Record) { 2716 2717 // If there is no Record, get the record via the typedef. 2718 if (!Record) 2719 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 2720 2721 // Mock up a declarator. 2722 Declarator Dc(DS, Declarator::TypeNameContext); 2723 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 2724 assert(TInfo && "couldn't build declarator info for anonymous struct"); 2725 2726 // Create a declaration for this anonymous struct. 2727 NamedDecl* Anon = FieldDecl::Create(Context, 2728 cast<RecordDecl>(CurContext), 2729 DS.getSourceRange().getBegin(), 2730 DS.getSourceRange().getBegin(), 2731 /*IdentifierInfo=*/0, 2732 Context.getTypeDeclType(Record), 2733 TInfo, 2734 /*BitWidth=*/0, /*Mutable=*/false, 2735 /*HasInit=*/false); 2736 Anon->setImplicit(); 2737 2738 // Add the anonymous struct object to the current context. 2739 CurContext->addDecl(Anon); 2740 2741 // Inject the members of the anonymous struct into the current 2742 // context and into the identifier resolver chain for name lookup 2743 // purposes. 2744 llvm::SmallVector<NamedDecl*, 2> Chain; 2745 Chain.push_back(Anon); 2746 2747 if (InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 2748 Record->getDefinition(), 2749 AS_none, Chain, true)) 2750 Anon->setInvalidDecl(); 2751 2752 return Anon; 2753} 2754 2755/// GetNameForDeclarator - Determine the full declaration name for the 2756/// given Declarator. 2757DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 2758 return GetNameFromUnqualifiedId(D.getName()); 2759} 2760 2761/// \brief Retrieves the declaration name from a parsed unqualified-id. 2762DeclarationNameInfo 2763Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 2764 DeclarationNameInfo NameInfo; 2765 NameInfo.setLoc(Name.StartLocation); 2766 2767 switch (Name.getKind()) { 2768 2769 case UnqualifiedId::IK_Identifier: 2770 NameInfo.setName(Name.Identifier); 2771 NameInfo.setLoc(Name.StartLocation); 2772 return NameInfo; 2773 2774 case UnqualifiedId::IK_OperatorFunctionId: 2775 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 2776 Name.OperatorFunctionId.Operator)); 2777 NameInfo.setLoc(Name.StartLocation); 2778 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 2779 = Name.OperatorFunctionId.SymbolLocations[0]; 2780 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 2781 = Name.EndLocation.getRawEncoding(); 2782 return NameInfo; 2783 2784 case UnqualifiedId::IK_LiteralOperatorId: 2785 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 2786 Name.Identifier)); 2787 NameInfo.setLoc(Name.StartLocation); 2788 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 2789 return NameInfo; 2790 2791 case UnqualifiedId::IK_ConversionFunctionId: { 2792 TypeSourceInfo *TInfo; 2793 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 2794 if (Ty.isNull()) 2795 return DeclarationNameInfo(); 2796 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 2797 Context.getCanonicalType(Ty))); 2798 NameInfo.setLoc(Name.StartLocation); 2799 NameInfo.setNamedTypeInfo(TInfo); 2800 return NameInfo; 2801 } 2802 2803 case UnqualifiedId::IK_ConstructorName: { 2804 TypeSourceInfo *TInfo; 2805 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 2806 if (Ty.isNull()) 2807 return DeclarationNameInfo(); 2808 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2809 Context.getCanonicalType(Ty))); 2810 NameInfo.setLoc(Name.StartLocation); 2811 NameInfo.setNamedTypeInfo(TInfo); 2812 return NameInfo; 2813 } 2814 2815 case UnqualifiedId::IK_ConstructorTemplateId: { 2816 // In well-formed code, we can only have a constructor 2817 // template-id that refers to the current context, so go there 2818 // to find the actual type being constructed. 2819 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 2820 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 2821 return DeclarationNameInfo(); 2822 2823 // Determine the type of the class being constructed. 2824 QualType CurClassType = Context.getTypeDeclType(CurClass); 2825 2826 // FIXME: Check two things: that the template-id names the same type as 2827 // CurClassType, and that the template-id does not occur when the name 2828 // was qualified. 2829 2830 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 2831 Context.getCanonicalType(CurClassType))); 2832 NameInfo.setLoc(Name.StartLocation); 2833 // FIXME: should we retrieve TypeSourceInfo? 2834 NameInfo.setNamedTypeInfo(0); 2835 return NameInfo; 2836 } 2837 2838 case UnqualifiedId::IK_DestructorName: { 2839 TypeSourceInfo *TInfo; 2840 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 2841 if (Ty.isNull()) 2842 return DeclarationNameInfo(); 2843 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 2844 Context.getCanonicalType(Ty))); 2845 NameInfo.setLoc(Name.StartLocation); 2846 NameInfo.setNamedTypeInfo(TInfo); 2847 return NameInfo; 2848 } 2849 2850 case UnqualifiedId::IK_TemplateId: { 2851 TemplateName TName = Name.TemplateId->Template.get(); 2852 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 2853 return Context.getNameForTemplate(TName, TNameLoc); 2854 } 2855 2856 } // switch (Name.getKind()) 2857 2858 assert(false && "Unknown name kind"); 2859 return DeclarationNameInfo(); 2860} 2861 2862/// isNearlyMatchingFunction - Determine whether the C++ functions 2863/// Declaration and Definition are "nearly" matching. This heuristic 2864/// is used to improve diagnostics in the case where an out-of-line 2865/// function definition doesn't match any declaration within 2866/// the class or namespace. 2867static bool isNearlyMatchingFunction(ASTContext &Context, 2868 FunctionDecl *Declaration, 2869 FunctionDecl *Definition) { 2870 if (Declaration->param_size() != Definition->param_size()) 2871 return false; 2872 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 2873 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 2874 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 2875 2876 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(), 2877 DefParamTy.getNonReferenceType())) 2878 return false; 2879 } 2880 2881 return true; 2882} 2883 2884/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 2885/// declarator needs to be rebuilt in the current instantiation. 2886/// Any bits of declarator which appear before the name are valid for 2887/// consideration here. That's specifically the type in the decl spec 2888/// and the base type in any member-pointer chunks. 2889static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 2890 DeclarationName Name) { 2891 // The types we specifically need to rebuild are: 2892 // - typenames, typeofs, and decltypes 2893 // - types which will become injected class names 2894 // Of course, we also need to rebuild any type referencing such a 2895 // type. It's safest to just say "dependent", but we call out a 2896 // few cases here. 2897 2898 DeclSpec &DS = D.getMutableDeclSpec(); 2899 switch (DS.getTypeSpecType()) { 2900 case DeclSpec::TST_typename: 2901 case DeclSpec::TST_typeofType: 2902 case DeclSpec::TST_decltype: 2903 case DeclSpec::TST_underlyingType: { 2904 // Grab the type from the parser. 2905 TypeSourceInfo *TSI = 0; 2906 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 2907 if (T.isNull() || !T->isDependentType()) break; 2908 2909 // Make sure there's a type source info. This isn't really much 2910 // of a waste; most dependent types should have type source info 2911 // attached already. 2912 if (!TSI) 2913 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 2914 2915 // Rebuild the type in the current instantiation. 2916 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 2917 if (!TSI) return true; 2918 2919 // Store the new type back in the decl spec. 2920 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 2921 DS.UpdateTypeRep(LocType); 2922 break; 2923 } 2924 2925 case DeclSpec::TST_typeofExpr: { 2926 Expr *E = DS.getRepAsExpr(); 2927 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 2928 if (Result.isInvalid()) return true; 2929 DS.UpdateExprRep(Result.get()); 2930 break; 2931 } 2932 2933 default: 2934 // Nothing to do for these decl specs. 2935 break; 2936 } 2937 2938 // It doesn't matter what order we do this in. 2939 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 2940 DeclaratorChunk &Chunk = D.getTypeObject(I); 2941 2942 // The only type information in the declarator which can come 2943 // before the declaration name is the base type of a member 2944 // pointer. 2945 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 2946 continue; 2947 2948 // Rebuild the scope specifier in-place. 2949 CXXScopeSpec &SS = Chunk.Mem.Scope(); 2950 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 2951 return true; 2952 } 2953 2954 return false; 2955} 2956 2957Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 2958 return HandleDeclarator(S, D, MultiTemplateParamsArg(*this), 2959 /*IsFunctionDefinition=*/false); 2960} 2961 2962/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 2963/// If T is the name of a class, then each of the following shall have a 2964/// name different from T: 2965/// - every static data member of class T; 2966/// - every member function of class T 2967/// - every member of class T that is itself a type; 2968/// \returns true if the declaration name violates these rules. 2969bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 2970 DeclarationNameInfo NameInfo) { 2971 DeclarationName Name = NameInfo.getName(); 2972 2973 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 2974 if (Record->getIdentifier() && Record->getDeclName() == Name) { 2975 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 2976 return true; 2977 } 2978 2979 return false; 2980} 2981 2982Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 2983 MultiTemplateParamsArg TemplateParamLists, 2984 bool IsFunctionDefinition) { 2985 // TODO: consider using NameInfo for diagnostic. 2986 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2987 DeclarationName Name = NameInfo.getName(); 2988 2989 // All of these full declarators require an identifier. If it doesn't have 2990 // one, the ParsedFreeStandingDeclSpec action should be used. 2991 if (!Name) { 2992 if (!D.isInvalidType()) // Reject this if we think it is valid. 2993 Diag(D.getDeclSpec().getSourceRange().getBegin(), 2994 diag::err_declarator_need_ident) 2995 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 2996 return 0; 2997 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 2998 return 0; 2999 3000 // The scope passed in may not be a decl scope. Zip up the scope tree until 3001 // we find one that is. 3002 while ((S->getFlags() & Scope::DeclScope) == 0 || 3003 (S->getFlags() & Scope::TemplateParamScope) != 0) 3004 S = S->getParent(); 3005 3006 DeclContext *DC = CurContext; 3007 if (D.getCXXScopeSpec().isInvalid()) 3008 D.setInvalidType(); 3009 else if (D.getCXXScopeSpec().isSet()) { 3010 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3011 UPPC_DeclarationQualifier)) 3012 return 0; 3013 3014 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3015 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3016 if (!DC) { 3017 // If we could not compute the declaration context, it's because the 3018 // declaration context is dependent but does not refer to a class, 3019 // class template, or class template partial specialization. Complain 3020 // and return early, to avoid the coming semantic disaster. 3021 Diag(D.getIdentifierLoc(), 3022 diag::err_template_qualified_declarator_no_match) 3023 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3024 << D.getCXXScopeSpec().getRange(); 3025 return 0; 3026 } 3027 bool IsDependentContext = DC->isDependentContext(); 3028 3029 if (!IsDependentContext && 3030 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3031 return 0; 3032 3033 if (isa<CXXRecordDecl>(DC)) { 3034 if (!cast<CXXRecordDecl>(DC)->hasDefinition()) { 3035 Diag(D.getIdentifierLoc(), 3036 diag::err_member_def_undefined_record) 3037 << Name << DC << D.getCXXScopeSpec().getRange(); 3038 D.setInvalidType(); 3039 } else if (isa<CXXRecordDecl>(CurContext) && 3040 !D.getDeclSpec().isFriendSpecified()) { 3041 // The user provided a superfluous scope specifier inside a class 3042 // definition: 3043 // 3044 // class X { 3045 // void X::f(); 3046 // }; 3047 if (CurContext->Equals(DC)) 3048 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 3049 << Name << FixItHint::CreateRemoval(D.getCXXScopeSpec().getRange()); 3050 else 3051 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3052 << Name << D.getCXXScopeSpec().getRange(); 3053 3054 // Pretend that this qualifier was not here. 3055 D.getCXXScopeSpec().clear(); 3056 } 3057 } 3058 3059 // Check whether we need to rebuild the type of the given 3060 // declaration in the current instantiation. 3061 if (EnteringContext && IsDependentContext && 3062 TemplateParamLists.size() != 0) { 3063 ContextRAII SavedContext(*this, DC); 3064 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3065 D.setInvalidType(); 3066 } 3067 } 3068 3069 if (DiagnoseClassNameShadow(DC, NameInfo)) 3070 // If this is a typedef, we'll end up spewing multiple diagnostics. 3071 // Just return early; it's safer. 3072 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3073 return 0; 3074 3075 NamedDecl *New; 3076 3077 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3078 QualType R = TInfo->getType(); 3079 3080 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3081 UPPC_DeclarationType)) 3082 D.setInvalidType(); 3083 3084 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3085 ForRedeclaration); 3086 3087 // See if this is a redefinition of a variable in the same scope. 3088 if (!D.getCXXScopeSpec().isSet()) { 3089 bool IsLinkageLookup = false; 3090 3091 // If the declaration we're planning to build will be a function 3092 // or object with linkage, then look for another declaration with 3093 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3094 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3095 /* Do nothing*/; 3096 else if (R->isFunctionType()) { 3097 if (CurContext->isFunctionOrMethod() || 3098 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3099 IsLinkageLookup = true; 3100 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3101 IsLinkageLookup = true; 3102 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3103 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3104 IsLinkageLookup = true; 3105 3106 if (IsLinkageLookup) 3107 Previous.clear(LookupRedeclarationWithLinkage); 3108 3109 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3110 } else { // Something like "int foo::x;" 3111 LookupQualifiedName(Previous, DC); 3112 3113 // Don't consider using declarations as previous declarations for 3114 // out-of-line members. 3115 RemoveUsingDecls(Previous); 3116 3117 // C++ 7.3.1.2p2: 3118 // Members (including explicit specializations of templates) of a named 3119 // namespace can also be defined outside that namespace by explicit 3120 // qualification of the name being defined, provided that the entity being 3121 // defined was already declared in the namespace and the definition appears 3122 // after the point of declaration in a namespace that encloses the 3123 // declarations namespace. 3124 // 3125 // Note that we only check the context at this point. We don't yet 3126 // have enough information to make sure that PrevDecl is actually 3127 // the declaration we want to match. For example, given: 3128 // 3129 // class X { 3130 // void f(); 3131 // void f(float); 3132 // }; 3133 // 3134 // void X::f(int) { } // ill-formed 3135 // 3136 // In this case, PrevDecl will point to the overload set 3137 // containing the two f's declared in X, but neither of them 3138 // matches. 3139 3140 // First check whether we named the global scope. 3141 if (isa<TranslationUnitDecl>(DC)) { 3142 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 3143 << Name << D.getCXXScopeSpec().getRange(); 3144 } else { 3145 DeclContext *Cur = CurContext; 3146 while (isa<LinkageSpecDecl>(Cur)) 3147 Cur = Cur->getParent(); 3148 if (!Cur->Encloses(DC)) { 3149 // The qualifying scope doesn't enclose the original declaration. 3150 // Emit diagnostic based on current scope. 3151 SourceLocation L = D.getIdentifierLoc(); 3152 SourceRange R = D.getCXXScopeSpec().getRange(); 3153 if (isa<FunctionDecl>(Cur)) 3154 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 3155 else 3156 Diag(L, diag::err_invalid_declarator_scope) 3157 << Name << cast<NamedDecl>(DC) << R; 3158 D.setInvalidType(); 3159 } 3160 } 3161 } 3162 3163 if (Previous.isSingleResult() && 3164 Previous.getFoundDecl()->isTemplateParameter()) { 3165 // Maybe we will complain about the shadowed template parameter. 3166 if (!D.isInvalidType()) 3167 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3168 Previous.getFoundDecl())) 3169 D.setInvalidType(); 3170 3171 // Just pretend that we didn't see the previous declaration. 3172 Previous.clear(); 3173 } 3174 3175 // In C++, the previous declaration we find might be a tag type 3176 // (class or enum). In this case, the new declaration will hide the 3177 // tag type. Note that this does does not apply if we're declaring a 3178 // typedef (C++ [dcl.typedef]p4). 3179 if (Previous.isSingleTagDecl() && 3180 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3181 Previous.clear(); 3182 3183 bool Redeclaration = false; 3184 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3185 if (TemplateParamLists.size()) { 3186 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3187 return 0; 3188 } 3189 3190 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration); 3191 } else if (R->isFunctionType()) { 3192 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous, 3193 move(TemplateParamLists), 3194 IsFunctionDefinition, Redeclaration); 3195 } else { 3196 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous, 3197 move(TemplateParamLists), 3198 Redeclaration); 3199 } 3200 3201 if (New == 0) 3202 return 0; 3203 3204 // If this has an identifier and is not an invalid redeclaration or 3205 // function template specialization, add it to the scope stack. 3206 if (New->getDeclName() && !(Redeclaration && New->isInvalidDecl())) 3207 PushOnScopeChains(New, S); 3208 3209 return New; 3210} 3211 3212/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3213/// types into constant array types in certain situations which would otherwise 3214/// be errors (for GCC compatibility). 3215static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3216 ASTContext &Context, 3217 bool &SizeIsNegative, 3218 llvm::APSInt &Oversized) { 3219 // This method tries to turn a variable array into a constant 3220 // array even when the size isn't an ICE. This is necessary 3221 // for compatibility with code that depends on gcc's buggy 3222 // constant expression folding, like struct {char x[(int)(char*)2];} 3223 SizeIsNegative = false; 3224 Oversized = 0; 3225 3226 if (T->isDependentType()) 3227 return QualType(); 3228 3229 QualifierCollector Qs; 3230 const Type *Ty = Qs.strip(T); 3231 3232 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3233 QualType Pointee = PTy->getPointeeType(); 3234 QualType FixedType = 3235 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3236 Oversized); 3237 if (FixedType.isNull()) return FixedType; 3238 FixedType = Context.getPointerType(FixedType); 3239 return Qs.apply(Context, FixedType); 3240 } 3241 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3242 QualType Inner = PTy->getInnerType(); 3243 QualType FixedType = 3244 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3245 Oversized); 3246 if (FixedType.isNull()) return FixedType; 3247 FixedType = Context.getParenType(FixedType); 3248 return Qs.apply(Context, FixedType); 3249 } 3250 3251 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3252 if (!VLATy) 3253 return QualType(); 3254 // FIXME: We should probably handle this case 3255 if (VLATy->getElementType()->isVariablyModifiedType()) 3256 return QualType(); 3257 3258 Expr::EvalResult EvalResult; 3259 if (!VLATy->getSizeExpr() || 3260 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 3261 !EvalResult.Val.isInt()) 3262 return QualType(); 3263 3264 // Check whether the array size is negative. 3265 llvm::APSInt &Res = EvalResult.Val.getInt(); 3266 if (Res.isSigned() && Res.isNegative()) { 3267 SizeIsNegative = true; 3268 return QualType(); 3269 } 3270 3271 // Check whether the array is too large to be addressed. 3272 unsigned ActiveSizeBits 3273 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3274 Res); 3275 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3276 Oversized = Res; 3277 return QualType(); 3278 } 3279 3280 return Context.getConstantArrayType(VLATy->getElementType(), 3281 Res, ArrayType::Normal, 0); 3282} 3283 3284/// \brief Register the given locally-scoped external C declaration so 3285/// that it can be found later for redeclarations 3286void 3287Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 3288 const LookupResult &Previous, 3289 Scope *S) { 3290 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 3291 "Decl is not a locally-scoped decl!"); 3292 // Note that we have a locally-scoped external with this name. 3293 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 3294 3295 if (!Previous.isSingleResult()) 3296 return; 3297 3298 NamedDecl *PrevDecl = Previous.getFoundDecl(); 3299 3300 // If there was a previous declaration of this variable, it may be 3301 // in our identifier chain. Update the identifier chain with the new 3302 // declaration. 3303 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 3304 // The previous declaration was found on the identifer resolver 3305 // chain, so remove it from its scope. 3306 3307 if (S->isDeclScope(PrevDecl)) { 3308 // Special case for redeclarations in the SAME scope. 3309 // Because this declaration is going to be added to the identifier chain 3310 // later, we should temporarily take it OFF the chain. 3311 IdResolver.RemoveDecl(ND); 3312 3313 } else { 3314 // Find the scope for the original declaration. 3315 while (S && !S->isDeclScope(PrevDecl)) 3316 S = S->getParent(); 3317 } 3318 3319 if (S) 3320 S->RemoveDecl(PrevDecl); 3321 } 3322} 3323 3324/// \brief Diagnose function specifiers on a declaration of an identifier that 3325/// does not identify a function. 3326void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 3327 // FIXME: We should probably indicate the identifier in question to avoid 3328 // confusion for constructs like "inline int a(), b;" 3329 if (D.getDeclSpec().isInlineSpecified()) 3330 Diag(D.getDeclSpec().getInlineSpecLoc(), 3331 diag::err_inline_non_function); 3332 3333 if (D.getDeclSpec().isVirtualSpecified()) 3334 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3335 diag::err_virtual_non_function); 3336 3337 if (D.getDeclSpec().isExplicitSpecified()) 3338 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3339 diag::err_explicit_non_function); 3340} 3341 3342NamedDecl* 3343Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 3344 QualType R, TypeSourceInfo *TInfo, 3345 LookupResult &Previous, bool &Redeclaration) { 3346 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 3347 if (D.getCXXScopeSpec().isSet()) { 3348 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 3349 << D.getCXXScopeSpec().getRange(); 3350 D.setInvalidType(); 3351 // Pretend we didn't see the scope specifier. 3352 DC = CurContext; 3353 Previous.clear(); 3354 } 3355 3356 if (getLangOptions().CPlusPlus) { 3357 // Check that there are no default arguments (C++ only). 3358 CheckExtraCXXDefaultArguments(D); 3359 } 3360 3361 DiagnoseFunctionSpecifiers(D); 3362 3363 if (D.getDeclSpec().isThreadSpecified()) 3364 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 3365 3366 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 3367 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 3368 << D.getName().getSourceRange(); 3369 return 0; 3370 } 3371 3372 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo); 3373 if (!NewTD) return 0; 3374 3375 // Handle attributes prior to checking for duplicates in MergeVarDecl 3376 ProcessDeclAttributes(S, NewTD, D); 3377 3378 CheckTypedefForVariablyModifiedType(S, NewTD); 3379 3380 return ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 3381} 3382 3383void 3384Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 3385 // C99 6.7.7p2: If a typedef name specifies a variably modified type 3386 // then it shall have block scope. 3387 // Note that variably modified types must be fixed before merging the decl so 3388 // that redeclarations will match. 3389 QualType T = NewTD->getUnderlyingType(); 3390 if (T->isVariablyModifiedType()) { 3391 getCurFunction()->setHasBranchProtectedScope(); 3392 3393 if (S->getFnParent() == 0) { 3394 bool SizeIsNegative; 3395 llvm::APSInt Oversized; 3396 QualType FixedTy = 3397 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3398 Oversized); 3399 if (!FixedTy.isNull()) { 3400 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 3401 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 3402 } else { 3403 if (SizeIsNegative) 3404 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 3405 else if (T->isVariableArrayType()) 3406 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 3407 else if (Oversized.getBoolValue()) 3408 Diag(NewTD->getLocation(), diag::err_array_too_large) << Oversized.toString(10); 3409 else 3410 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 3411 NewTD->setInvalidDecl(); 3412 } 3413 } 3414 } 3415} 3416 3417 3418/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 3419/// declares a typedef-name, either using the 'typedef' type specifier or via 3420/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 3421NamedDecl* 3422Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 3423 LookupResult &Previous, bool &Redeclaration) { 3424 // Merge the decl with the existing one if appropriate. If the decl is 3425 // in an outer scope, it isn't the same thing. 3426 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 3427 /*ExplicitInstantiationOrSpecialization=*/false); 3428 if (!Previous.empty()) { 3429 Redeclaration = true; 3430 MergeTypedefNameDecl(NewTD, Previous); 3431 } 3432 3433 // If this is the C FILE type, notify the AST context. 3434 if (IdentifierInfo *II = NewTD->getIdentifier()) 3435 if (!NewTD->isInvalidDecl() && 3436 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 3437 if (II->isStr("FILE")) 3438 Context.setFILEDecl(NewTD); 3439 else if (II->isStr("jmp_buf")) 3440 Context.setjmp_bufDecl(NewTD); 3441 else if (II->isStr("sigjmp_buf")) 3442 Context.setsigjmp_bufDecl(NewTD); 3443 else if (II->isStr("__builtin_va_list")) 3444 Context.setBuiltinVaListType(Context.getTypedefType(NewTD)); 3445 } 3446 3447 return NewTD; 3448} 3449 3450/// \brief Determines whether the given declaration is an out-of-scope 3451/// previous declaration. 3452/// 3453/// This routine should be invoked when name lookup has found a 3454/// previous declaration (PrevDecl) that is not in the scope where a 3455/// new declaration by the same name is being introduced. If the new 3456/// declaration occurs in a local scope, previous declarations with 3457/// linkage may still be considered previous declarations (C99 3458/// 6.2.2p4-5, C++ [basic.link]p6). 3459/// 3460/// \param PrevDecl the previous declaration found by name 3461/// lookup 3462/// 3463/// \param DC the context in which the new declaration is being 3464/// declared. 3465/// 3466/// \returns true if PrevDecl is an out-of-scope previous declaration 3467/// for a new delcaration with the same name. 3468static bool 3469isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 3470 ASTContext &Context) { 3471 if (!PrevDecl) 3472 return false; 3473 3474 if (!PrevDecl->hasLinkage()) 3475 return false; 3476 3477 if (Context.getLangOptions().CPlusPlus) { 3478 // C++ [basic.link]p6: 3479 // If there is a visible declaration of an entity with linkage 3480 // having the same name and type, ignoring entities declared 3481 // outside the innermost enclosing namespace scope, the block 3482 // scope declaration declares that same entity and receives the 3483 // linkage of the previous declaration. 3484 DeclContext *OuterContext = DC->getRedeclContext(); 3485 if (!OuterContext->isFunctionOrMethod()) 3486 // This rule only applies to block-scope declarations. 3487 return false; 3488 3489 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 3490 if (PrevOuterContext->isRecord()) 3491 // We found a member function: ignore it. 3492 return false; 3493 3494 // Find the innermost enclosing namespace for the new and 3495 // previous declarations. 3496 OuterContext = OuterContext->getEnclosingNamespaceContext(); 3497 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 3498 3499 // The previous declaration is in a different namespace, so it 3500 // isn't the same function. 3501 if (!OuterContext->Equals(PrevOuterContext)) 3502 return false; 3503 } 3504 3505 return true; 3506} 3507 3508static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 3509 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3510 if (!SS.isSet()) return; 3511 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 3512} 3513 3514bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 3515 QualType type = decl->getType(); 3516 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 3517 if (lifetime == Qualifiers::OCL_Autoreleasing) { 3518 // Various kinds of declaration aren't allowed to be __autoreleasing. 3519 unsigned kind = -1U; 3520 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3521 if (var->hasAttr<BlocksAttr>()) 3522 kind = 0; // __block 3523 else if (!var->hasLocalStorage()) 3524 kind = 1; // global 3525 } else if (isa<ObjCIvarDecl>(decl)) { 3526 kind = 3; // ivar 3527 } else if (isa<FieldDecl>(decl)) { 3528 kind = 2; // field 3529 } 3530 3531 if (kind != -1U) { 3532 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 3533 << kind; 3534 } 3535 } else if (lifetime == Qualifiers::OCL_None) { 3536 // Try to infer lifetime. 3537 if (!type->isObjCLifetimeType()) 3538 return false; 3539 3540 lifetime = type->getObjCARCImplicitLifetime(); 3541 type = Context.getLifetimeQualifiedType(type, lifetime); 3542 decl->setType(type); 3543 } 3544 3545 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 3546 // Thread-local variables cannot have lifetime. 3547 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 3548 var->isThreadSpecified()) { 3549 Diag(var->getLocation(), diag::err_arc_thread_ownership) 3550 << var->getType(); 3551 return true; 3552 } 3553 } 3554 3555 return false; 3556} 3557 3558NamedDecl* 3559Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 3560 QualType R, TypeSourceInfo *TInfo, 3561 LookupResult &Previous, 3562 MultiTemplateParamsArg TemplateParamLists, 3563 bool &Redeclaration) { 3564 DeclarationName Name = GetNameForDeclarator(D).getName(); 3565 3566 // Check that there are no default arguments (C++ only). 3567 if (getLangOptions().CPlusPlus) 3568 CheckExtraCXXDefaultArguments(D); 3569 3570 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 3571 assert(SCSpec != DeclSpec::SCS_typedef && 3572 "Parser allowed 'typedef' as storage class VarDecl."); 3573 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3574 if (SCSpec == DeclSpec::SCS_mutable) { 3575 // mutable can only appear on non-static class members, so it's always 3576 // an error here 3577 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 3578 D.setInvalidType(); 3579 SC = SC_None; 3580 } 3581 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 3582 VarDecl::StorageClass SCAsWritten 3583 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3584 3585 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3586 if (!II) { 3587 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 3588 << Name.getAsString(); 3589 return 0; 3590 } 3591 3592 DiagnoseFunctionSpecifiers(D); 3593 3594 if (!DC->isRecord() && S->getFnParent() == 0) { 3595 // C99 6.9p2: The storage-class specifiers auto and register shall not 3596 // appear in the declaration specifiers in an external declaration. 3597 if (SC == SC_Auto || SC == SC_Register) { 3598 3599 // If this is a register variable with an asm label specified, then this 3600 // is a GNU extension. 3601 if (SC == SC_Register && D.getAsmLabel()) 3602 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 3603 else 3604 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 3605 D.setInvalidType(); 3606 } 3607 } 3608 3609 bool isExplicitSpecialization = false; 3610 VarDecl *NewVD; 3611 if (!getLangOptions().CPlusPlus) { 3612 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3613 D.getIdentifierLoc(), II, 3614 R, TInfo, SC, SCAsWritten); 3615 3616 if (D.isInvalidType()) 3617 NewVD->setInvalidDecl(); 3618 } else { 3619 if (DC->isRecord() && !CurContext->isRecord()) { 3620 // This is an out-of-line definition of a static data member. 3621 if (SC == SC_Static) { 3622 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3623 diag::err_static_out_of_line) 3624 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3625 } else if (SC == SC_None) 3626 SC = SC_Static; 3627 } 3628 if (SC == SC_Static) { 3629 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 3630 if (RD->isLocalClass()) 3631 Diag(D.getIdentifierLoc(), 3632 diag::err_static_data_member_not_allowed_in_local_class) 3633 << Name << RD->getDeclName(); 3634 3635 // C++ [class.union]p1: If a union contains a static data member, 3636 // the program is ill-formed. 3637 // 3638 // We also disallow static data members in anonymous structs. 3639 if (CurContext->isRecord() && (RD->isUnion() || !RD->getDeclName())) 3640 Diag(D.getIdentifierLoc(), 3641 diag::err_static_data_member_not_allowed_in_union_or_anon_struct) 3642 << Name << RD->isUnion(); 3643 } 3644 } 3645 3646 // Match up the template parameter lists with the scope specifier, then 3647 // determine whether we have a template or a template specialization. 3648 isExplicitSpecialization = false; 3649 bool Invalid = false; 3650 if (TemplateParameterList *TemplateParams 3651 = MatchTemplateParametersToScopeSpecifier( 3652 D.getDeclSpec().getSourceRange().getBegin(), 3653 D.getIdentifierLoc(), 3654 D.getCXXScopeSpec(), 3655 TemplateParamLists.get(), 3656 TemplateParamLists.size(), 3657 /*never a friend*/ false, 3658 isExplicitSpecialization, 3659 Invalid)) { 3660 if (TemplateParams->size() > 0) { 3661 // There is no such thing as a variable template. 3662 Diag(D.getIdentifierLoc(), diag::err_template_variable) 3663 << II 3664 << SourceRange(TemplateParams->getTemplateLoc(), 3665 TemplateParams->getRAngleLoc()); 3666 return 0; 3667 } else { 3668 // There is an extraneous 'template<>' for this variable. Complain 3669 // about it, but allow the declaration of the variable. 3670 Diag(TemplateParams->getTemplateLoc(), 3671 diag::err_template_variable_noparams) 3672 << II 3673 << SourceRange(TemplateParams->getTemplateLoc(), 3674 TemplateParams->getRAngleLoc()); 3675 } 3676 } 3677 3678 NewVD = VarDecl::Create(Context, DC, D.getSourceRange().getBegin(), 3679 D.getIdentifierLoc(), II, 3680 R, TInfo, SC, SCAsWritten); 3681 3682 // If this decl has an auto type in need of deduction, make a note of the 3683 // Decl so we can diagnose uses of it in its own initializer. 3684 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 3685 R->getContainedAutoType()) 3686 ParsingInitForAutoVars.insert(NewVD); 3687 3688 if (D.isInvalidType() || Invalid) 3689 NewVD->setInvalidDecl(); 3690 3691 SetNestedNameSpecifier(NewVD, D); 3692 3693 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 3694 NewVD->setTemplateParameterListsInfo(Context, 3695 TemplateParamLists.size(), 3696 TemplateParamLists.release()); 3697 } 3698 } 3699 3700 if (D.getDeclSpec().isThreadSpecified()) { 3701 if (NewVD->hasLocalStorage()) 3702 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 3703 else if (!Context.Target.isTLSSupported()) 3704 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 3705 else 3706 NewVD->setThreadSpecified(true); 3707 } 3708 3709 // Set the lexical context. If the declarator has a C++ scope specifier, the 3710 // lexical context will be different from the semantic context. 3711 NewVD->setLexicalDeclContext(CurContext); 3712 3713 // Handle attributes prior to checking for duplicates in MergeVarDecl 3714 ProcessDeclAttributes(S, NewVD, D); 3715 3716 // In auto-retain/release, infer strong retension for variables of 3717 // retainable type. 3718 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 3719 NewVD->setInvalidDecl(); 3720 3721 // Handle GNU asm-label extension (encoded as an attribute). 3722 if (Expr *E = (Expr*)D.getAsmLabel()) { 3723 // The parser guarantees this is a string. 3724 StringLiteral *SE = cast<StringLiteral>(E); 3725 llvm::StringRef Label = SE->getString(); 3726 if (S->getFnParent() != 0) { 3727 switch (SC) { 3728 case SC_None: 3729 case SC_Auto: 3730 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 3731 break; 3732 case SC_Register: 3733 if (!Context.Target.isValidGCCRegisterName(Label)) 3734 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 3735 break; 3736 case SC_Static: 3737 case SC_Extern: 3738 case SC_PrivateExtern: 3739 break; 3740 } 3741 } 3742 3743 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 3744 Context, Label)); 3745 } 3746 3747 // Diagnose shadowed variables before filtering for scope. 3748 if (!D.getCXXScopeSpec().isSet()) 3749 CheckShadow(S, NewVD, Previous); 3750 3751 // Don't consider existing declarations that are in a different 3752 // scope and are out-of-semantic-context declarations (if the new 3753 // declaration has linkage). 3754 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 3755 isExplicitSpecialization); 3756 3757 if (!getLangOptions().CPlusPlus) 3758 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 3759 else { 3760 // Merge the decl with the existing one if appropriate. 3761 if (!Previous.empty()) { 3762 if (Previous.isSingleResult() && 3763 isa<FieldDecl>(Previous.getFoundDecl()) && 3764 D.getCXXScopeSpec().isSet()) { 3765 // The user tried to define a non-static data member 3766 // out-of-line (C++ [dcl.meaning]p1). 3767 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 3768 << D.getCXXScopeSpec().getRange(); 3769 Previous.clear(); 3770 NewVD->setInvalidDecl(); 3771 } 3772 } else if (D.getCXXScopeSpec().isSet()) { 3773 // No previous declaration in the qualifying scope. 3774 Diag(D.getIdentifierLoc(), diag::err_no_member) 3775 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 3776 << D.getCXXScopeSpec().getRange(); 3777 NewVD->setInvalidDecl(); 3778 } 3779 3780 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 3781 3782 // This is an explicit specialization of a static data member. Check it. 3783 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 3784 CheckMemberSpecialization(NewVD, Previous)) 3785 NewVD->setInvalidDecl(); 3786 } 3787 3788 // attributes declared post-definition are currently ignored 3789 // FIXME: This should be handled in attribute merging, not 3790 // here. 3791 if (Previous.isSingleResult()) { 3792 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3793 if (Def && (Def = Def->getDefinition()) && 3794 Def != NewVD && D.hasAttributes()) { 3795 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 3796 Diag(Def->getLocation(), diag::note_previous_definition); 3797 } 3798 } 3799 3800 // If this is a locally-scoped extern C variable, update the map of 3801 // such variables. 3802 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 3803 !NewVD->isInvalidDecl()) 3804 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 3805 3806 // If there's a #pragma GCC visibility in scope, and this isn't a class 3807 // member, set the visibility of this variable. 3808 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 3809 AddPushedVisibilityAttribute(NewVD); 3810 3811 MarkUnusedFileScopedDecl(NewVD); 3812 3813 return NewVD; 3814} 3815 3816/// \brief Diagnose variable or built-in function shadowing. Implements 3817/// -Wshadow. 3818/// 3819/// This method is called whenever a VarDecl is added to a "useful" 3820/// scope. 3821/// 3822/// \param S the scope in which the shadowing name is being declared 3823/// \param R the lookup of the name 3824/// 3825void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 3826 // Return if warning is ignored. 3827 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 3828 Diagnostic::Ignored) 3829 return; 3830 3831 // Don't diagnose declarations at file scope. 3832 if (D->hasGlobalStorage()) 3833 return; 3834 3835 DeclContext *NewDC = D->getDeclContext(); 3836 3837 // Only diagnose if we're shadowing an unambiguous field or variable. 3838 if (R.getResultKind() != LookupResult::Found) 3839 return; 3840 3841 NamedDecl* ShadowedDecl = R.getFoundDecl(); 3842 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 3843 return; 3844 3845 // Fields are not shadowed by variables in C++ static methods. 3846 if (isa<FieldDecl>(ShadowedDecl)) 3847 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 3848 if (MD->isStatic()) 3849 return; 3850 3851 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 3852 if (shadowedVar->isExternC()) { 3853 // For shadowing external vars, make sure that we point to the global 3854 // declaration, not a locally scoped extern declaration. 3855 for (VarDecl::redecl_iterator 3856 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 3857 I != E; ++I) 3858 if (I->isFileVarDecl()) { 3859 ShadowedDecl = *I; 3860 break; 3861 } 3862 } 3863 3864 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 3865 3866 // Only warn about certain kinds of shadowing for class members. 3867 if (NewDC && NewDC->isRecord()) { 3868 // In particular, don't warn about shadowing non-class members. 3869 if (!OldDC->isRecord()) 3870 return; 3871 3872 // TODO: should we warn about static data members shadowing 3873 // static data members from base classes? 3874 3875 // TODO: don't diagnose for inaccessible shadowed members. 3876 // This is hard to do perfectly because we might friend the 3877 // shadowing context, but that's just a false negative. 3878 } 3879 3880 // Determine what kind of declaration we're shadowing. 3881 unsigned Kind; 3882 if (isa<RecordDecl>(OldDC)) { 3883 if (isa<FieldDecl>(ShadowedDecl)) 3884 Kind = 3; // field 3885 else 3886 Kind = 2; // static data member 3887 } else if (OldDC->isFileContext()) 3888 Kind = 1; // global 3889 else 3890 Kind = 0; // local 3891 3892 DeclarationName Name = R.getLookupName(); 3893 3894 // Emit warning and note. 3895 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 3896 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 3897} 3898 3899/// \brief Check -Wshadow without the advantage of a previous lookup. 3900void Sema::CheckShadow(Scope *S, VarDecl *D) { 3901 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 3902 Diagnostic::Ignored) 3903 return; 3904 3905 LookupResult R(*this, D->getDeclName(), D->getLocation(), 3906 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 3907 LookupName(R, S); 3908 CheckShadow(S, D, R); 3909} 3910 3911/// \brief Perform semantic checking on a newly-created variable 3912/// declaration. 3913/// 3914/// This routine performs all of the type-checking required for a 3915/// variable declaration once it has been built. It is used both to 3916/// check variables after they have been parsed and their declarators 3917/// have been translated into a declaration, and to check variables 3918/// that have been instantiated from a template. 3919/// 3920/// Sets NewVD->isInvalidDecl() if an error was encountered. 3921void Sema::CheckVariableDeclaration(VarDecl *NewVD, 3922 LookupResult &Previous, 3923 bool &Redeclaration) { 3924 // If the decl is already known invalid, don't check it. 3925 if (NewVD->isInvalidDecl()) 3926 return; 3927 3928 QualType T = NewVD->getType(); 3929 3930 if (T->isObjCObjectType()) { 3931 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 3932 return NewVD->setInvalidDecl(); 3933 } 3934 3935 // Emit an error if an address space was applied to decl with local storage. 3936 // This includes arrays of objects with address space qualifiers, but not 3937 // automatic variables that point to other address spaces. 3938 // ISO/IEC TR 18037 S5.1.2 3939 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 3940 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 3941 return NewVD->setInvalidDecl(); 3942 } 3943 3944 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 3945 && !NewVD->hasAttr<BlocksAttr>()) { 3946 if (getLangOptions().getGCMode() != LangOptions::NonGC) 3947 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 3948 else 3949 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 3950 } 3951 3952 bool isVM = T->isVariablyModifiedType(); 3953 if (isVM || NewVD->hasAttr<CleanupAttr>() || 3954 NewVD->hasAttr<BlocksAttr>()) 3955 getCurFunction()->setHasBranchProtectedScope(); 3956 3957 if ((isVM && NewVD->hasLinkage()) || 3958 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 3959 bool SizeIsNegative; 3960 llvm::APSInt Oversized; 3961 QualType FixedTy = 3962 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 3963 Oversized); 3964 3965 if (FixedTy.isNull() && T->isVariableArrayType()) { 3966 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 3967 // FIXME: This won't give the correct result for 3968 // int a[10][n]; 3969 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 3970 3971 if (NewVD->isFileVarDecl()) 3972 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 3973 << SizeRange; 3974 else if (NewVD->getStorageClass() == SC_Static) 3975 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 3976 << SizeRange; 3977 else 3978 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 3979 << SizeRange; 3980 return NewVD->setInvalidDecl(); 3981 } 3982 3983 if (FixedTy.isNull()) { 3984 if (NewVD->isFileVarDecl()) 3985 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 3986 else 3987 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 3988 return NewVD->setInvalidDecl(); 3989 } 3990 3991 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 3992 NewVD->setType(FixedTy); 3993 } 3994 3995 if (Previous.empty() && NewVD->isExternC()) { 3996 // Since we did not find anything by this name and we're declaring 3997 // an extern "C" variable, look for a non-visible extern "C" 3998 // declaration with the same name. 3999 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4000 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 4001 if (Pos != LocallyScopedExternalDecls.end()) 4002 Previous.addDecl(Pos->second); 4003 } 4004 4005 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4006 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4007 << T; 4008 return NewVD->setInvalidDecl(); 4009 } 4010 4011 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4012 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4013 return NewVD->setInvalidDecl(); 4014 } 4015 4016 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4017 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4018 return NewVD->setInvalidDecl(); 4019 } 4020 4021 // Function pointers and references cannot have qualified function type, only 4022 // function pointer-to-members can do that. 4023 QualType Pointee; 4024 unsigned PtrOrRef = 0; 4025 if (const PointerType *Ptr = T->getAs<PointerType>()) 4026 Pointee = Ptr->getPointeeType(); 4027 else if (const ReferenceType *Ref = T->getAs<ReferenceType>()) { 4028 Pointee = Ref->getPointeeType(); 4029 PtrOrRef = 1; 4030 } 4031 if (!Pointee.isNull() && Pointee->isFunctionProtoType() && 4032 Pointee->getAs<FunctionProtoType>()->getTypeQuals() != 0) { 4033 Diag(NewVD->getLocation(), diag::err_invalid_qualified_function_pointer) 4034 << PtrOrRef; 4035 return NewVD->setInvalidDecl(); 4036 } 4037 4038 if (!Previous.empty()) { 4039 Redeclaration = true; 4040 MergeVarDecl(NewVD, Previous); 4041 } 4042} 4043 4044/// \brief Data used with FindOverriddenMethod 4045struct FindOverriddenMethodData { 4046 Sema *S; 4047 CXXMethodDecl *Method; 4048}; 4049 4050/// \brief Member lookup function that determines whether a given C++ 4051/// method overrides a method in a base class, to be used with 4052/// CXXRecordDecl::lookupInBases(). 4053static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4054 CXXBasePath &Path, 4055 void *UserData) { 4056 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4057 4058 FindOverriddenMethodData *Data 4059 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4060 4061 DeclarationName Name = Data->Method->getDeclName(); 4062 4063 // FIXME: Do we care about other names here too? 4064 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4065 // We really want to find the base class destructor here. 4066 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4067 CanQualType CT = Data->S->Context.getCanonicalType(T); 4068 4069 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4070 } 4071 4072 for (Path.Decls = BaseRecord->lookup(Name); 4073 Path.Decls.first != Path.Decls.second; 4074 ++Path.Decls.first) { 4075 NamedDecl *D = *Path.Decls.first; 4076 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4077 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4078 return true; 4079 } 4080 } 4081 4082 return false; 4083} 4084 4085/// AddOverriddenMethods - See if a method overrides any in the base classes, 4086/// and if so, check that it's a valid override and remember it. 4087bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4088 // Look for virtual methods in base classes that this method might override. 4089 CXXBasePaths Paths; 4090 FindOverriddenMethodData Data; 4091 Data.Method = MD; 4092 Data.S = this; 4093 bool AddedAny = false; 4094 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4095 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4096 E = Paths.found_decls_end(); I != E; ++I) { 4097 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4098 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4099 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4100 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4101 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4102 AddedAny = true; 4103 } 4104 } 4105 } 4106 } 4107 4108 return AddedAny; 4109} 4110 4111static void DiagnoseInvalidRedeclaration(Sema &S, FunctionDecl *NewFD) { 4112 LookupResult Prev(S, NewFD->getDeclName(), NewFD->getLocation(), 4113 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4114 S.LookupQualifiedName(Prev, NewFD->getDeclContext()); 4115 assert(!Prev.isAmbiguous() && 4116 "Cannot have an ambiguity in previous-declaration lookup"); 4117 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 4118 Func != FuncEnd; ++Func) { 4119 if (isa<FunctionDecl>(*Func) && 4120 isNearlyMatchingFunction(S.Context, cast<FunctionDecl>(*Func), NewFD)) 4121 S.Diag((*Func)->getLocation(), diag::note_member_def_close_match); 4122 } 4123} 4124 4125NamedDecl* 4126Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4127 QualType R, TypeSourceInfo *TInfo, 4128 LookupResult &Previous, 4129 MultiTemplateParamsArg TemplateParamLists, 4130 bool IsFunctionDefinition, bool &Redeclaration) { 4131 assert(R.getTypePtr()->isFunctionType()); 4132 4133 // TODO: consider using NameInfo for diagnostic. 4134 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4135 DeclarationName Name = NameInfo.getName(); 4136 FunctionDecl::StorageClass SC = SC_None; 4137 switch (D.getDeclSpec().getStorageClassSpec()) { 4138 default: assert(0 && "Unknown storage class!"); 4139 case DeclSpec::SCS_auto: 4140 case DeclSpec::SCS_register: 4141 case DeclSpec::SCS_mutable: 4142 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4143 diag::err_typecheck_sclass_func); 4144 D.setInvalidType(); 4145 break; 4146 case DeclSpec::SCS_unspecified: SC = SC_None; break; 4147 case DeclSpec::SCS_extern: SC = SC_Extern; break; 4148 case DeclSpec::SCS_static: { 4149 if (CurContext->getRedeclContext()->isFunctionOrMethod()) { 4150 // C99 6.7.1p5: 4151 // The declaration of an identifier for a function that has 4152 // block scope shall have no explicit storage-class specifier 4153 // other than extern 4154 // See also (C++ [dcl.stc]p4). 4155 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4156 diag::err_static_block_func); 4157 SC = SC_None; 4158 } else 4159 SC = SC_Static; 4160 break; 4161 } 4162 case DeclSpec::SCS_private_extern: SC = SC_PrivateExtern; break; 4163 } 4164 4165 if (D.getDeclSpec().isThreadSpecified()) 4166 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4167 4168 // Do not allow returning a objc interface by-value. 4169 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 4170 Diag(D.getIdentifierLoc(), 4171 diag::err_object_cannot_be_passed_returned_by_value) << 0 4172 << R->getAs<FunctionType>()->getResultType(); 4173 D.setInvalidType(); 4174 } 4175 4176 FunctionDecl *NewFD; 4177 bool isInline = D.getDeclSpec().isInlineSpecified(); 4178 bool isFriend = false; 4179 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4180 FunctionDecl::StorageClass SCAsWritten 4181 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 4182 FunctionTemplateDecl *FunctionTemplate = 0; 4183 bool isExplicitSpecialization = false; 4184 bool isFunctionTemplateSpecialization = false; 4185 4186 if (!getLangOptions().CPlusPlus) { 4187 // Determine whether the function was written with a 4188 // prototype. This true when: 4189 // - there is a prototype in the declarator, or 4190 // - the type R of the function is some kind of typedef or other reference 4191 // to a type name (which eventually refers to a function type). 4192 bool HasPrototype = 4193 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 4194 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 4195 4196 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4197 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4198 HasPrototype); 4199 if (D.isInvalidType()) 4200 NewFD->setInvalidDecl(); 4201 4202 // Set the lexical context. 4203 NewFD->setLexicalDeclContext(CurContext); 4204 // Filter out previous declarations that don't match the scope. 4205 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 4206 /*ExplicitInstantiationOrSpecialization=*/false); 4207 } else { 4208 isFriend = D.getDeclSpec().isFriendSpecified(); 4209 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4210 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 4211 bool isVirtualOkay = false; 4212 4213 // Check that the return type is not an abstract class type. 4214 // For record types, this is done by the AbstractClassUsageDiagnoser once 4215 // the class has been completely parsed. 4216 if (!DC->isRecord() && 4217 RequireNonAbstractType(D.getIdentifierLoc(), 4218 R->getAs<FunctionType>()->getResultType(), 4219 diag::err_abstract_type_in_decl, 4220 AbstractReturnType)) 4221 D.setInvalidType(); 4222 4223 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 4224 // This is a C++ constructor declaration. 4225 assert(DC->isRecord() && 4226 "Constructors can only be declared in a member context"); 4227 4228 R = CheckConstructorDeclarator(D, R, SC); 4229 4230 // Create the new declaration 4231 CXXConstructorDecl *NewCD = CXXConstructorDecl::Create( 4232 Context, 4233 cast<CXXRecordDecl>(DC), 4234 D.getSourceRange().getBegin(), 4235 NameInfo, R, TInfo, 4236 isExplicit, isInline, 4237 /*isImplicitlyDeclared=*/false); 4238 4239 NewFD = NewCD; 4240 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4241 // This is a C++ destructor declaration. 4242 if (DC->isRecord()) { 4243 R = CheckDestructorDeclarator(D, R, SC); 4244 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 4245 4246 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(Context, Record, 4247 D.getSourceRange().getBegin(), 4248 NameInfo, R, TInfo, 4249 isInline, 4250 /*isImplicitlyDeclared=*/false); 4251 NewFD = NewDD; 4252 isVirtualOkay = true; 4253 4254 // If the class is complete, then we now create the implicit exception 4255 // specification. If the class is incomplete or dependent, we can't do 4256 // it yet. 4257 if (getLangOptions().CPlusPlus0x && !Record->isDependentType() && 4258 Record->getDefinition() && !Record->isBeingDefined() && 4259 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 4260 AdjustDestructorExceptionSpec(Record, NewDD); 4261 } 4262 4263 } else { 4264 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 4265 4266 // Create a FunctionDecl to satisfy the function definition parsing 4267 // code path. 4268 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4269 D.getIdentifierLoc(), Name, R, TInfo, 4270 SC, SCAsWritten, isInline, 4271 /*hasPrototype=*/true); 4272 D.setInvalidType(); 4273 } 4274 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4275 if (!DC->isRecord()) { 4276 Diag(D.getIdentifierLoc(), 4277 diag::err_conv_function_not_member); 4278 return 0; 4279 } 4280 4281 CheckConversionDeclarator(D, R, SC); 4282 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 4283 D.getSourceRange().getBegin(), 4284 NameInfo, R, TInfo, 4285 isInline, isExplicit, 4286 SourceLocation()); 4287 4288 isVirtualOkay = true; 4289 } else if (DC->isRecord()) { 4290 // If the of the function is the same as the name of the record, then this 4291 // must be an invalid constructor that has a return type. 4292 // (The parser checks for a return type and makes the declarator a 4293 // constructor if it has no return type). 4294 // must have an invalid constructor that has a return type 4295 if (Name.getAsIdentifierInfo() && 4296 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 4297 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 4298 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4299 << SourceRange(D.getIdentifierLoc()); 4300 return 0; 4301 } 4302 4303 bool isStatic = SC == SC_Static; 4304 4305 // [class.free]p1: 4306 // Any allocation function for a class T is a static member 4307 // (even if not explicitly declared static). 4308 if (Name.getCXXOverloadedOperator() == OO_New || 4309 Name.getCXXOverloadedOperator() == OO_Array_New) 4310 isStatic = true; 4311 4312 // [class.free]p6 Any deallocation function for a class X is a static member 4313 // (even if not explicitly declared static). 4314 if (Name.getCXXOverloadedOperator() == OO_Delete || 4315 Name.getCXXOverloadedOperator() == OO_Array_Delete) 4316 isStatic = true; 4317 4318 // This is a C++ method declaration. 4319 CXXMethodDecl *NewMD = CXXMethodDecl::Create( 4320 Context, cast<CXXRecordDecl>(DC), 4321 D.getSourceRange().getBegin(), 4322 NameInfo, R, TInfo, 4323 isStatic, SCAsWritten, isInline, 4324 SourceLocation()); 4325 NewFD = NewMD; 4326 4327 isVirtualOkay = !isStatic; 4328 } else { 4329 // Determine whether the function was written with a 4330 // prototype. This true when: 4331 // - we're in C++ (where every function has a prototype), 4332 NewFD = FunctionDecl::Create(Context, DC, D.getSourceRange().getBegin(), 4333 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 4334 true/*HasPrototype*/); 4335 } 4336 4337 if (isFriend && !isInline && IsFunctionDefinition) { 4338 // C++ [class.friend]p5 4339 // A function can be defined in a friend declaration of a 4340 // class . . . . Such a function is implicitly inline. 4341 NewFD->setImplicitlyInline(); 4342 } 4343 4344 SetNestedNameSpecifier(NewFD, D); 4345 isExplicitSpecialization = false; 4346 isFunctionTemplateSpecialization = false; 4347 if (D.isInvalidType()) 4348 NewFD->setInvalidDecl(); 4349 4350 // Set the lexical context. If the declarator has a C++ 4351 // scope specifier, or is the object of a friend declaration, the 4352 // lexical context will be different from the semantic context. 4353 NewFD->setLexicalDeclContext(CurContext); 4354 4355 // Match up the template parameter lists with the scope specifier, then 4356 // determine whether we have a template or a template specialization. 4357 bool Invalid = false; 4358 if (TemplateParameterList *TemplateParams 4359 = MatchTemplateParametersToScopeSpecifier( 4360 D.getDeclSpec().getSourceRange().getBegin(), 4361 D.getIdentifierLoc(), 4362 D.getCXXScopeSpec(), 4363 TemplateParamLists.get(), 4364 TemplateParamLists.size(), 4365 isFriend, 4366 isExplicitSpecialization, 4367 Invalid)) { 4368 if (TemplateParams->size() > 0) { 4369 // This is a function template 4370 4371 // Check that we can declare a template here. 4372 if (CheckTemplateDeclScope(S, TemplateParams)) 4373 return 0; 4374 4375 // A destructor cannot be a template. 4376 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4377 Diag(NewFD->getLocation(), diag::err_destructor_template); 4378 return 0; 4379 } 4380 4381 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 4382 NewFD->getLocation(), 4383 Name, TemplateParams, 4384 NewFD); 4385 FunctionTemplate->setLexicalDeclContext(CurContext); 4386 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 4387 4388 // For source fidelity, store the other template param lists. 4389 if (TemplateParamLists.size() > 1) { 4390 NewFD->setTemplateParameterListsInfo(Context, 4391 TemplateParamLists.size() - 1, 4392 TemplateParamLists.release()); 4393 } 4394 } else { 4395 // This is a function template specialization. 4396 isFunctionTemplateSpecialization = true; 4397 // For source fidelity, store all the template param lists. 4398 NewFD->setTemplateParameterListsInfo(Context, 4399 TemplateParamLists.size(), 4400 TemplateParamLists.release()); 4401 4402 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 4403 if (isFriend) { 4404 // We want to remove the "template<>", found here. 4405 SourceRange RemoveRange = TemplateParams->getSourceRange(); 4406 4407 // If we remove the template<> and the name is not a 4408 // template-id, we're actually silently creating a problem: 4409 // the friend declaration will refer to an untemplated decl, 4410 // and clearly the user wants a template specialization. So 4411 // we need to insert '<>' after the name. 4412 SourceLocation InsertLoc; 4413 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 4414 InsertLoc = D.getName().getSourceRange().getEnd(); 4415 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 4416 } 4417 4418 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 4419 << Name << RemoveRange 4420 << FixItHint::CreateRemoval(RemoveRange) 4421 << FixItHint::CreateInsertion(InsertLoc, "<>"); 4422 } 4423 } 4424 } 4425 else { 4426 // All template param lists were matched against the scope specifier: 4427 // this is NOT (an explicit specialization of) a template. 4428 if (TemplateParamLists.size() > 0) 4429 // For source fidelity, store all the template param lists. 4430 NewFD->setTemplateParameterListsInfo(Context, 4431 TemplateParamLists.size(), 4432 TemplateParamLists.release()); 4433 } 4434 4435 if (Invalid) { 4436 NewFD->setInvalidDecl(); 4437 if (FunctionTemplate) 4438 FunctionTemplate->setInvalidDecl(); 4439 } 4440 4441 // C++ [dcl.fct.spec]p5: 4442 // The virtual specifier shall only be used in declarations of 4443 // nonstatic class member functions that appear within a 4444 // member-specification of a class declaration; see 10.3. 4445 // 4446 if (isVirtual && !NewFD->isInvalidDecl()) { 4447 if (!isVirtualOkay) { 4448 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4449 diag::err_virtual_non_function); 4450 } else if (!CurContext->isRecord()) { 4451 // 'virtual' was specified outside of the class. 4452 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4453 diag::err_virtual_out_of_class) 4454 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4455 } else if (NewFD->getDescribedFunctionTemplate()) { 4456 // C++ [temp.mem]p3: 4457 // A member function template shall not be virtual. 4458 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4459 diag::err_virtual_member_function_template) 4460 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 4461 } else { 4462 // Okay: Add virtual to the method. 4463 NewFD->setVirtualAsWritten(true); 4464 } 4465 } 4466 4467 // C++ [dcl.fct.spec]p3: 4468 // The inline specifier shall not appear on a block scope function declaration. 4469 if (isInline && !NewFD->isInvalidDecl()) { 4470 if (CurContext->isFunctionOrMethod()) { 4471 // 'inline' is not allowed on block scope function declaration. 4472 Diag(D.getDeclSpec().getInlineSpecLoc(), 4473 diag::err_inline_declaration_block_scope) << Name 4474 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 4475 } 4476 } 4477 4478 // C++ [dcl.fct.spec]p6: 4479 // The explicit specifier shall be used only in the declaration of a 4480 // constructor or conversion function within its class definition; see 12.3.1 4481 // and 12.3.2. 4482 if (isExplicit && !NewFD->isInvalidDecl()) { 4483 if (!CurContext->isRecord()) { 4484 // 'explicit' was specified outside of the class. 4485 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4486 diag::err_explicit_out_of_class) 4487 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4488 } else if (!isa<CXXConstructorDecl>(NewFD) && 4489 !isa<CXXConversionDecl>(NewFD)) { 4490 // 'explicit' was specified on a function that wasn't a constructor 4491 // or conversion function. 4492 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4493 diag::err_explicit_non_ctor_or_conv_function) 4494 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 4495 } 4496 } 4497 4498 // Filter out previous declarations that don't match the scope. 4499 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 4500 isExplicitSpecialization || 4501 isFunctionTemplateSpecialization); 4502 4503 if (isFriend) { 4504 // For now, claim that the objects have no previous declaration. 4505 if (FunctionTemplate) { 4506 FunctionTemplate->setObjectOfFriendDecl(false); 4507 FunctionTemplate->setAccess(AS_public); 4508 } 4509 NewFD->setObjectOfFriendDecl(false); 4510 NewFD->setAccess(AS_public); 4511 } 4512 4513 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && IsFunctionDefinition) { 4514 // A method is implicitly inline if it's defined in its class 4515 // definition. 4516 NewFD->setImplicitlyInline(); 4517 } 4518 4519 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 4520 !CurContext->isRecord()) { 4521 // C++ [class.static]p1: 4522 // A data or function member of a class may be declared static 4523 // in a class definition, in which case it is a static member of 4524 // the class. 4525 4526 // Complain about the 'static' specifier if it's on an out-of-line 4527 // member function definition. 4528 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4529 diag::err_static_out_of_line) 4530 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4531 } 4532 } 4533 4534 // Handle GNU asm-label extension (encoded as an attribute). 4535 if (Expr *E = (Expr*) D.getAsmLabel()) { 4536 // The parser guarantees this is a string. 4537 StringLiteral *SE = cast<StringLiteral>(E); 4538 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 4539 SE->getString())); 4540 } 4541 4542 // Copy the parameter declarations from the declarator D to the function 4543 // declaration NewFD, if they are available. First scavenge them into Params. 4544 llvm::SmallVector<ParmVarDecl*, 16> Params; 4545 if (D.isFunctionDeclarator()) { 4546 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4547 4548 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 4549 // function that takes no arguments, not a function that takes a 4550 // single void argument. 4551 // We let through "const void" here because Sema::GetTypeForDeclarator 4552 // already checks for that case. 4553 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4554 FTI.ArgInfo[0].Param && 4555 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 4556 // Empty arg list, don't push any params. 4557 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 4558 4559 // In C++, the empty parameter-type-list must be spelled "void"; a 4560 // typedef of void is not permitted. 4561 if (getLangOptions().CPlusPlus && 4562 Param->getType().getUnqualifiedType() != Context.VoidTy) { 4563 bool IsTypeAlias = false; 4564 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 4565 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 4566 else if (const TemplateSpecializationType *TST = 4567 Param->getType()->getAs<TemplateSpecializationType>()) 4568 IsTypeAlias = TST->isTypeAlias(); 4569 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 4570 << IsTypeAlias; 4571 } 4572 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 4573 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 4574 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 4575 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 4576 Param->setDeclContext(NewFD); 4577 Params.push_back(Param); 4578 4579 if (Param->isInvalidDecl()) 4580 NewFD->setInvalidDecl(); 4581 } 4582 } 4583 4584 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 4585 // When we're declaring a function with a typedef, typeof, etc as in the 4586 // following example, we'll need to synthesize (unnamed) 4587 // parameters for use in the declaration. 4588 // 4589 // @code 4590 // typedef void fn(int); 4591 // fn f; 4592 // @endcode 4593 4594 // Synthesize a parameter for each argument type. 4595 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 4596 AE = FT->arg_type_end(); AI != AE; ++AI) { 4597 ParmVarDecl *Param = 4598 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 4599 Param->setScopeInfo(0, Params.size()); 4600 Params.push_back(Param); 4601 } 4602 } else { 4603 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 4604 "Should not need args for typedef of non-prototype fn"); 4605 } 4606 // Finally, we know we have the right number of parameters, install them. 4607 NewFD->setParams(Params.data(), Params.size()); 4608 4609 // Process the non-inheritable attributes on this declaration. 4610 ProcessDeclAttributes(S, NewFD, D, 4611 /*NonInheritable=*/true, /*Inheritable=*/false); 4612 4613 if (!getLangOptions().CPlusPlus) { 4614 // Perform semantic checking on the function declaration. 4615 bool isExplicitSpecialization=false; 4616 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 4617 Redeclaration); 4618 assert((NewFD->isInvalidDecl() || !Redeclaration || 4619 Previous.getResultKind() != LookupResult::FoundOverloaded) && 4620 "previous declaration set still overloaded"); 4621 } else { 4622 // If the declarator is a template-id, translate the parser's template 4623 // argument list into our AST format. 4624 bool HasExplicitTemplateArgs = false; 4625 TemplateArgumentListInfo TemplateArgs; 4626 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 4627 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4628 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 4629 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 4630 ASTTemplateArgsPtr TemplateArgsPtr(*this, 4631 TemplateId->getTemplateArgs(), 4632 TemplateId->NumArgs); 4633 translateTemplateArguments(TemplateArgsPtr, 4634 TemplateArgs); 4635 TemplateArgsPtr.release(); 4636 4637 HasExplicitTemplateArgs = true; 4638 4639 if (NewFD->isInvalidDecl()) { 4640 HasExplicitTemplateArgs = false; 4641 } else if (FunctionTemplate) { 4642 // Function template with explicit template arguments. 4643 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 4644 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 4645 4646 HasExplicitTemplateArgs = false; 4647 } else if (!isFunctionTemplateSpecialization && 4648 !D.getDeclSpec().isFriendSpecified()) { 4649 // We have encountered something that the user meant to be a 4650 // specialization (because it has explicitly-specified template 4651 // arguments) but that was not introduced with a "template<>" (or had 4652 // too few of them). 4653 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 4654 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 4655 << FixItHint::CreateInsertion( 4656 D.getDeclSpec().getSourceRange().getBegin(), 4657 "template<> "); 4658 isFunctionTemplateSpecialization = true; 4659 } else { 4660 // "friend void foo<>(int);" is an implicit specialization decl. 4661 isFunctionTemplateSpecialization = true; 4662 } 4663 } else if (isFriend && isFunctionTemplateSpecialization) { 4664 // This combination is only possible in a recovery case; the user 4665 // wrote something like: 4666 // template <> friend void foo(int); 4667 // which we're recovering from as if the user had written: 4668 // friend void foo<>(int); 4669 // Go ahead and fake up a template id. 4670 HasExplicitTemplateArgs = true; 4671 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 4672 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 4673 } 4674 4675 // If it's a friend (and only if it's a friend), it's possible 4676 // that either the specialized function type or the specialized 4677 // template is dependent, and therefore matching will fail. In 4678 // this case, don't check the specialization yet. 4679 if (isFunctionTemplateSpecialization && isFriend && 4680 (NewFD->getType()->isDependentType() || DC->isDependentContext())) { 4681 assert(HasExplicitTemplateArgs && 4682 "friend function specialization without template args"); 4683 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 4684 Previous)) 4685 NewFD->setInvalidDecl(); 4686 } else if (isFunctionTemplateSpecialization) { 4687 if (CurContext->isDependentContext() && CurContext->isRecord() 4688 && !isFriend) { 4689 Diag(NewFD->getLocation(), diag::err_function_specialization_in_class) 4690 << NewFD->getDeclName(); 4691 NewFD->setInvalidDecl(); 4692 return 0; 4693 } else if (CheckFunctionTemplateSpecialization(NewFD, 4694 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 4695 Previous)) 4696 NewFD->setInvalidDecl(); 4697 4698 // C++ [dcl.stc]p1: 4699 // A storage-class-specifier shall not be specified in an explicit 4700 // specialization (14.7.3) 4701 if (SC != SC_None) { 4702 if (SC != NewFD->getStorageClass()) 4703 Diag(NewFD->getLocation(), 4704 diag::err_explicit_specialization_inconsistent_storage_class) 4705 << SC 4706 << FixItHint::CreateRemoval( 4707 D.getDeclSpec().getStorageClassSpecLoc()); 4708 4709 else 4710 Diag(NewFD->getLocation(), 4711 diag::ext_explicit_specialization_storage_class) 4712 << FixItHint::CreateRemoval( 4713 D.getDeclSpec().getStorageClassSpecLoc()); 4714 } 4715 4716 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 4717 if (CheckMemberSpecialization(NewFD, Previous)) 4718 NewFD->setInvalidDecl(); 4719 } 4720 4721 // Perform semantic checking on the function declaration. 4722 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 4723 Redeclaration); 4724 4725 assert((NewFD->isInvalidDecl() || !Redeclaration || 4726 Previous.getResultKind() != LookupResult::FoundOverloaded) && 4727 "previous declaration set still overloaded"); 4728 4729 NamedDecl *PrincipalDecl = (FunctionTemplate 4730 ? cast<NamedDecl>(FunctionTemplate) 4731 : NewFD); 4732 4733 if (isFriend && Redeclaration) { 4734 AccessSpecifier Access = AS_public; 4735 if (!NewFD->isInvalidDecl()) 4736 Access = NewFD->getPreviousDeclaration()->getAccess(); 4737 4738 NewFD->setAccess(Access); 4739 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 4740 4741 PrincipalDecl->setObjectOfFriendDecl(true); 4742 } 4743 4744 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 4745 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 4746 PrincipalDecl->setNonMemberOperator(); 4747 4748 // If we have a function template, check the template parameter 4749 // list. This will check and merge default template arguments. 4750 if (FunctionTemplate) { 4751 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration(); 4752 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 4753 PrevTemplate? PrevTemplate->getTemplateParameters() : 0, 4754 D.getDeclSpec().isFriendSpecified() 4755 ? (IsFunctionDefinition 4756 ? TPC_FriendFunctionTemplateDefinition 4757 : TPC_FriendFunctionTemplate) 4758 : (D.getCXXScopeSpec().isSet() && 4759 DC && DC->isRecord() && 4760 DC->isDependentContext()) 4761 ? TPC_ClassTemplateMember 4762 : TPC_FunctionTemplate); 4763 } 4764 4765 if (NewFD->isInvalidDecl()) { 4766 // Ignore all the rest of this. 4767 } else if (!Redeclaration) { 4768 // Fake up an access specifier if it's supposed to be a class member. 4769 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 4770 NewFD->setAccess(AS_public); 4771 4772 // Qualified decls generally require a previous declaration. 4773 if (D.getCXXScopeSpec().isSet()) { 4774 // ...with the major exception of templated-scope or 4775 // dependent-scope friend declarations. 4776 4777 // TODO: we currently also suppress this check in dependent 4778 // contexts because (1) the parameter depth will be off when 4779 // matching friend templates and (2) we might actually be 4780 // selecting a friend based on a dependent factor. But there 4781 // are situations where these conditions don't apply and we 4782 // can actually do this check immediately. 4783 if (isFriend && 4784 (TemplateParamLists.size() || 4785 D.getCXXScopeSpec().getScopeRep()->isDependent() || 4786 CurContext->isDependentContext())) { 4787 // ignore these 4788 } else { 4789 // The user tried to provide an out-of-line definition for a 4790 // function that is a member of a class or namespace, but there 4791 // was no such member function declared (C++ [class.mfct]p2, 4792 // C++ [namespace.memdef]p2). For example: 4793 // 4794 // class X { 4795 // void f() const; 4796 // }; 4797 // 4798 // void X::f() { } // ill-formed 4799 // 4800 // Complain about this problem, and attempt to suggest close 4801 // matches (e.g., those that differ only in cv-qualifiers and 4802 // whether the parameter types are references). 4803 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 4804 << Name << DC << D.getCXXScopeSpec().getRange(); 4805 NewFD->setInvalidDecl(); 4806 4807 DiagnoseInvalidRedeclaration(*this, NewFD); 4808 } 4809 4810 // Unqualified local friend declarations are required to resolve 4811 // to something. 4812 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 4813 Diag(D.getIdentifierLoc(), diag::err_no_matching_local_friend); 4814 NewFD->setInvalidDecl(); 4815 DiagnoseInvalidRedeclaration(*this, NewFD); 4816 } 4817 4818 } else if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && 4819 !isFriend && !isFunctionTemplateSpecialization && 4820 !isExplicitSpecialization) { 4821 // An out-of-line member function declaration must also be a 4822 // definition (C++ [dcl.meaning]p1). 4823 // Note that this is not the case for explicit specializations of 4824 // function templates or member functions of class templates, per 4825 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension 4826 // for compatibility with old SWIG code which likes to generate them. 4827 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 4828 << D.getCXXScopeSpec().getRange(); 4829 } 4830 } 4831 4832 4833 // Handle attributes. We need to have merged decls when handling attributes 4834 // (for example to check for conflicts, etc). 4835 // FIXME: This needs to happen before we merge declarations. Then, 4836 // let attribute merging cope with attribute conflicts. 4837 ProcessDeclAttributes(S, NewFD, D, 4838 /*NonInheritable=*/false, /*Inheritable=*/true); 4839 4840 // attributes declared post-definition are currently ignored 4841 // FIXME: This should happen during attribute merging 4842 if (Redeclaration && Previous.isSingleResult()) { 4843 const FunctionDecl *Def; 4844 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 4845 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) { 4846 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 4847 Diag(Def->getLocation(), diag::note_previous_definition); 4848 } 4849 } 4850 4851 AddKnownFunctionAttributes(NewFD); 4852 4853 if (NewFD->hasAttr<OverloadableAttr>() && 4854 !NewFD->getType()->getAs<FunctionProtoType>()) { 4855 Diag(NewFD->getLocation(), 4856 diag::err_attribute_overloadable_no_prototype) 4857 << NewFD; 4858 4859 // Turn this into a variadic function with no parameters. 4860 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 4861 FunctionProtoType::ExtProtoInfo EPI; 4862 EPI.Variadic = true; 4863 EPI.ExtInfo = FT->getExtInfo(); 4864 4865 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 4866 NewFD->setType(R); 4867 } 4868 4869 // If there's a #pragma GCC visibility in scope, and this isn't a class 4870 // member, set the visibility of this function. 4871 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4872 AddPushedVisibilityAttribute(NewFD); 4873 4874 // If this is a locally-scoped extern C function, update the 4875 // map of such names. 4876 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 4877 && !NewFD->isInvalidDecl()) 4878 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 4879 4880 // Set this FunctionDecl's range up to the right paren. 4881 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 4882 4883 if (getLangOptions().CPlusPlus) { 4884 if (FunctionTemplate) { 4885 if (NewFD->isInvalidDecl()) 4886 FunctionTemplate->setInvalidDecl(); 4887 return FunctionTemplate; 4888 } 4889 } 4890 4891 MarkUnusedFileScopedDecl(NewFD); 4892 4893 if (getLangOptions().CUDA) 4894 if (IdentifierInfo *II = NewFD->getIdentifier()) 4895 if (!NewFD->isInvalidDecl() && 4896 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4897 if (II->isStr("cudaConfigureCall")) { 4898 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 4899 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 4900 4901 Context.setcudaConfigureCallDecl(NewFD); 4902 } 4903 } 4904 4905 return NewFD; 4906} 4907 4908/// \brief Perform semantic checking of a new function declaration. 4909/// 4910/// Performs semantic analysis of the new function declaration 4911/// NewFD. This routine performs all semantic checking that does not 4912/// require the actual declarator involved in the declaration, and is 4913/// used both for the declaration of functions as they are parsed 4914/// (called via ActOnDeclarator) and for the declaration of functions 4915/// that have been instantiated via C++ template instantiation (called 4916/// via InstantiateDecl). 4917/// 4918/// \param IsExplicitSpecialiation whether this new function declaration is 4919/// an explicit specialization of the previous declaration. 4920/// 4921/// This sets NewFD->isInvalidDecl() to true if there was an error. 4922void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 4923 LookupResult &Previous, 4924 bool IsExplicitSpecialization, 4925 bool &Redeclaration) { 4926 // If NewFD is already known erroneous, don't do any of this checking. 4927 if (NewFD->isInvalidDecl()) { 4928 // If this is a class member, mark the class invalid immediately. 4929 // This avoids some consistency errors later. 4930 if (isa<CXXMethodDecl>(NewFD)) 4931 cast<CXXMethodDecl>(NewFD)->getParent()->setInvalidDecl(); 4932 4933 return; 4934 } 4935 4936 if (NewFD->getResultType()->isVariablyModifiedType()) { 4937 // Functions returning a variably modified type violate C99 6.7.5.2p2 4938 // because all functions have linkage. 4939 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 4940 return NewFD->setInvalidDecl(); 4941 } 4942 4943 if (NewFD->isMain()) 4944 CheckMain(NewFD); 4945 4946 // Check for a previous declaration of this name. 4947 if (Previous.empty() && NewFD->isExternC()) { 4948 // Since we did not find anything by this name and we're declaring 4949 // an extern "C" function, look for a non-visible extern "C" 4950 // declaration with the same name. 4951 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4952 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 4953 if (Pos != LocallyScopedExternalDecls.end()) 4954 Previous.addDecl(Pos->second); 4955 } 4956 4957 // Merge or overload the declaration with an existing declaration of 4958 // the same name, if appropriate. 4959 if (!Previous.empty()) { 4960 // Determine whether NewFD is an overload of PrevDecl or 4961 // a declaration that requires merging. If it's an overload, 4962 // there's no more work to do here; we'll just add the new 4963 // function to the scope. 4964 4965 NamedDecl *OldDecl = 0; 4966 if (!AllowOverloadingOfFunction(Previous, Context)) { 4967 Redeclaration = true; 4968 OldDecl = Previous.getFoundDecl(); 4969 } else { 4970 switch (CheckOverload(S, NewFD, Previous, OldDecl, 4971 /*NewIsUsingDecl*/ false)) { 4972 case Ovl_Match: 4973 Redeclaration = true; 4974 break; 4975 4976 case Ovl_NonFunction: 4977 Redeclaration = true; 4978 break; 4979 4980 case Ovl_Overload: 4981 Redeclaration = false; 4982 break; 4983 } 4984 4985 if (!getLangOptions().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 4986 // If a function name is overloadable in C, then every function 4987 // with that name must be marked "overloadable". 4988 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 4989 << Redeclaration << NewFD; 4990 NamedDecl *OverloadedDecl = 0; 4991 if (Redeclaration) 4992 OverloadedDecl = OldDecl; 4993 else if (!Previous.empty()) 4994 OverloadedDecl = Previous.getRepresentativeDecl(); 4995 if (OverloadedDecl) 4996 Diag(OverloadedDecl->getLocation(), 4997 diag::note_attribute_overloadable_prev_overload); 4998 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 4999 Context)); 5000 } 5001 } 5002 5003 if (Redeclaration) { 5004 // NewFD and OldDecl represent declarations that need to be 5005 // merged. 5006 if (MergeFunctionDecl(NewFD, OldDecl)) 5007 return NewFD->setInvalidDecl(); 5008 5009 Previous.clear(); 5010 Previous.addDecl(OldDecl); 5011 5012 if (FunctionTemplateDecl *OldTemplateDecl 5013 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 5014 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 5015 FunctionTemplateDecl *NewTemplateDecl 5016 = NewFD->getDescribedFunctionTemplate(); 5017 assert(NewTemplateDecl && "Template/non-template mismatch"); 5018 if (CXXMethodDecl *Method 5019 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 5020 Method->setAccess(OldTemplateDecl->getAccess()); 5021 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 5022 } 5023 5024 // If this is an explicit specialization of a member that is a function 5025 // template, mark it as a member specialization. 5026 if (IsExplicitSpecialization && 5027 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 5028 NewTemplateDecl->setMemberSpecialization(); 5029 assert(OldTemplateDecl->isMemberSpecialization()); 5030 } 5031 } else { 5032 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 5033 NewFD->setAccess(OldDecl->getAccess()); 5034 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 5035 } 5036 } 5037 } 5038 5039 // Semantic checking for this function declaration (in isolation). 5040 if (getLangOptions().CPlusPlus) { 5041 // C++-specific checks. 5042 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 5043 CheckConstructor(Constructor); 5044 } else if (CXXDestructorDecl *Destructor = 5045 dyn_cast<CXXDestructorDecl>(NewFD)) { 5046 CXXRecordDecl *Record = Destructor->getParent(); 5047 QualType ClassType = Context.getTypeDeclType(Record); 5048 5049 // FIXME: Shouldn't we be able to perform this check even when the class 5050 // type is dependent? Both gcc and edg can handle that. 5051 if (!ClassType->isDependentType()) { 5052 DeclarationName Name 5053 = Context.DeclarationNames.getCXXDestructorName( 5054 Context.getCanonicalType(ClassType)); 5055 if (NewFD->getDeclName() != Name) { 5056 Diag(NewFD->getLocation(), diag::err_destructor_name); 5057 return NewFD->setInvalidDecl(); 5058 } 5059 } 5060 } else if (CXXConversionDecl *Conversion 5061 = dyn_cast<CXXConversionDecl>(NewFD)) { 5062 ActOnConversionDeclarator(Conversion); 5063 } 5064 5065 // Find any virtual functions that this function overrides. 5066 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 5067 if (!Method->isFunctionTemplateSpecialization() && 5068 !Method->getDescribedFunctionTemplate()) { 5069 if (AddOverriddenMethods(Method->getParent(), Method)) { 5070 // If the function was marked as "static", we have a problem. 5071 if (NewFD->getStorageClass() == SC_Static) { 5072 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 5073 << NewFD->getDeclName(); 5074 for (CXXMethodDecl::method_iterator 5075 Overridden = Method->begin_overridden_methods(), 5076 OverriddenEnd = Method->end_overridden_methods(); 5077 Overridden != OverriddenEnd; 5078 ++Overridden) { 5079 Diag((*Overridden)->getLocation(), 5080 diag::note_overridden_virtual_function); 5081 } 5082 } 5083 } 5084 } 5085 } 5086 5087 // Extra checking for C++ overloaded operators (C++ [over.oper]). 5088 if (NewFD->isOverloadedOperator() && 5089 CheckOverloadedOperatorDeclaration(NewFD)) 5090 return NewFD->setInvalidDecl(); 5091 5092 // Extra checking for C++0x literal operators (C++0x [over.literal]). 5093 if (NewFD->getLiteralIdentifier() && 5094 CheckLiteralOperatorDeclaration(NewFD)) 5095 return NewFD->setInvalidDecl(); 5096 5097 // In C++, check default arguments now that we have merged decls. Unless 5098 // the lexical context is the class, because in this case this is done 5099 // during delayed parsing anyway. 5100 if (!CurContext->isRecord()) 5101 CheckCXXDefaultArguments(NewFD); 5102 5103 // If this function declares a builtin function, check the type of this 5104 // declaration against the expected type for the builtin. 5105 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 5106 ASTContext::GetBuiltinTypeError Error; 5107 QualType T = Context.GetBuiltinType(BuiltinID, Error); 5108 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 5109 // The type of this function differs from the type of the builtin, 5110 // so forget about the builtin entirely. 5111 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 5112 } 5113 } 5114 } 5115} 5116 5117void Sema::CheckMain(FunctionDecl* FD) { 5118 // C++ [basic.start.main]p3: A program that declares main to be inline 5119 // or static is ill-formed. 5120 // C99 6.7.4p4: In a hosted environment, the inline function specifier 5121 // shall not appear in a declaration of main. 5122 // static main is not an error under C99, but we should warn about it. 5123 bool isInline = FD->isInlineSpecified(); 5124 bool isStatic = FD->getStorageClass() == SC_Static; 5125 if (isInline || isStatic) { 5126 unsigned diagID = diag::warn_unusual_main_decl; 5127 if (isInline || getLangOptions().CPlusPlus) 5128 diagID = diag::err_unusual_main_decl; 5129 5130 int which = isStatic + (isInline << 1) - 1; 5131 Diag(FD->getLocation(), diagID) << which; 5132 } 5133 5134 QualType T = FD->getType(); 5135 assert(T->isFunctionType() && "function decl is not of function type"); 5136 const FunctionType* FT = T->getAs<FunctionType>(); 5137 5138 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 5139 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 5140 FD->setInvalidDecl(true); 5141 } 5142 5143 // Treat protoless main() as nullary. 5144 if (isa<FunctionNoProtoType>(FT)) return; 5145 5146 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 5147 unsigned nparams = FTP->getNumArgs(); 5148 assert(FD->getNumParams() == nparams); 5149 5150 bool HasExtraParameters = (nparams > 3); 5151 5152 // Darwin passes an undocumented fourth argument of type char**. If 5153 // other platforms start sprouting these, the logic below will start 5154 // getting shifty. 5155 if (nparams == 4 && Context.Target.getTriple().isOSDarwin()) 5156 HasExtraParameters = false; 5157 5158 if (HasExtraParameters) { 5159 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 5160 FD->setInvalidDecl(true); 5161 nparams = 3; 5162 } 5163 5164 // FIXME: a lot of the following diagnostics would be improved 5165 // if we had some location information about types. 5166 5167 QualType CharPP = 5168 Context.getPointerType(Context.getPointerType(Context.CharTy)); 5169 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 5170 5171 for (unsigned i = 0; i < nparams; ++i) { 5172 QualType AT = FTP->getArgType(i); 5173 5174 bool mismatch = true; 5175 5176 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 5177 mismatch = false; 5178 else if (Expected[i] == CharPP) { 5179 // As an extension, the following forms are okay: 5180 // char const ** 5181 // char const * const * 5182 // char * const * 5183 5184 QualifierCollector qs; 5185 const PointerType* PT; 5186 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 5187 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 5188 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 5189 qs.removeConst(); 5190 mismatch = !qs.empty(); 5191 } 5192 } 5193 5194 if (mismatch) { 5195 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 5196 // TODO: suggest replacing given type with expected type 5197 FD->setInvalidDecl(true); 5198 } 5199 } 5200 5201 if (nparams == 1 && !FD->isInvalidDecl()) { 5202 Diag(FD->getLocation(), diag::warn_main_one_arg); 5203 } 5204 5205 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 5206 Diag(FD->getLocation(), diag::err_main_template_decl); 5207 FD->setInvalidDecl(); 5208 } 5209} 5210 5211bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 5212 // FIXME: Need strict checking. In C89, we need to check for 5213 // any assignment, increment, decrement, function-calls, or 5214 // commas outside of a sizeof. In C99, it's the same list, 5215 // except that the aforementioned are allowed in unevaluated 5216 // expressions. Everything else falls under the 5217 // "may accept other forms of constant expressions" exception. 5218 // (We never end up here for C++, so the constant expression 5219 // rules there don't matter.) 5220 if (Init->isConstantInitializer(Context, false)) 5221 return false; 5222 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 5223 << Init->getSourceRange(); 5224 return true; 5225} 5226 5227namespace { 5228 // Visits an initialization expression to see if OrigDecl is evaluated in 5229 // its own initialization and throws a warning if it does. 5230 class SelfReferenceChecker 5231 : public EvaluatedExprVisitor<SelfReferenceChecker> { 5232 Sema &S; 5233 Decl *OrigDecl; 5234 5235 public: 5236 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 5237 5238 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 5239 S(S), OrigDecl(OrigDecl) { } 5240 5241 void VisitExpr(Expr *E) { 5242 if (isa<ObjCMessageExpr>(*E)) return; 5243 Inherited::VisitExpr(E); 5244 } 5245 5246 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 5247 CheckForSelfReference(E); 5248 Inherited::VisitImplicitCastExpr(E); 5249 } 5250 5251 void CheckForSelfReference(ImplicitCastExpr *E) { 5252 if (E->getCastKind() != CK_LValueToRValue) return; 5253 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts(); 5254 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr); 5255 if (!DRE) return; 5256 Decl* ReferenceDecl = DRE->getDecl(); 5257 if (OrigDecl != ReferenceDecl) return; 5258 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 5259 Sema::NotForRedeclaration); 5260 S.DiagRuntimeBehavior(SubExpr->getLocStart(), SubExpr, 5261 S.PDiag(diag::warn_uninit_self_reference_in_init) 5262 << Result.getLookupName() 5263 << OrigDecl->getLocation() 5264 << SubExpr->getSourceRange()); 5265 } 5266 }; 5267} 5268 5269/// AddInitializerToDecl - Adds the initializer Init to the 5270/// declaration dcl. If DirectInit is true, this is C++ direct 5271/// initialization rather than copy initialization. 5272void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 5273 bool DirectInit, bool TypeMayContainAuto) { 5274 // If there is no declaration, there was an error parsing it. Just ignore 5275 // the initializer. 5276 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 5277 return; 5278 5279 // Check for self-references within variable initializers. 5280 if (VarDecl *vd = dyn_cast<VarDecl>(RealDecl)) { 5281 // Variables declared within a function/method body are handled 5282 // by a dataflow analysis. 5283 if (!vd->hasLocalStorage() && !vd->isStaticLocal()) 5284 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init); 5285 } 5286 else { 5287 SelfReferenceChecker(*this, RealDecl).VisitExpr(Init); 5288 } 5289 5290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 5291 // With declarators parsed the way they are, the parser cannot 5292 // distinguish between a normal initializer and a pure-specifier. 5293 // Thus this grotesque test. 5294 IntegerLiteral *IL; 5295 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 5296 Context.getCanonicalType(IL->getType()) == Context.IntTy) 5297 CheckPureMethod(Method, Init->getSourceRange()); 5298 else { 5299 Diag(Method->getLocation(), diag::err_member_function_initialization) 5300 << Method->getDeclName() << Init->getSourceRange(); 5301 Method->setInvalidDecl(); 5302 } 5303 return; 5304 } 5305 5306 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 5307 if (!VDecl) { 5308 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 5309 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 5310 RealDecl->setInvalidDecl(); 5311 return; 5312 } 5313 5314 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 5315 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 5316 TypeSourceInfo *DeducedType = 0; 5317 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 5318 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 5319 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 5320 << Init->getSourceRange(); 5321 if (!DeducedType) { 5322 RealDecl->setInvalidDecl(); 5323 return; 5324 } 5325 VDecl->setTypeSourceInfo(DeducedType); 5326 VDecl->setType(DeducedType->getType()); 5327 5328 // In ARC, infer lifetime. 5329 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 5330 VDecl->setInvalidDecl(); 5331 5332 // If this is a redeclaration, check that the type we just deduced matches 5333 // the previously declared type. 5334 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 5335 MergeVarDeclTypes(VDecl, Old); 5336 } 5337 5338 5339 // A definition must end up with a complete type, which means it must be 5340 // complete with the restriction that an array type might be completed by the 5341 // initializer; note that later code assumes this restriction. 5342 QualType BaseDeclType = VDecl->getType(); 5343 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 5344 BaseDeclType = Array->getElementType(); 5345 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 5346 diag::err_typecheck_decl_incomplete_type)) { 5347 RealDecl->setInvalidDecl(); 5348 return; 5349 } 5350 5351 // The variable can not have an abstract class type. 5352 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 5353 diag::err_abstract_type_in_decl, 5354 AbstractVariableType)) 5355 VDecl->setInvalidDecl(); 5356 5357 const VarDecl *Def; 5358 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 5359 Diag(VDecl->getLocation(), diag::err_redefinition) 5360 << VDecl->getDeclName(); 5361 Diag(Def->getLocation(), diag::note_previous_definition); 5362 VDecl->setInvalidDecl(); 5363 return; 5364 } 5365 5366 const VarDecl* PrevInit = 0; 5367 if (getLangOptions().CPlusPlus) { 5368 // C++ [class.static.data]p4 5369 // If a static data member is of const integral or const 5370 // enumeration type, its declaration in the class definition can 5371 // specify a constant-initializer which shall be an integral 5372 // constant expression (5.19). In that case, the member can appear 5373 // in integral constant expressions. The member shall still be 5374 // defined in a namespace scope if it is used in the program and the 5375 // namespace scope definition shall not contain an initializer. 5376 // 5377 // We already performed a redefinition check above, but for static 5378 // data members we also need to check whether there was an in-class 5379 // declaration with an initializer. 5380 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 5381 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 5382 Diag(PrevInit->getLocation(), diag::note_previous_definition); 5383 return; 5384 } 5385 5386 if (VDecl->hasLocalStorage()) 5387 getCurFunction()->setHasBranchProtectedScope(); 5388 5389 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 5390 VDecl->setInvalidDecl(); 5391 return; 5392 } 5393 } 5394 5395 // Capture the variable that is being initialized and the style of 5396 // initialization. 5397 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 5398 5399 // FIXME: Poor source location information. 5400 InitializationKind Kind 5401 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 5402 Init->getLocStart(), 5403 Init->getLocEnd()) 5404 : InitializationKind::CreateCopy(VDecl->getLocation(), 5405 Init->getLocStart()); 5406 5407 // Get the decls type and save a reference for later, since 5408 // CheckInitializerTypes may change it. 5409 QualType DclT = VDecl->getType(), SavT = DclT; 5410 if (VDecl->isLocalVarDecl()) { 5411 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 5412 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 5413 VDecl->setInvalidDecl(); 5414 } else if (!VDecl->isInvalidDecl()) { 5415 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5416 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5417 MultiExprArg(*this, &Init, 1), 5418 &DclT); 5419 if (Result.isInvalid()) { 5420 VDecl->setInvalidDecl(); 5421 return; 5422 } 5423 5424 Init = Result.takeAs<Expr>(); 5425 5426 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 5427 // Don't check invalid declarations to avoid emitting useless diagnostics. 5428 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 5429 if (VDecl->getStorageClass() == SC_Static) // C99 6.7.8p4. 5430 CheckForConstantInitializer(Init, DclT); 5431 } 5432 } 5433 } else if (VDecl->isStaticDataMember() && 5434 VDecl->getLexicalDeclContext()->isRecord()) { 5435 // This is an in-class initialization for a static data member, e.g., 5436 // 5437 // struct S { 5438 // static const int value = 17; 5439 // }; 5440 5441 // Try to perform the initialization regardless. 5442 if (!VDecl->isInvalidDecl()) { 5443 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5444 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5445 MultiExprArg(*this, &Init, 1), 5446 &DclT); 5447 if (Result.isInvalid()) { 5448 VDecl->setInvalidDecl(); 5449 return; 5450 } 5451 5452 Init = Result.takeAs<Expr>(); 5453 } 5454 5455 // C++ [class.mem]p4: 5456 // A member-declarator can contain a constant-initializer only 5457 // if it declares a static member (9.4) of const integral or 5458 // const enumeration type, see 9.4.2. 5459 QualType T = VDecl->getType(); 5460 5461 // Do nothing on dependent types. 5462 if (T->isDependentType()) { 5463 5464 // Require constness. 5465 } else if (!T.isConstQualified()) { 5466 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 5467 << Init->getSourceRange(); 5468 VDecl->setInvalidDecl(); 5469 5470 // We allow integer constant expressions in all cases. 5471 } else if (T->isIntegralOrEnumerationType()) { 5472 // Check whether the expression is a constant expression. 5473 SourceLocation Loc; 5474 if (Init->isValueDependent()) 5475 ; // Nothing to check. 5476 else if (Init->isIntegerConstantExpr(Context, &Loc)) 5477 ; // Ok, it's an ICE! 5478 else if (Init->isEvaluatable(Context)) { 5479 // If we can constant fold the initializer through heroics, accept it, 5480 // but report this as a use of an extension for -pedantic. 5481 Diag(Loc, diag::ext_in_class_initializer_non_constant) 5482 << Init->getSourceRange(); 5483 } else { 5484 // Otherwise, this is some crazy unknown case. Report the issue at the 5485 // location provided by the isIntegerConstantExpr failed check. 5486 Diag(Loc, diag::err_in_class_initializer_non_constant) 5487 << Init->getSourceRange(); 5488 VDecl->setInvalidDecl(); 5489 } 5490 5491 // We allow floating-point constants as an extension in C++03, and 5492 // C++0x has far more complicated rules that we don't really 5493 // implement fully. 5494 } else { 5495 bool Allowed = false; 5496 if (getLangOptions().CPlusPlus0x) { 5497 Allowed = T->isLiteralType(); 5498 } else if (T->isFloatingType()) { // also permits complex, which is ok 5499 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 5500 << T << Init->getSourceRange(); 5501 Allowed = true; 5502 } 5503 5504 if (!Allowed) { 5505 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 5506 << T << Init->getSourceRange(); 5507 VDecl->setInvalidDecl(); 5508 5509 // TODO: there are probably expressions that pass here that shouldn't. 5510 } else if (!Init->isValueDependent() && 5511 !Init->isConstantInitializer(Context, false)) { 5512 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 5513 << Init->getSourceRange(); 5514 VDecl->setInvalidDecl(); 5515 } 5516 } 5517 } else if (VDecl->isFileVarDecl()) { 5518 if (VDecl->getStorageClassAsWritten() == SC_Extern && 5519 (!getLangOptions().CPlusPlus || 5520 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 5521 Diag(VDecl->getLocation(), diag::warn_extern_init); 5522 if (!VDecl->isInvalidDecl()) { 5523 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 5524 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5525 MultiExprArg(*this, &Init, 1), 5526 &DclT); 5527 if (Result.isInvalid()) { 5528 VDecl->setInvalidDecl(); 5529 return; 5530 } 5531 5532 Init = Result.takeAs<Expr>(); 5533 } 5534 5535 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 5536 // Don't check invalid declarations to avoid emitting useless diagnostics. 5537 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 5538 // C99 6.7.8p4. All file scoped initializers need to be constant. 5539 CheckForConstantInitializer(Init, DclT); 5540 } 5541 } 5542 // If the type changed, it means we had an incomplete type that was 5543 // completed by the initializer. For example: 5544 // int ary[] = { 1, 3, 5 }; 5545 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 5546 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 5547 VDecl->setType(DclT); 5548 Init->setType(DclT); 5549 } 5550 5551 5552 // If this variable is a local declaration with record type, make sure it 5553 // doesn't have a flexible member initialization. We only support this as a 5554 // global/static definition. 5555 if (VDecl->hasLocalStorage()) 5556 if (const RecordType *RT = VDecl->getType()->getAs<RecordType>()) 5557 if (RT->getDecl()->hasFlexibleArrayMember()) { 5558 // Check whether the initializer tries to initialize the flexible 5559 // array member itself to anything other than an empty initializer list. 5560 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 5561 unsigned Index = std::distance(RT->getDecl()->field_begin(), 5562 RT->getDecl()->field_end()) - 1; 5563 if (Index < ILE->getNumInits() && 5564 !(isa<InitListExpr>(ILE->getInit(Index)) && 5565 cast<InitListExpr>(ILE->getInit(Index))->getNumInits() == 0)) { 5566 Diag(VDecl->getLocation(), diag::err_nonstatic_flexible_variable); 5567 VDecl->setInvalidDecl(); 5568 } 5569 } 5570 } 5571 5572 // Check any implicit conversions within the expression. 5573 CheckImplicitConversions(Init, VDecl->getLocation()); 5574 5575 if (!VDecl->isInvalidDecl()) 5576 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 5577 5578 Init = MaybeCreateExprWithCleanups(Init); 5579 // Attach the initializer to the decl. 5580 VDecl->setInit(Init); 5581 5582 CheckCompleteVariableDeclaration(VDecl); 5583} 5584 5585/// ActOnInitializerError - Given that there was an error parsing an 5586/// initializer for the given declaration, try to return to some form 5587/// of sanity. 5588void Sema::ActOnInitializerError(Decl *D) { 5589 // Our main concern here is re-establishing invariants like "a 5590 // variable's type is either dependent or complete". 5591 if (!D || D->isInvalidDecl()) return; 5592 5593 VarDecl *VD = dyn_cast<VarDecl>(D); 5594 if (!VD) return; 5595 5596 // Auto types are meaningless if we can't make sense of the initializer. 5597 if (ParsingInitForAutoVars.count(D)) { 5598 D->setInvalidDecl(); 5599 return; 5600 } 5601 5602 QualType Ty = VD->getType(); 5603 if (Ty->isDependentType()) return; 5604 5605 // Require a complete type. 5606 if (RequireCompleteType(VD->getLocation(), 5607 Context.getBaseElementType(Ty), 5608 diag::err_typecheck_decl_incomplete_type)) { 5609 VD->setInvalidDecl(); 5610 return; 5611 } 5612 5613 // Require an abstract type. 5614 if (RequireNonAbstractType(VD->getLocation(), Ty, 5615 diag::err_abstract_type_in_decl, 5616 AbstractVariableType)) { 5617 VD->setInvalidDecl(); 5618 return; 5619 } 5620 5621 // Don't bother complaining about constructors or destructors, 5622 // though. 5623} 5624 5625void Sema::ActOnUninitializedDecl(Decl *RealDecl, 5626 bool TypeMayContainAuto) { 5627 // If there is no declaration, there was an error parsing it. Just ignore it. 5628 if (RealDecl == 0) 5629 return; 5630 5631 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 5632 QualType Type = Var->getType(); 5633 5634 // C++0x [dcl.spec.auto]p3 5635 if (TypeMayContainAuto && Type->getContainedAutoType()) { 5636 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 5637 << Var->getDeclName() << Type; 5638 Var->setInvalidDecl(); 5639 return; 5640 } 5641 5642 switch (Var->isThisDeclarationADefinition()) { 5643 case VarDecl::Definition: 5644 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 5645 break; 5646 5647 // We have an out-of-line definition of a static data member 5648 // that has an in-class initializer, so we type-check this like 5649 // a declaration. 5650 // 5651 // Fall through 5652 5653 case VarDecl::DeclarationOnly: 5654 // It's only a declaration. 5655 5656 // Block scope. C99 6.7p7: If an identifier for an object is 5657 // declared with no linkage (C99 6.2.2p6), the type for the 5658 // object shall be complete. 5659 if (!Type->isDependentType() && Var->isLocalVarDecl() && 5660 !Var->getLinkage() && !Var->isInvalidDecl() && 5661 RequireCompleteType(Var->getLocation(), Type, 5662 diag::err_typecheck_decl_incomplete_type)) 5663 Var->setInvalidDecl(); 5664 5665 // Make sure that the type is not abstract. 5666 if (!Type->isDependentType() && !Var->isInvalidDecl() && 5667 RequireNonAbstractType(Var->getLocation(), Type, 5668 diag::err_abstract_type_in_decl, 5669 AbstractVariableType)) 5670 Var->setInvalidDecl(); 5671 return; 5672 5673 case VarDecl::TentativeDefinition: 5674 // File scope. C99 6.9.2p2: A declaration of an identifier for an 5675 // object that has file scope without an initializer, and without a 5676 // storage-class specifier or with the storage-class specifier "static", 5677 // constitutes a tentative definition. Note: A tentative definition with 5678 // external linkage is valid (C99 6.2.2p5). 5679 if (!Var->isInvalidDecl()) { 5680 if (const IncompleteArrayType *ArrayT 5681 = Context.getAsIncompleteArrayType(Type)) { 5682 if (RequireCompleteType(Var->getLocation(), 5683 ArrayT->getElementType(), 5684 diag::err_illegal_decl_array_incomplete_type)) 5685 Var->setInvalidDecl(); 5686 } else if (Var->getStorageClass() == SC_Static) { 5687 // C99 6.9.2p3: If the declaration of an identifier for an object is 5688 // a tentative definition and has internal linkage (C99 6.2.2p3), the 5689 // declared type shall not be an incomplete type. 5690 // NOTE: code such as the following 5691 // static struct s; 5692 // struct s { int a; }; 5693 // is accepted by gcc. Hence here we issue a warning instead of 5694 // an error and we do not invalidate the static declaration. 5695 // NOTE: to avoid multiple warnings, only check the first declaration. 5696 if (Var->getPreviousDeclaration() == 0) 5697 RequireCompleteType(Var->getLocation(), Type, 5698 diag::ext_typecheck_decl_incomplete_type); 5699 } 5700 } 5701 5702 // Record the tentative definition; we're done. 5703 if (!Var->isInvalidDecl()) 5704 TentativeDefinitions.push_back(Var); 5705 return; 5706 } 5707 5708 // Provide a specific diagnostic for uninitialized variable 5709 // definitions with incomplete array type. 5710 if (Type->isIncompleteArrayType()) { 5711 Diag(Var->getLocation(), 5712 diag::err_typecheck_incomplete_array_needs_initializer); 5713 Var->setInvalidDecl(); 5714 return; 5715 } 5716 5717 // Provide a specific diagnostic for uninitialized variable 5718 // definitions with reference type. 5719 if (Type->isReferenceType()) { 5720 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 5721 << Var->getDeclName() 5722 << SourceRange(Var->getLocation(), Var->getLocation()); 5723 Var->setInvalidDecl(); 5724 return; 5725 } 5726 5727 // Do not attempt to type-check the default initializer for a 5728 // variable with dependent type. 5729 if (Type->isDependentType()) 5730 return; 5731 5732 if (Var->isInvalidDecl()) 5733 return; 5734 5735 if (RequireCompleteType(Var->getLocation(), 5736 Context.getBaseElementType(Type), 5737 diag::err_typecheck_decl_incomplete_type)) { 5738 Var->setInvalidDecl(); 5739 return; 5740 } 5741 5742 // The variable can not have an abstract class type. 5743 if (RequireNonAbstractType(Var->getLocation(), Type, 5744 diag::err_abstract_type_in_decl, 5745 AbstractVariableType)) { 5746 Var->setInvalidDecl(); 5747 return; 5748 } 5749 5750 // Check for jumps past the implicit initializer. C++0x 5751 // clarifies that this applies to a "variable with automatic 5752 // storage duration", not a "local variable". 5753 // C++0x [stmt.dcl]p3 5754 // A program that jumps from a point where a variable with automatic 5755 // storage duration is not in scope to a point where it is in scope is 5756 // ill-formed unless the variable has scalar type, class type with a 5757 // trivial default constructor and a trivial destructor, a cv-qualified 5758 // version of one of these types, or an array of one of the preceding 5759 // types and is declared without an initializer. 5760 if (getLangOptions().CPlusPlus && Var->hasLocalStorage()) { 5761 if (const RecordType *Record 5762 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 5763 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 5764 if ((!getLangOptions().CPlusPlus0x && !CXXRecord->isPOD()) || 5765 (getLangOptions().CPlusPlus0x && 5766 (!CXXRecord->hasTrivialDefaultConstructor() || 5767 !CXXRecord->hasTrivialDestructor()))) 5768 getCurFunction()->setHasBranchProtectedScope(); 5769 } 5770 } 5771 5772 // C++03 [dcl.init]p9: 5773 // If no initializer is specified for an object, and the 5774 // object is of (possibly cv-qualified) non-POD class type (or 5775 // array thereof), the object shall be default-initialized; if 5776 // the object is of const-qualified type, the underlying class 5777 // type shall have a user-declared default 5778 // constructor. Otherwise, if no initializer is specified for 5779 // a non- static object, the object and its subobjects, if 5780 // any, have an indeterminate initial value); if the object 5781 // or any of its subobjects are of const-qualified type, the 5782 // program is ill-formed. 5783 // C++0x [dcl.init]p11: 5784 // If no initializer is specified for an object, the object is 5785 // default-initialized; [...]. 5786 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 5787 InitializationKind Kind 5788 = InitializationKind::CreateDefault(Var->getLocation()); 5789 5790 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 5791 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 5792 MultiExprArg(*this, 0, 0)); 5793 if (Init.isInvalid()) 5794 Var->setInvalidDecl(); 5795 else if (Init.get()) 5796 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 5797 5798 CheckCompleteVariableDeclaration(Var); 5799 } 5800} 5801 5802void Sema::ActOnCXXForRangeDecl(Decl *D) { 5803 VarDecl *VD = dyn_cast<VarDecl>(D); 5804 if (!VD) { 5805 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 5806 D->setInvalidDecl(); 5807 return; 5808 } 5809 5810 VD->setCXXForRangeDecl(true); 5811 5812 // for-range-declaration cannot be given a storage class specifier. 5813 int Error = -1; 5814 switch (VD->getStorageClassAsWritten()) { 5815 case SC_None: 5816 break; 5817 case SC_Extern: 5818 Error = 0; 5819 break; 5820 case SC_Static: 5821 Error = 1; 5822 break; 5823 case SC_PrivateExtern: 5824 Error = 2; 5825 break; 5826 case SC_Auto: 5827 Error = 3; 5828 break; 5829 case SC_Register: 5830 Error = 4; 5831 break; 5832 } 5833 // FIXME: constexpr isn't allowed here. 5834 //if (DS.isConstexprSpecified()) 5835 // Error = 5; 5836 if (Error != -1) { 5837 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 5838 << VD->getDeclName() << Error; 5839 D->setInvalidDecl(); 5840 } 5841} 5842 5843void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 5844 if (var->isInvalidDecl()) return; 5845 5846 // In ARC, don't allow jumps past the implicit initialization of a 5847 // local retaining variable. 5848 if (getLangOptions().ObjCAutoRefCount && 5849 var->hasLocalStorage()) { 5850 switch (var->getType().getObjCLifetime()) { 5851 case Qualifiers::OCL_None: 5852 case Qualifiers::OCL_ExplicitNone: 5853 case Qualifiers::OCL_Autoreleasing: 5854 break; 5855 5856 case Qualifiers::OCL_Weak: 5857 case Qualifiers::OCL_Strong: 5858 getCurFunction()->setHasBranchProtectedScope(); 5859 break; 5860 } 5861 } 5862 5863 // All the following checks are C++ only. 5864 if (!getLangOptions().CPlusPlus) return; 5865 5866 QualType baseType = Context.getBaseElementType(var->getType()); 5867 if (baseType->isDependentType()) return; 5868 5869 // __block variables might require us to capture a copy-initializer. 5870 if (var->hasAttr<BlocksAttr>()) { 5871 // It's currently invalid to ever have a __block variable with an 5872 // array type; should we diagnose that here? 5873 5874 // Regardless, we don't want to ignore array nesting when 5875 // constructing this copy. 5876 QualType type = var->getType(); 5877 5878 if (type->isStructureOrClassType()) { 5879 SourceLocation poi = var->getLocation(); 5880 Expr *varRef = new (Context) DeclRefExpr(var, type, VK_LValue, poi); 5881 ExprResult result = 5882 PerformCopyInitialization( 5883 InitializedEntity::InitializeBlock(poi, type, false), 5884 poi, Owned(varRef)); 5885 if (!result.isInvalid()) { 5886 result = MaybeCreateExprWithCleanups(result); 5887 Expr *init = result.takeAs<Expr>(); 5888 Context.setBlockVarCopyInits(var, init); 5889 } 5890 } 5891 } 5892 5893 // Check for global constructors. 5894 if (!var->getDeclContext()->isDependentContext() && 5895 var->hasGlobalStorage() && 5896 !var->isStaticLocal() && 5897 var->getInit() && 5898 !var->getInit()->isConstantInitializer(Context, 5899 baseType->isReferenceType())) 5900 Diag(var->getLocation(), diag::warn_global_constructor) 5901 << var->getInit()->getSourceRange(); 5902 5903 // Require the destructor. 5904 if (const RecordType *recordType = baseType->getAs<RecordType>()) 5905 FinalizeVarWithDestructor(var, recordType); 5906} 5907 5908/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 5909/// any semantic actions necessary after any initializer has been attached. 5910void 5911Sema::FinalizeDeclaration(Decl *ThisDecl) { 5912 // Note that we are no longer parsing the initializer for this declaration. 5913 ParsingInitForAutoVars.erase(ThisDecl); 5914} 5915 5916Sema::DeclGroupPtrTy 5917Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 5918 Decl **Group, unsigned NumDecls) { 5919 llvm::SmallVector<Decl*, 8> Decls; 5920 5921 if (DS.isTypeSpecOwned()) 5922 Decls.push_back(DS.getRepAsDecl()); 5923 5924 for (unsigned i = 0; i != NumDecls; ++i) 5925 if (Decl *D = Group[i]) 5926 Decls.push_back(D); 5927 5928 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 5929 DS.getTypeSpecType() == DeclSpec::TST_auto); 5930} 5931 5932/// BuildDeclaratorGroup - convert a list of declarations into a declaration 5933/// group, performing any necessary semantic checking. 5934Sema::DeclGroupPtrTy 5935Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 5936 bool TypeMayContainAuto) { 5937 // C++0x [dcl.spec.auto]p7: 5938 // If the type deduced for the template parameter U is not the same in each 5939 // deduction, the program is ill-formed. 5940 // FIXME: When initializer-list support is added, a distinction is needed 5941 // between the deduced type U and the deduced type which 'auto' stands for. 5942 // auto a = 0, b = { 1, 2, 3 }; 5943 // is legal because the deduced type U is 'int' in both cases. 5944 if (TypeMayContainAuto && NumDecls > 1) { 5945 QualType Deduced; 5946 CanQualType DeducedCanon; 5947 VarDecl *DeducedDecl = 0; 5948 for (unsigned i = 0; i != NumDecls; ++i) { 5949 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 5950 AutoType *AT = D->getType()->getContainedAutoType(); 5951 // Don't reissue diagnostics when instantiating a template. 5952 if (AT && D->isInvalidDecl()) 5953 break; 5954 if (AT && AT->isDeduced()) { 5955 QualType U = AT->getDeducedType(); 5956 CanQualType UCanon = Context.getCanonicalType(U); 5957 if (Deduced.isNull()) { 5958 Deduced = U; 5959 DeducedCanon = UCanon; 5960 DeducedDecl = D; 5961 } else if (DeducedCanon != UCanon) { 5962 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 5963 diag::err_auto_different_deductions) 5964 << Deduced << DeducedDecl->getDeclName() 5965 << U << D->getDeclName() 5966 << DeducedDecl->getInit()->getSourceRange() 5967 << D->getInit()->getSourceRange(); 5968 D->setInvalidDecl(); 5969 break; 5970 } 5971 } 5972 } 5973 } 5974 } 5975 5976 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 5977} 5978 5979 5980/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 5981/// to introduce parameters into function prototype scope. 5982Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 5983 const DeclSpec &DS = D.getDeclSpec(); 5984 5985 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 5986 VarDecl::StorageClass StorageClass = SC_None; 5987 VarDecl::StorageClass StorageClassAsWritten = SC_None; 5988 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 5989 StorageClass = SC_Register; 5990 StorageClassAsWritten = SC_Register; 5991 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 5992 Diag(DS.getStorageClassSpecLoc(), 5993 diag::err_invalid_storage_class_in_func_decl); 5994 D.getMutableDeclSpec().ClearStorageClassSpecs(); 5995 } 5996 5997 if (D.getDeclSpec().isThreadSpecified()) 5998 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5999 6000 DiagnoseFunctionSpecifiers(D); 6001 6002 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6003 QualType parmDeclType = TInfo->getType(); 6004 6005 if (getLangOptions().CPlusPlus) { 6006 // Check that there are no default arguments inside the type of this 6007 // parameter. 6008 CheckExtraCXXDefaultArguments(D); 6009 6010 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 6011 if (D.getCXXScopeSpec().isSet()) { 6012 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 6013 << D.getCXXScopeSpec().getRange(); 6014 D.getCXXScopeSpec().clear(); 6015 } 6016 } 6017 6018 // Ensure we have a valid name 6019 IdentifierInfo *II = 0; 6020 if (D.hasName()) { 6021 II = D.getIdentifier(); 6022 if (!II) { 6023 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 6024 << GetNameForDeclarator(D).getName().getAsString(); 6025 D.setInvalidType(true); 6026 } 6027 } 6028 6029 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 6030 if (II) { 6031 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 6032 ForRedeclaration); 6033 LookupName(R, S); 6034 if (R.isSingleResult()) { 6035 NamedDecl *PrevDecl = R.getFoundDecl(); 6036 if (PrevDecl->isTemplateParameter()) { 6037 // Maybe we will complain about the shadowed template parameter. 6038 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6039 // Just pretend that we didn't see the previous declaration. 6040 PrevDecl = 0; 6041 } else if (S->isDeclScope(PrevDecl)) { 6042 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 6043 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 6044 6045 // Recover by removing the name 6046 II = 0; 6047 D.SetIdentifier(0, D.getIdentifierLoc()); 6048 D.setInvalidType(true); 6049 } 6050 } 6051 } 6052 6053 // Temporarily put parameter variables in the translation unit, not 6054 // the enclosing context. This prevents them from accidentally 6055 // looking like class members in C++. 6056 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 6057 D.getSourceRange().getBegin(), 6058 D.getIdentifierLoc(), II, 6059 parmDeclType, TInfo, 6060 StorageClass, StorageClassAsWritten); 6061 6062 if (D.isInvalidType()) 6063 New->setInvalidDecl(); 6064 6065 assert(S->isFunctionPrototypeScope()); 6066 assert(S->getFunctionPrototypeDepth() >= 1); 6067 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 6068 S->getNextFunctionPrototypeIndex()); 6069 6070 // Add the parameter declaration into this scope. 6071 S->AddDecl(New); 6072 if (II) 6073 IdResolver.AddDecl(New); 6074 6075 ProcessDeclAttributes(S, New, D); 6076 6077 if (New->hasAttr<BlocksAttr>()) { 6078 Diag(New->getLocation(), diag::err_block_on_nonlocal); 6079 } 6080 return New; 6081} 6082 6083/// \brief Synthesizes a variable for a parameter arising from a 6084/// typedef. 6085ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 6086 SourceLocation Loc, 6087 QualType T) { 6088 /* FIXME: setting StartLoc == Loc. 6089 Would it be worth to modify callers so as to provide proper source 6090 location for the unnamed parameters, embedding the parameter's type? */ 6091 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 6092 T, Context.getTrivialTypeSourceInfo(T, Loc), 6093 SC_None, SC_None, 0); 6094 Param->setImplicit(); 6095 return Param; 6096} 6097 6098void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 6099 ParmVarDecl * const *ParamEnd) { 6100 // Don't diagnose unused-parameter errors in template instantiations; we 6101 // will already have done so in the template itself. 6102 if (!ActiveTemplateInstantiations.empty()) 6103 return; 6104 6105 for (; Param != ParamEnd; ++Param) { 6106 if (!(*Param)->isUsed() && (*Param)->getDeclName() && 6107 !(*Param)->hasAttr<UnusedAttr>()) { 6108 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 6109 << (*Param)->getDeclName(); 6110 } 6111 } 6112} 6113 6114void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 6115 ParmVarDecl * const *ParamEnd, 6116 QualType ReturnTy, 6117 NamedDecl *D) { 6118 if (LangOpts.NumLargeByValueCopy == 0) // No check. 6119 return; 6120 6121 // Warn if the return value is pass-by-value and larger than the specified 6122 // threshold. 6123 if (ReturnTy.isPODType(Context)) { 6124 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 6125 if (Size > LangOpts.NumLargeByValueCopy) 6126 Diag(D->getLocation(), diag::warn_return_value_size) 6127 << D->getDeclName() << Size; 6128 } 6129 6130 // Warn if any parameter is pass-by-value and larger than the specified 6131 // threshold. 6132 for (; Param != ParamEnd; ++Param) { 6133 QualType T = (*Param)->getType(); 6134 if (!T.isPODType(Context)) 6135 continue; 6136 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 6137 if (Size > LangOpts.NumLargeByValueCopy) 6138 Diag((*Param)->getLocation(), diag::warn_parameter_size) 6139 << (*Param)->getDeclName() << Size; 6140 } 6141} 6142 6143ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 6144 SourceLocation NameLoc, IdentifierInfo *Name, 6145 QualType T, TypeSourceInfo *TSInfo, 6146 VarDecl::StorageClass StorageClass, 6147 VarDecl::StorageClass StorageClassAsWritten) { 6148 // In ARC, infer a lifetime qualifier for appropriate parameter types. 6149 if (getLangOptions().ObjCAutoRefCount && 6150 T.getObjCLifetime() == Qualifiers::OCL_None && 6151 T->isObjCLifetimeType()) { 6152 6153 Qualifiers::ObjCLifetime lifetime; 6154 6155 // Special cases for arrays: 6156 // - if it's const, use __unsafe_unretained 6157 // - otherwise, it's an error 6158 if (T->isArrayType()) { 6159 if (!T.isConstQualified()) { 6160 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 6161 << TSInfo->getTypeLoc().getSourceRange(); 6162 } 6163 lifetime = Qualifiers::OCL_ExplicitNone; 6164 } else { 6165 lifetime = T->getObjCARCImplicitLifetime(); 6166 } 6167 T = Context.getLifetimeQualifiedType(T, lifetime); 6168 } 6169 6170 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 6171 Context.getAdjustedParameterType(T), 6172 TSInfo, 6173 StorageClass, StorageClassAsWritten, 6174 0); 6175 6176 // Parameters can not be abstract class types. 6177 // For record types, this is done by the AbstractClassUsageDiagnoser once 6178 // the class has been completely parsed. 6179 if (!CurContext->isRecord() && 6180 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 6181 AbstractParamType)) 6182 New->setInvalidDecl(); 6183 6184 // Parameter declarators cannot be interface types. All ObjC objects are 6185 // passed by reference. 6186 if (T->isObjCObjectType()) { 6187 Diag(NameLoc, 6188 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 6189 New->setInvalidDecl(); 6190 } 6191 6192 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 6193 // duration shall not be qualified by an address-space qualifier." 6194 // Since all parameters have automatic store duration, they can not have 6195 // an address space. 6196 if (T.getAddressSpace() != 0) { 6197 Diag(NameLoc, diag::err_arg_with_address_space); 6198 New->setInvalidDecl(); 6199 } 6200 6201 return New; 6202} 6203 6204void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 6205 SourceLocation LocAfterDecls) { 6206 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6207 6208 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 6209 // for a K&R function. 6210 if (!FTI.hasPrototype) { 6211 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 6212 --i; 6213 if (FTI.ArgInfo[i].Param == 0) { 6214 llvm::SmallString<256> Code; 6215 llvm::raw_svector_ostream(Code) << " int " 6216 << FTI.ArgInfo[i].Ident->getName() 6217 << ";\n"; 6218 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 6219 << FTI.ArgInfo[i].Ident 6220 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 6221 6222 // Implicitly declare the argument as type 'int' for lack of a better 6223 // type. 6224 AttributeFactory attrs; 6225 DeclSpec DS(attrs); 6226 const char* PrevSpec; // unused 6227 unsigned DiagID; // unused 6228 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 6229 PrevSpec, DiagID); 6230 Declarator ParamD(DS, Declarator::KNRTypeListContext); 6231 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 6232 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 6233 } 6234 } 6235 } 6236} 6237 6238Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 6239 Declarator &D) { 6240 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 6241 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 6242 Scope *ParentScope = FnBodyScope->getParent(); 6243 6244 Decl *DP = HandleDeclarator(ParentScope, D, 6245 MultiTemplateParamsArg(*this), 6246 /*IsFunctionDefinition=*/true); 6247 return ActOnStartOfFunctionDef(FnBodyScope, DP); 6248} 6249 6250static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 6251 // Don't warn about invalid declarations. 6252 if (FD->isInvalidDecl()) 6253 return false; 6254 6255 // Or declarations that aren't global. 6256 if (!FD->isGlobal()) 6257 return false; 6258 6259 // Don't warn about C++ member functions. 6260 if (isa<CXXMethodDecl>(FD)) 6261 return false; 6262 6263 // Don't warn about 'main'. 6264 if (FD->isMain()) 6265 return false; 6266 6267 // Don't warn about inline functions. 6268 if (FD->isInlined()) 6269 return false; 6270 6271 // Don't warn about function templates. 6272 if (FD->getDescribedFunctionTemplate()) 6273 return false; 6274 6275 // Don't warn about function template specializations. 6276 if (FD->isFunctionTemplateSpecialization()) 6277 return false; 6278 6279 bool MissingPrototype = true; 6280 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 6281 Prev; Prev = Prev->getPreviousDeclaration()) { 6282 // Ignore any declarations that occur in function or method 6283 // scope, because they aren't visible from the header. 6284 if (Prev->getDeclContext()->isFunctionOrMethod()) 6285 continue; 6286 6287 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 6288 break; 6289 } 6290 6291 return MissingPrototype; 6292} 6293 6294void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 6295 // Don't complain if we're in GNU89 mode and the previous definition 6296 // was an extern inline function. 6297 const FunctionDecl *Definition; 6298 if (FD->isDefined(Definition) && 6299 !canRedefineFunction(Definition, getLangOptions())) { 6300 if (getLangOptions().GNUMode && Definition->isInlineSpecified() && 6301 Definition->getStorageClass() == SC_Extern) 6302 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 6303 << FD->getDeclName() << getLangOptions().CPlusPlus; 6304 else 6305 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 6306 Diag(Definition->getLocation(), diag::note_previous_definition); 6307 } 6308} 6309 6310Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 6311 // Clear the last template instantiation error context. 6312 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 6313 6314 if (!D) 6315 return D; 6316 FunctionDecl *FD = 0; 6317 6318 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 6319 FD = FunTmpl->getTemplatedDecl(); 6320 else 6321 FD = cast<FunctionDecl>(D); 6322 6323 // Enter a new function scope 6324 PushFunctionScope(); 6325 6326 // See if this is a redefinition. 6327 if (!FD->isLateTemplateParsed()) 6328 CheckForFunctionRedefinition(FD); 6329 6330 // Builtin functions cannot be defined. 6331 if (unsigned BuiltinID = FD->getBuiltinID()) { 6332 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 6333 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 6334 FD->setInvalidDecl(); 6335 } 6336 } 6337 6338 // The return type of a function definition must be complete 6339 // (C99 6.9.1p3, C++ [dcl.fct]p6). 6340 QualType ResultType = FD->getResultType(); 6341 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 6342 !FD->isInvalidDecl() && 6343 RequireCompleteType(FD->getLocation(), ResultType, 6344 diag::err_func_def_incomplete_result)) 6345 FD->setInvalidDecl(); 6346 6347 // GNU warning -Wmissing-prototypes: 6348 // Warn if a global function is defined without a previous 6349 // prototype declaration. This warning is issued even if the 6350 // definition itself provides a prototype. The aim is to detect 6351 // global functions that fail to be declared in header files. 6352 if (ShouldWarnAboutMissingPrototype(FD)) 6353 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 6354 6355 if (FnBodyScope) 6356 PushDeclContext(FnBodyScope, FD); 6357 6358 // Check the validity of our function parameters 6359 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 6360 /*CheckParameterNames=*/true); 6361 6362 // Introduce our parameters into the function scope 6363 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 6364 ParmVarDecl *Param = FD->getParamDecl(p); 6365 Param->setOwningFunction(FD); 6366 6367 // If this has an identifier, add it to the scope stack. 6368 if (Param->getIdentifier() && FnBodyScope) { 6369 CheckShadow(FnBodyScope, Param); 6370 6371 PushOnScopeChains(Param, FnBodyScope); 6372 } 6373 } 6374 6375 // Checking attributes of current function definition 6376 // dllimport attribute. 6377 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 6378 if (DA && (!FD->getAttr<DLLExportAttr>())) { 6379 // dllimport attribute cannot be directly applied to definition. 6380 // Microsoft accepts dllimport for functions defined within class scope. 6381 if (!DA->isInherited() && 6382 !(LangOpts.Microsoft && FD->getLexicalDeclContext()->isRecord())) { 6383 Diag(FD->getLocation(), 6384 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 6385 << "dllimport"; 6386 FD->setInvalidDecl(); 6387 return FD; 6388 } 6389 6390 // Visual C++ appears to not think this is an issue, so only issue 6391 // a warning when Microsoft extensions are disabled. 6392 if (!LangOpts.Microsoft) { 6393 // If a symbol previously declared dllimport is later defined, the 6394 // attribute is ignored in subsequent references, and a warning is 6395 // emitted. 6396 Diag(FD->getLocation(), 6397 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6398 << FD->getName() << "dllimport"; 6399 } 6400 } 6401 return FD; 6402} 6403 6404/// \brief Given the set of return statements within a function body, 6405/// compute the variables that are subject to the named return value 6406/// optimization. 6407/// 6408/// Each of the variables that is subject to the named return value 6409/// optimization will be marked as NRVO variables in the AST, and any 6410/// return statement that has a marked NRVO variable as its NRVO candidate can 6411/// use the named return value optimization. 6412/// 6413/// This function applies a very simplistic algorithm for NRVO: if every return 6414/// statement in the function has the same NRVO candidate, that candidate is 6415/// the NRVO variable. 6416/// 6417/// FIXME: Employ a smarter algorithm that accounts for multiple return 6418/// statements and the lifetimes of the NRVO candidates. We should be able to 6419/// find a maximal set of NRVO variables. 6420static void ComputeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 6421 ReturnStmt **Returns = Scope->Returns.data(); 6422 6423 const VarDecl *NRVOCandidate = 0; 6424 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 6425 if (!Returns[I]->getNRVOCandidate()) 6426 return; 6427 6428 if (!NRVOCandidate) 6429 NRVOCandidate = Returns[I]->getNRVOCandidate(); 6430 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 6431 return; 6432 } 6433 6434 if (NRVOCandidate) 6435 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 6436} 6437 6438Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 6439 return ActOnFinishFunctionBody(D, move(BodyArg), false); 6440} 6441 6442Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 6443 bool IsInstantiation) { 6444 FunctionDecl *FD = 0; 6445 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 6446 if (FunTmpl) 6447 FD = FunTmpl->getTemplatedDecl(); 6448 else 6449 FD = dyn_cast_or_null<FunctionDecl>(dcl); 6450 6451 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 6452 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 6453 6454 if (FD) { 6455 FD->setBody(Body); 6456 if (FD->isMain()) { 6457 // C and C++ allow for main to automagically return 0. 6458 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6459 FD->setHasImplicitReturnZero(true); 6460 WP.disableCheckFallThrough(); 6461 } else if (FD->hasAttr<NakedAttr>()) { 6462 // If the function is marked 'naked', don't complain about missing return 6463 // statements. 6464 WP.disableCheckFallThrough(); 6465 } 6466 6467 // MSVC permits the use of pure specifier (=0) on function definition, 6468 // defined at class scope, warn about this non standard construct. 6469 if (getLangOptions().Microsoft && FD->isPure()) 6470 Diag(FD->getLocation(), diag::warn_pure_function_definition); 6471 6472 if (!FD->isInvalidDecl()) { 6473 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 6474 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 6475 FD->getResultType(), FD); 6476 6477 // If this is a constructor, we need a vtable. 6478 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 6479 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 6480 6481 ComputeNRVO(Body, getCurFunction()); 6482 } 6483 6484 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 6485 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 6486 assert(MD == getCurMethodDecl() && "Method parsing confused"); 6487 MD->setBody(Body); 6488 if (Body) 6489 MD->setEndLoc(Body->getLocEnd()); 6490 if (!MD->isInvalidDecl()) { 6491 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 6492 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 6493 MD->getResultType(), MD); 6494 } 6495 } else { 6496 return 0; 6497 } 6498 6499 // Verify and clean out per-function state. 6500 if (Body) { 6501 // C++ constructors that have function-try-blocks can't have return 6502 // statements in the handlers of that block. (C++ [except.handle]p14) 6503 // Verify this. 6504 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 6505 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 6506 6507 // Verify that that gotos and switch cases don't jump into scopes illegally. 6508 // Verify that that gotos and switch cases don't jump into scopes illegally. 6509 if (getCurFunction()->NeedsScopeChecking() && 6510 !dcl->isInvalidDecl() && 6511 !hasAnyUnrecoverableErrorsInThisFunction()) 6512 DiagnoseInvalidJumps(Body); 6513 6514 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 6515 if (!Destructor->getParent()->isDependentType()) 6516 CheckDestructor(Destructor); 6517 6518 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 6519 Destructor->getParent()); 6520 } 6521 6522 // If any errors have occurred, clear out any temporaries that may have 6523 // been leftover. This ensures that these temporaries won't be picked up for 6524 // deletion in some later function. 6525 if (PP.getDiagnostics().hasErrorOccurred() || 6526 PP.getDiagnostics().getSuppressAllDiagnostics()) { 6527 ExprTemporaries.clear(); 6528 ExprNeedsCleanups = false; 6529 } else if (!isa<FunctionTemplateDecl>(dcl)) { 6530 // Since the body is valid, issue any analysis-based warnings that are 6531 // enabled. 6532 ActivePolicy = &WP; 6533 } 6534 6535 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 6536 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 6537 } 6538 6539 if (!IsInstantiation) 6540 PopDeclContext(); 6541 6542 PopFunctionOrBlockScope(ActivePolicy, dcl); 6543 6544 // If any errors have occurred, clear out any temporaries that may have 6545 // been leftover. This ensures that these temporaries won't be picked up for 6546 // deletion in some later function. 6547 if (getDiagnostics().hasErrorOccurred()) { 6548 ExprTemporaries.clear(); 6549 ExprNeedsCleanups = false; 6550 } 6551 6552 return dcl; 6553} 6554 6555/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 6556/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 6557NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 6558 IdentifierInfo &II, Scope *S) { 6559 // Before we produce a declaration for an implicitly defined 6560 // function, see whether there was a locally-scoped declaration of 6561 // this name as a function or variable. If so, use that 6562 // (non-visible) declaration, and complain about it. 6563 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6564 = LocallyScopedExternalDecls.find(&II); 6565 if (Pos != LocallyScopedExternalDecls.end()) { 6566 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 6567 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 6568 return Pos->second; 6569 } 6570 6571 // Extension in C99. Legal in C90, but warn about it. 6572 if (II.getName().startswith("__builtin_")) 6573 Diag(Loc, diag::warn_builtin_unknown) << &II; 6574 else if (getLangOptions().C99) 6575 Diag(Loc, diag::ext_implicit_function_decl) << &II; 6576 else 6577 Diag(Loc, diag::warn_implicit_function_decl) << &II; 6578 6579 // Set a Declarator for the implicit definition: int foo(); 6580 const char *Dummy; 6581 AttributeFactory attrFactory; 6582 DeclSpec DS(attrFactory); 6583 unsigned DiagID; 6584 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 6585 (void)Error; // Silence warning. 6586 assert(!Error && "Error setting up implicit decl!"); 6587 Declarator D(DS, Declarator::BlockContext); 6588 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 6589 0, 0, true, SourceLocation(), 6590 EST_None, SourceLocation(), 6591 0, 0, 0, 0, Loc, Loc, D), 6592 DS.getAttributes(), 6593 SourceLocation()); 6594 D.SetIdentifier(&II, Loc); 6595 6596 // Insert this function into translation-unit scope. 6597 6598 DeclContext *PrevDC = CurContext; 6599 CurContext = Context.getTranslationUnitDecl(); 6600 6601 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 6602 FD->setImplicit(); 6603 6604 CurContext = PrevDC; 6605 6606 AddKnownFunctionAttributes(FD); 6607 6608 return FD; 6609} 6610 6611/// \brief Adds any function attributes that we know a priori based on 6612/// the declaration of this function. 6613/// 6614/// These attributes can apply both to implicitly-declared builtins 6615/// (like __builtin___printf_chk) or to library-declared functions 6616/// like NSLog or printf. 6617/// 6618/// We need to check for duplicate attributes both here and where user-written 6619/// attributes are applied to declarations. 6620void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 6621 if (FD->isInvalidDecl()) 6622 return; 6623 6624 // If this is a built-in function, map its builtin attributes to 6625 // actual attributes. 6626 if (unsigned BuiltinID = FD->getBuiltinID()) { 6627 // Handle printf-formatting attributes. 6628 unsigned FormatIdx; 6629 bool HasVAListArg; 6630 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 6631 if (!FD->getAttr<FormatAttr>()) 6632 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6633 "printf", FormatIdx+1, 6634 HasVAListArg ? 0 : FormatIdx+2)); 6635 } 6636 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 6637 HasVAListArg)) { 6638 if (!FD->getAttr<FormatAttr>()) 6639 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6640 "scanf", FormatIdx+1, 6641 HasVAListArg ? 0 : FormatIdx+2)); 6642 } 6643 6644 // Mark const if we don't care about errno and that is the only 6645 // thing preventing the function from being const. This allows 6646 // IRgen to use LLVM intrinsics for such functions. 6647 if (!getLangOptions().MathErrno && 6648 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 6649 if (!FD->getAttr<ConstAttr>()) 6650 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 6651 } 6652 6653 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 6654 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 6655 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 6656 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 6657 } 6658 6659 IdentifierInfo *Name = FD->getIdentifier(); 6660 if (!Name) 6661 return; 6662 if ((!getLangOptions().CPlusPlus && 6663 FD->getDeclContext()->isTranslationUnit()) || 6664 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 6665 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 6666 LinkageSpecDecl::lang_c)) { 6667 // Okay: this could be a libc/libm/Objective-C function we know 6668 // about. 6669 } else 6670 return; 6671 6672 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 6673 // FIXME: NSLog and NSLogv should be target specific 6674 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 6675 // FIXME: We known better than our headers. 6676 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 6677 } else 6678 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6679 "printf", 1, 6680 Name->isStr("NSLogv") ? 0 : 2)); 6681 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 6682 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 6683 // target-specific builtins, perhaps? 6684 if (!FD->getAttr<FormatAttr>()) 6685 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 6686 "printf", 2, 6687 Name->isStr("vasprintf") ? 0 : 3)); 6688 } 6689} 6690 6691TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 6692 TypeSourceInfo *TInfo) { 6693 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 6694 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 6695 6696 if (!TInfo) { 6697 assert(D.isInvalidType() && "no declarator info for valid type"); 6698 TInfo = Context.getTrivialTypeSourceInfo(T); 6699 } 6700 6701 // Scope manipulation handled by caller. 6702 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 6703 D.getSourceRange().getBegin(), 6704 D.getIdentifierLoc(), 6705 D.getIdentifier(), 6706 TInfo); 6707 6708 // Bail out immediately if we have an invalid declaration. 6709 if (D.isInvalidType()) { 6710 NewTD->setInvalidDecl(); 6711 return NewTD; 6712 } 6713 6714 // C++ [dcl.typedef]p8: 6715 // If the typedef declaration defines an unnamed class (or 6716 // enum), the first typedef-name declared by the declaration 6717 // to be that class type (or enum type) is used to denote the 6718 // class type (or enum type) for linkage purposes only. 6719 // We need to check whether the type was declared in the declaration. 6720 switch (D.getDeclSpec().getTypeSpecType()) { 6721 case TST_enum: 6722 case TST_struct: 6723 case TST_union: 6724 case TST_class: { 6725 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 6726 6727 // Do nothing if the tag is not anonymous or already has an 6728 // associated typedef (from an earlier typedef in this decl group). 6729 if (tagFromDeclSpec->getIdentifier()) break; 6730 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 6731 6732 // A well-formed anonymous tag must always be a TUK_Definition. 6733 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 6734 6735 // The type must match the tag exactly; no qualifiers allowed. 6736 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 6737 break; 6738 6739 // Otherwise, set this is the anon-decl typedef for the tag. 6740 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 6741 break; 6742 } 6743 6744 default: 6745 break; 6746 } 6747 6748 return NewTD; 6749} 6750 6751 6752/// \brief Determine whether a tag with a given kind is acceptable 6753/// as a redeclaration of the given tag declaration. 6754/// 6755/// \returns true if the new tag kind is acceptable, false otherwise. 6756bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 6757 TagTypeKind NewTag, bool isDefinition, 6758 SourceLocation NewTagLoc, 6759 const IdentifierInfo &Name) { 6760 // C++ [dcl.type.elab]p3: 6761 // The class-key or enum keyword present in the 6762 // elaborated-type-specifier shall agree in kind with the 6763 // declaration to which the name in the elaborated-type-specifier 6764 // refers. This rule also applies to the form of 6765 // elaborated-type-specifier that declares a class-name or 6766 // friend class since it can be construed as referring to the 6767 // definition of the class. Thus, in any 6768 // elaborated-type-specifier, the enum keyword shall be used to 6769 // refer to an enumeration (7.2), the union class-key shall be 6770 // used to refer to a union (clause 9), and either the class or 6771 // struct class-key shall be used to refer to a class (clause 9) 6772 // declared using the class or struct class-key. 6773 TagTypeKind OldTag = Previous->getTagKind(); 6774 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 6775 if (OldTag == NewTag) 6776 return true; 6777 6778 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 6779 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 6780 // Warn about the struct/class tag mismatch. 6781 bool isTemplate = false; 6782 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 6783 isTemplate = Record->getDescribedClassTemplate(); 6784 6785 if (!ActiveTemplateInstantiations.empty()) { 6786 // In a template instantiation, do not offer fix-its for tag mismatches 6787 // since they usually mess up the template instead of fixing the problem. 6788 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 6789 << (NewTag == TTK_Class) << isTemplate << &Name; 6790 return true; 6791 } 6792 6793 if (isDefinition) { 6794 // On definitions, check previous tags and issue a fix-it for each 6795 // one that doesn't match the current tag. 6796 if (Previous->getDefinition()) { 6797 // Don't suggest fix-its for redefinitions. 6798 return true; 6799 } 6800 6801 bool previousMismatch = false; 6802 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 6803 E(Previous->redecls_end()); I != E; ++I) { 6804 if (I->getTagKind() != NewTag) { 6805 if (!previousMismatch) { 6806 previousMismatch = true; 6807 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 6808 << (NewTag == TTK_Class) << isTemplate << &Name; 6809 } 6810 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 6811 << (NewTag == TTK_Class) 6812 << FixItHint::CreateReplacement(I->getInnerLocStart(), 6813 NewTag == TTK_Class? 6814 "class" : "struct"); 6815 } 6816 } 6817 return true; 6818 } 6819 6820 // Check for a previous definition. If current tag and definition 6821 // are same type, do nothing. If no definition, but disagree with 6822 // with previous tag type, give a warning, but no fix-it. 6823 const TagDecl *Redecl = Previous->getDefinition() ? 6824 Previous->getDefinition() : Previous; 6825 if (Redecl->getTagKind() == NewTag) { 6826 return true; 6827 } 6828 6829 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 6830 << (NewTag == TTK_Class) 6831 << isTemplate << &Name; 6832 Diag(Redecl->getLocation(), diag::note_previous_use); 6833 6834 // If there is a previous defintion, suggest a fix-it. 6835 if (Previous->getDefinition()) { 6836 Diag(NewTagLoc, diag::note_struct_class_suggestion) 6837 << (Redecl->getTagKind() == TTK_Class) 6838 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 6839 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 6840 } 6841 6842 return true; 6843 } 6844 return false; 6845} 6846 6847/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 6848/// former case, Name will be non-null. In the later case, Name will be null. 6849/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 6850/// reference/declaration/definition of a tag. 6851Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 6852 SourceLocation KWLoc, CXXScopeSpec &SS, 6853 IdentifierInfo *Name, SourceLocation NameLoc, 6854 AttributeList *Attr, AccessSpecifier AS, 6855 MultiTemplateParamsArg TemplateParameterLists, 6856 bool &OwnedDecl, bool &IsDependent, 6857 bool ScopedEnum, bool ScopedEnumUsesClassTag, 6858 TypeResult UnderlyingType) { 6859 // If this is not a definition, it must have a name. 6860 assert((Name != 0 || TUK == TUK_Definition) && 6861 "Nameless record must be a definition!"); 6862 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 6863 6864 OwnedDecl = false; 6865 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6866 6867 // FIXME: Check explicit specializations more carefully. 6868 bool isExplicitSpecialization = false; 6869 bool Invalid = false; 6870 6871 // We only need to do this matching if we have template parameters 6872 // or a scope specifier, which also conveniently avoids this work 6873 // for non-C++ cases. 6874 if (TemplateParameterLists.size() > 0 || 6875 (SS.isNotEmpty() && TUK != TUK_Reference)) { 6876 if (TemplateParameterList *TemplateParams 6877 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 6878 TemplateParameterLists.get(), 6879 TemplateParameterLists.size(), 6880 TUK == TUK_Friend, 6881 isExplicitSpecialization, 6882 Invalid)) { 6883 if (TemplateParams->size() > 0) { 6884 // This is a declaration or definition of a class template (which may 6885 // be a member of another template). 6886 6887 if (Invalid) 6888 return 0; 6889 6890 OwnedDecl = false; 6891 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 6892 SS, Name, NameLoc, Attr, 6893 TemplateParams, AS, 6894 TemplateParameterLists.size() - 1, 6895 (TemplateParameterList**) TemplateParameterLists.release()); 6896 return Result.get(); 6897 } else { 6898 // The "template<>" header is extraneous. 6899 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 6900 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 6901 isExplicitSpecialization = true; 6902 } 6903 } 6904 } 6905 6906 // Figure out the underlying type if this a enum declaration. We need to do 6907 // this early, because it's needed to detect if this is an incompatible 6908 // redeclaration. 6909 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 6910 6911 if (Kind == TTK_Enum) { 6912 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 6913 // No underlying type explicitly specified, or we failed to parse the 6914 // type, default to int. 6915 EnumUnderlying = Context.IntTy.getTypePtr(); 6916 else if (UnderlyingType.get()) { 6917 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 6918 // integral type; any cv-qualification is ignored. 6919 TypeSourceInfo *TI = 0; 6920 QualType T = GetTypeFromParser(UnderlyingType.get(), &TI); 6921 EnumUnderlying = TI; 6922 6923 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 6924 6925 if (!T->isDependentType() && !T->isIntegralType(Context)) { 6926 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 6927 << T; 6928 // Recover by falling back to int. 6929 EnumUnderlying = Context.IntTy.getTypePtr(); 6930 } 6931 6932 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc, TI, 6933 UPPC_FixedUnderlyingType)) 6934 EnumUnderlying = Context.IntTy.getTypePtr(); 6935 6936 } else if (getLangOptions().Microsoft) 6937 // Microsoft enums are always of int type. 6938 EnumUnderlying = Context.IntTy.getTypePtr(); 6939 } 6940 6941 DeclContext *SearchDC = CurContext; 6942 DeclContext *DC = CurContext; 6943 bool isStdBadAlloc = false; 6944 6945 RedeclarationKind Redecl = ForRedeclaration; 6946 if (TUK == TUK_Friend || TUK == TUK_Reference) 6947 Redecl = NotForRedeclaration; 6948 6949 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 6950 6951 if (Name && SS.isNotEmpty()) { 6952 // We have a nested-name tag ('struct foo::bar'). 6953 6954 // Check for invalid 'foo::'. 6955 if (SS.isInvalid()) { 6956 Name = 0; 6957 goto CreateNewDecl; 6958 } 6959 6960 // If this is a friend or a reference to a class in a dependent 6961 // context, don't try to make a decl for it. 6962 if (TUK == TUK_Friend || TUK == TUK_Reference) { 6963 DC = computeDeclContext(SS, false); 6964 if (!DC) { 6965 IsDependent = true; 6966 return 0; 6967 } 6968 } else { 6969 DC = computeDeclContext(SS, true); 6970 if (!DC) { 6971 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 6972 << SS.getRange(); 6973 return 0; 6974 } 6975 } 6976 6977 if (RequireCompleteDeclContext(SS, DC)) 6978 return 0; 6979 6980 SearchDC = DC; 6981 // Look-up name inside 'foo::'. 6982 LookupQualifiedName(Previous, DC); 6983 6984 if (Previous.isAmbiguous()) 6985 return 0; 6986 6987 if (Previous.empty()) { 6988 // Name lookup did not find anything. However, if the 6989 // nested-name-specifier refers to the current instantiation, 6990 // and that current instantiation has any dependent base 6991 // classes, we might find something at instantiation time: treat 6992 // this as a dependent elaborated-type-specifier. 6993 // But this only makes any sense for reference-like lookups. 6994 if (Previous.wasNotFoundInCurrentInstantiation() && 6995 (TUK == TUK_Reference || TUK == TUK_Friend)) { 6996 IsDependent = true; 6997 return 0; 6998 } 6999 7000 // A tag 'foo::bar' must already exist. 7001 Diag(NameLoc, diag::err_not_tag_in_scope) 7002 << Kind << Name << DC << SS.getRange(); 7003 Name = 0; 7004 Invalid = true; 7005 goto CreateNewDecl; 7006 } 7007 } else if (Name) { 7008 // If this is a named struct, check to see if there was a previous forward 7009 // declaration or definition. 7010 // FIXME: We're looking into outer scopes here, even when we 7011 // shouldn't be. Doing so can result in ambiguities that we 7012 // shouldn't be diagnosing. 7013 LookupName(Previous, S); 7014 7015 if (Previous.isAmbiguous() && 7016 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 7017 LookupResult::Filter F = Previous.makeFilter(); 7018 while (F.hasNext()) { 7019 NamedDecl *ND = F.next(); 7020 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 7021 F.erase(); 7022 } 7023 F.done(); 7024 } 7025 7026 // Note: there used to be some attempt at recovery here. 7027 if (Previous.isAmbiguous()) 7028 return 0; 7029 7030 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 7031 // FIXME: This makes sure that we ignore the contexts associated 7032 // with C structs, unions, and enums when looking for a matching 7033 // tag declaration or definition. See the similar lookup tweak 7034 // in Sema::LookupName; is there a better way to deal with this? 7035 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 7036 SearchDC = SearchDC->getParent(); 7037 } 7038 } else if (S->isFunctionPrototypeScope()) { 7039 // If this is an enum declaration in function prototype scope, set its 7040 // initial context to the translation unit. 7041 SearchDC = Context.getTranslationUnitDecl(); 7042 } 7043 7044 if (Previous.isSingleResult() && 7045 Previous.getFoundDecl()->isTemplateParameter()) { 7046 // Maybe we will complain about the shadowed template parameter. 7047 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 7048 // Just pretend that we didn't see the previous declaration. 7049 Previous.clear(); 7050 } 7051 7052 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 7053 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 7054 // This is a declaration of or a reference to "std::bad_alloc". 7055 isStdBadAlloc = true; 7056 7057 if (Previous.empty() && StdBadAlloc) { 7058 // std::bad_alloc has been implicitly declared (but made invisible to 7059 // name lookup). Fill in this implicit declaration as the previous 7060 // declaration, so that the declarations get chained appropriately. 7061 Previous.addDecl(getStdBadAlloc()); 7062 } 7063 } 7064 7065 // If we didn't find a previous declaration, and this is a reference 7066 // (or friend reference), move to the correct scope. In C++, we 7067 // also need to do a redeclaration lookup there, just in case 7068 // there's a shadow friend decl. 7069 if (Name && Previous.empty() && 7070 (TUK == TUK_Reference || TUK == TUK_Friend)) { 7071 if (Invalid) goto CreateNewDecl; 7072 assert(SS.isEmpty()); 7073 7074 if (TUK == TUK_Reference) { 7075 // C++ [basic.scope.pdecl]p5: 7076 // -- for an elaborated-type-specifier of the form 7077 // 7078 // class-key identifier 7079 // 7080 // if the elaborated-type-specifier is used in the 7081 // decl-specifier-seq or parameter-declaration-clause of a 7082 // function defined in namespace scope, the identifier is 7083 // declared as a class-name in the namespace that contains 7084 // the declaration; otherwise, except as a friend 7085 // declaration, the identifier is declared in the smallest 7086 // non-class, non-function-prototype scope that contains the 7087 // declaration. 7088 // 7089 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 7090 // C structs and unions. 7091 // 7092 // It is an error in C++ to declare (rather than define) an enum 7093 // type, including via an elaborated type specifier. We'll 7094 // diagnose that later; for now, declare the enum in the same 7095 // scope as we would have picked for any other tag type. 7096 // 7097 // GNU C also supports this behavior as part of its incomplete 7098 // enum types extension, while GNU C++ does not. 7099 // 7100 // Find the context where we'll be declaring the tag. 7101 // FIXME: We would like to maintain the current DeclContext as the 7102 // lexical context, 7103 while (SearchDC->isRecord() || SearchDC->isTransparentContext()) 7104 SearchDC = SearchDC->getParent(); 7105 7106 // Find the scope where we'll be declaring the tag. 7107 while (S->isClassScope() || 7108 (getLangOptions().CPlusPlus && 7109 S->isFunctionPrototypeScope()) || 7110 ((S->getFlags() & Scope::DeclScope) == 0) || 7111 (S->getEntity() && 7112 ((DeclContext *)S->getEntity())->isTransparentContext())) 7113 S = S->getParent(); 7114 } else { 7115 assert(TUK == TUK_Friend); 7116 // C++ [namespace.memdef]p3: 7117 // If a friend declaration in a non-local class first declares a 7118 // class or function, the friend class or function is a member of 7119 // the innermost enclosing namespace. 7120 SearchDC = SearchDC->getEnclosingNamespaceContext(); 7121 } 7122 7123 // In C++, we need to do a redeclaration lookup to properly 7124 // diagnose some problems. 7125 if (getLangOptions().CPlusPlus) { 7126 Previous.setRedeclarationKind(ForRedeclaration); 7127 LookupQualifiedName(Previous, SearchDC); 7128 } 7129 } 7130 7131 if (!Previous.empty()) { 7132 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 7133 7134 // It's okay to have a tag decl in the same scope as a typedef 7135 // which hides a tag decl in the same scope. Finding this 7136 // insanity with a redeclaration lookup can only actually happen 7137 // in C++. 7138 // 7139 // This is also okay for elaborated-type-specifiers, which is 7140 // technically forbidden by the current standard but which is 7141 // okay according to the likely resolution of an open issue; 7142 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 7143 if (getLangOptions().CPlusPlus) { 7144 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7145 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 7146 TagDecl *Tag = TT->getDecl(); 7147 if (Tag->getDeclName() == Name && 7148 Tag->getDeclContext()->getRedeclContext() 7149 ->Equals(TD->getDeclContext()->getRedeclContext())) { 7150 PrevDecl = Tag; 7151 Previous.clear(); 7152 Previous.addDecl(Tag); 7153 Previous.resolveKind(); 7154 } 7155 } 7156 } 7157 } 7158 7159 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 7160 // If this is a use of a previous tag, or if the tag is already declared 7161 // in the same scope (so that the definition/declaration completes or 7162 // rementions the tag), reuse the decl. 7163 if (TUK == TUK_Reference || TUK == TUK_Friend || 7164 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 7165 // Make sure that this wasn't declared as an enum and now used as a 7166 // struct or something similar. 7167 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 7168 TUK == TUK_Definition, KWLoc, 7169 *Name)) { 7170 bool SafeToContinue 7171 = (PrevTagDecl->getTagKind() != TTK_Enum && 7172 Kind != TTK_Enum); 7173 if (SafeToContinue) 7174 Diag(KWLoc, diag::err_use_with_wrong_tag) 7175 << Name 7176 << FixItHint::CreateReplacement(SourceRange(KWLoc), 7177 PrevTagDecl->getKindName()); 7178 else 7179 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 7180 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7181 7182 if (SafeToContinue) 7183 Kind = PrevTagDecl->getTagKind(); 7184 else { 7185 // Recover by making this an anonymous redefinition. 7186 Name = 0; 7187 Previous.clear(); 7188 Invalid = true; 7189 } 7190 } 7191 7192 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 7193 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 7194 7195 // All conflicts with previous declarations are recovered by 7196 // returning the previous declaration. 7197 if (ScopedEnum != PrevEnum->isScoped()) { 7198 Diag(KWLoc, diag::err_enum_redeclare_scoped_mismatch) 7199 << PrevEnum->isScoped(); 7200 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7201 return PrevTagDecl; 7202 } 7203 else if (EnumUnderlying && PrevEnum->isFixed()) { 7204 QualType T; 7205 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7206 T = TI->getType(); 7207 else 7208 T = QualType(EnumUnderlying.get<const Type*>(), 0); 7209 7210 if (!Context.hasSameUnqualifiedType(T, PrevEnum->getIntegerType())) { 7211 Diag(NameLoc.isValid() ? NameLoc : KWLoc, 7212 diag::err_enum_redeclare_type_mismatch) 7213 << T 7214 << PrevEnum->getIntegerType(); 7215 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7216 return PrevTagDecl; 7217 } 7218 } 7219 else if (!EnumUnderlying.isNull() != PrevEnum->isFixed()) { 7220 Diag(KWLoc, diag::err_enum_redeclare_fixed_mismatch) 7221 << PrevEnum->isFixed(); 7222 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 7223 return PrevTagDecl; 7224 } 7225 } 7226 7227 if (!Invalid) { 7228 // If this is a use, just return the declaration we found. 7229 7230 // FIXME: In the future, return a variant or some other clue 7231 // for the consumer of this Decl to know it doesn't own it. 7232 // For our current ASTs this shouldn't be a problem, but will 7233 // need to be changed with DeclGroups. 7234 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 7235 getLangOptions().Microsoft)) || TUK == TUK_Friend) 7236 return PrevTagDecl; 7237 7238 // Diagnose attempts to redefine a tag. 7239 if (TUK == TUK_Definition) { 7240 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 7241 // If we're defining a specialization and the previous definition 7242 // is from an implicit instantiation, don't emit an error 7243 // here; we'll catch this in the general case below. 7244 if (!isExplicitSpecialization || 7245 !isa<CXXRecordDecl>(Def) || 7246 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 7247 == TSK_ExplicitSpecialization) { 7248 Diag(NameLoc, diag::err_redefinition) << Name; 7249 Diag(Def->getLocation(), diag::note_previous_definition); 7250 // If this is a redefinition, recover by making this 7251 // struct be anonymous, which will make any later 7252 // references get the previous definition. 7253 Name = 0; 7254 Previous.clear(); 7255 Invalid = true; 7256 } 7257 } else { 7258 // If the type is currently being defined, complain 7259 // about a nested redefinition. 7260 const TagType *Tag 7261 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 7262 if (Tag->isBeingDefined()) { 7263 Diag(NameLoc, diag::err_nested_redefinition) << Name; 7264 Diag(PrevTagDecl->getLocation(), 7265 diag::note_previous_definition); 7266 Name = 0; 7267 Previous.clear(); 7268 Invalid = true; 7269 } 7270 } 7271 7272 // Okay, this is definition of a previously declared or referenced 7273 // tag PrevDecl. We're going to create a new Decl for it. 7274 } 7275 } 7276 // If we get here we have (another) forward declaration or we 7277 // have a definition. Just create a new decl. 7278 7279 } else { 7280 // If we get here, this is a definition of a new tag type in a nested 7281 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 7282 // new decl/type. We set PrevDecl to NULL so that the entities 7283 // have distinct types. 7284 Previous.clear(); 7285 } 7286 // If we get here, we're going to create a new Decl. If PrevDecl 7287 // is non-NULL, it's a definition of the tag declared by 7288 // PrevDecl. If it's NULL, we have a new definition. 7289 7290 7291 // Otherwise, PrevDecl is not a tag, but was found with tag 7292 // lookup. This is only actually possible in C++, where a few 7293 // things like templates still live in the tag namespace. 7294 } else { 7295 assert(getLangOptions().CPlusPlus); 7296 7297 // Use a better diagnostic if an elaborated-type-specifier 7298 // found the wrong kind of type on the first 7299 // (non-redeclaration) lookup. 7300 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 7301 !Previous.isForRedeclaration()) { 7302 unsigned Kind = 0; 7303 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7304 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7305 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7306 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 7307 Diag(PrevDecl->getLocation(), diag::note_declared_at); 7308 Invalid = true; 7309 7310 // Otherwise, only diagnose if the declaration is in scope. 7311 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 7312 isExplicitSpecialization)) { 7313 // do nothing 7314 7315 // Diagnose implicit declarations introduced by elaborated types. 7316 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 7317 unsigned Kind = 0; 7318 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 7319 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 7320 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 7321 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 7322 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7323 Invalid = true; 7324 7325 // Otherwise it's a declaration. Call out a particularly common 7326 // case here. 7327 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 7328 unsigned Kind = 0; 7329 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 7330 Diag(NameLoc, diag::err_tag_definition_of_typedef) 7331 << Name << Kind << TND->getUnderlyingType(); 7332 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 7333 Invalid = true; 7334 7335 // Otherwise, diagnose. 7336 } else { 7337 // The tag name clashes with something else in the target scope, 7338 // issue an error and recover by making this tag be anonymous. 7339 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 7340 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7341 Name = 0; 7342 Invalid = true; 7343 } 7344 7345 // The existing declaration isn't relevant to us; we're in a 7346 // new scope, so clear out the previous declaration. 7347 Previous.clear(); 7348 } 7349 } 7350 7351CreateNewDecl: 7352 7353 TagDecl *PrevDecl = 0; 7354 if (Previous.isSingleResult()) 7355 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 7356 7357 // If there is an identifier, use the location of the identifier as the 7358 // location of the decl, otherwise use the location of the struct/union 7359 // keyword. 7360 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 7361 7362 // Otherwise, create a new declaration. If there is a previous 7363 // declaration of the same entity, the two will be linked via 7364 // PrevDecl. 7365 TagDecl *New; 7366 7367 bool IsForwardReference = false; 7368 if (Kind == TTK_Enum) { 7369 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 7370 // enum X { A, B, C } D; D should chain to X. 7371 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 7372 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 7373 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 7374 // If this is an undefined enum, warn. 7375 if (TUK != TUK_Definition && !Invalid) { 7376 TagDecl *Def; 7377 if (getLangOptions().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 7378 // C++0x: 7.2p2: opaque-enum-declaration. 7379 // Conflicts are diagnosed above. Do nothing. 7380 } 7381 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 7382 Diag(Loc, diag::ext_forward_ref_enum_def) 7383 << New; 7384 Diag(Def->getLocation(), diag::note_previous_definition); 7385 } else { 7386 unsigned DiagID = diag::ext_forward_ref_enum; 7387 if (getLangOptions().Microsoft) 7388 DiagID = diag::ext_ms_forward_ref_enum; 7389 else if (getLangOptions().CPlusPlus) 7390 DiagID = diag::err_forward_ref_enum; 7391 Diag(Loc, DiagID); 7392 7393 // If this is a forward-declared reference to an enumeration, make a 7394 // note of it; we won't actually be introducing the declaration into 7395 // the declaration context. 7396 if (TUK == TUK_Reference) 7397 IsForwardReference = true; 7398 } 7399 } 7400 7401 if (EnumUnderlying) { 7402 EnumDecl *ED = cast<EnumDecl>(New); 7403 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 7404 ED->setIntegerTypeSourceInfo(TI); 7405 else 7406 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 7407 ED->setPromotionType(ED->getIntegerType()); 7408 } 7409 7410 } else { 7411 // struct/union/class 7412 7413 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 7414 // struct X { int A; } D; D should chain to X. 7415 if (getLangOptions().CPlusPlus) { 7416 // FIXME: Look for a way to use RecordDecl for simple structs. 7417 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 7418 cast_or_null<CXXRecordDecl>(PrevDecl)); 7419 7420 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 7421 StdBadAlloc = cast<CXXRecordDecl>(New); 7422 } else 7423 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 7424 cast_or_null<RecordDecl>(PrevDecl)); 7425 } 7426 7427 // Maybe add qualifier info. 7428 if (SS.isNotEmpty()) { 7429 if (SS.isSet()) { 7430 New->setQualifierInfo(SS.getWithLocInContext(Context)); 7431 if (TemplateParameterLists.size() > 0) { 7432 New->setTemplateParameterListsInfo(Context, 7433 TemplateParameterLists.size(), 7434 (TemplateParameterList**) TemplateParameterLists.release()); 7435 } 7436 } 7437 else 7438 Invalid = true; 7439 } 7440 7441 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 7442 // Add alignment attributes if necessary; these attributes are checked when 7443 // the ASTContext lays out the structure. 7444 // 7445 // It is important for implementing the correct semantics that this 7446 // happen here (in act on tag decl). The #pragma pack stack is 7447 // maintained as a result of parser callbacks which can occur at 7448 // many points during the parsing of a struct declaration (because 7449 // the #pragma tokens are effectively skipped over during the 7450 // parsing of the struct). 7451 AddAlignmentAttributesForRecord(RD); 7452 7453 AddMsStructLayoutForRecord(RD); 7454 } 7455 7456 // If this is a specialization of a member class (of a class template), 7457 // check the specialization. 7458 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 7459 Invalid = true; 7460 7461 if (Invalid) 7462 New->setInvalidDecl(); 7463 7464 if (Attr) 7465 ProcessDeclAttributeList(S, New, Attr); 7466 7467 // If we're declaring or defining a tag in function prototype scope 7468 // in C, note that this type can only be used within the function. 7469 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 7470 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 7471 7472 // Set the lexical context. If the tag has a C++ scope specifier, the 7473 // lexical context will be different from the semantic context. 7474 New->setLexicalDeclContext(CurContext); 7475 7476 // Mark this as a friend decl if applicable. 7477 // In Microsoft mode, a friend declaration also acts as a forward 7478 // declaration so we always pass true to setObjectOfFriendDecl to make 7479 // the tag name visible. 7480 if (TUK == TUK_Friend) 7481 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 7482 getLangOptions().Microsoft); 7483 7484 // Set the access specifier. 7485 if (!Invalid && SearchDC->isRecord()) 7486 SetMemberAccessSpecifier(New, PrevDecl, AS); 7487 7488 if (TUK == TUK_Definition) 7489 New->startDefinition(); 7490 7491 // If this has an identifier, add it to the scope stack. 7492 if (TUK == TUK_Friend) { 7493 // We might be replacing an existing declaration in the lookup tables; 7494 // if so, borrow its access specifier. 7495 if (PrevDecl) 7496 New->setAccess(PrevDecl->getAccess()); 7497 7498 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 7499 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 7500 if (Name) // can be null along some error paths 7501 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 7502 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 7503 } else if (Name) { 7504 S = getNonFieldDeclScope(S); 7505 PushOnScopeChains(New, S, !IsForwardReference); 7506 if (IsForwardReference) 7507 SearchDC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 7508 7509 } else { 7510 CurContext->addDecl(New); 7511 } 7512 7513 // If this is the C FILE type, notify the AST context. 7514 if (IdentifierInfo *II = New->getIdentifier()) 7515 if (!New->isInvalidDecl() && 7516 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7517 II->isStr("FILE")) 7518 Context.setFILEDecl(New); 7519 7520 OwnedDecl = true; 7521 return New; 7522} 7523 7524void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 7525 AdjustDeclIfTemplate(TagD); 7526 TagDecl *Tag = cast<TagDecl>(TagD); 7527 7528 // Enter the tag context. 7529 PushDeclContext(S, Tag); 7530} 7531 7532void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 7533 SourceLocation FinalLoc, 7534 SourceLocation LBraceLoc) { 7535 AdjustDeclIfTemplate(TagD); 7536 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 7537 7538 FieldCollector->StartClass(); 7539 7540 if (!Record->getIdentifier()) 7541 return; 7542 7543 if (FinalLoc.isValid()) 7544 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 7545 7546 // C++ [class]p2: 7547 // [...] The class-name is also inserted into the scope of the 7548 // class itself; this is known as the injected-class-name. For 7549 // purposes of access checking, the injected-class-name is treated 7550 // as if it were a public member name. 7551 CXXRecordDecl *InjectedClassName 7552 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 7553 Record->getLocStart(), Record->getLocation(), 7554 Record->getIdentifier(), 7555 /*PrevDecl=*/0, 7556 /*DelayTypeCreation=*/true); 7557 Context.getTypeDeclType(InjectedClassName, Record); 7558 InjectedClassName->setImplicit(); 7559 InjectedClassName->setAccess(AS_public); 7560 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 7561 InjectedClassName->setDescribedClassTemplate(Template); 7562 PushOnScopeChains(InjectedClassName, S); 7563 assert(InjectedClassName->isInjectedClassName() && 7564 "Broken injected-class-name"); 7565} 7566 7567void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 7568 SourceLocation RBraceLoc) { 7569 AdjustDeclIfTemplate(TagD); 7570 TagDecl *Tag = cast<TagDecl>(TagD); 7571 Tag->setRBraceLoc(RBraceLoc); 7572 7573 if (isa<CXXRecordDecl>(Tag)) 7574 FieldCollector->FinishClass(); 7575 7576 // Exit this scope of this tag's definition. 7577 PopDeclContext(); 7578 7579 // Notify the consumer that we've defined a tag. 7580 Consumer.HandleTagDeclDefinition(Tag); 7581} 7582 7583void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 7584 AdjustDeclIfTemplate(TagD); 7585 TagDecl *Tag = cast<TagDecl>(TagD); 7586 Tag->setInvalidDecl(); 7587 7588 // We're undoing ActOnTagStartDefinition here, not 7589 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 7590 // the FieldCollector. 7591 7592 PopDeclContext(); 7593} 7594 7595// Note that FieldName may be null for anonymous bitfields. 7596bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 7597 QualType FieldTy, const Expr *BitWidth, 7598 bool *ZeroWidth) { 7599 // Default to true; that shouldn't confuse checks for emptiness 7600 if (ZeroWidth) 7601 *ZeroWidth = true; 7602 7603 // C99 6.7.2.1p4 - verify the field type. 7604 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 7605 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 7606 // Handle incomplete types with specific error. 7607 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 7608 return true; 7609 if (FieldName) 7610 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 7611 << FieldName << FieldTy << BitWidth->getSourceRange(); 7612 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 7613 << FieldTy << BitWidth->getSourceRange(); 7614 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 7615 UPPC_BitFieldWidth)) 7616 return true; 7617 7618 // If the bit-width is type- or value-dependent, don't try to check 7619 // it now. 7620 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 7621 return false; 7622 7623 llvm::APSInt Value; 7624 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 7625 return true; 7626 7627 if (Value != 0 && ZeroWidth) 7628 *ZeroWidth = false; 7629 7630 // Zero-width bitfield is ok for anonymous field. 7631 if (Value == 0 && FieldName) 7632 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 7633 7634 if (Value.isSigned() && Value.isNegative()) { 7635 if (FieldName) 7636 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 7637 << FieldName << Value.toString(10); 7638 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 7639 << Value.toString(10); 7640 } 7641 7642 if (!FieldTy->isDependentType()) { 7643 uint64_t TypeSize = Context.getTypeSize(FieldTy); 7644 if (Value.getZExtValue() > TypeSize) { 7645 if (!getLangOptions().CPlusPlus) { 7646 if (FieldName) 7647 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 7648 << FieldName << (unsigned)Value.getZExtValue() 7649 << (unsigned)TypeSize; 7650 7651 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 7652 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 7653 } 7654 7655 if (FieldName) 7656 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 7657 << FieldName << (unsigned)Value.getZExtValue() 7658 << (unsigned)TypeSize; 7659 else 7660 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 7661 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 7662 } 7663 } 7664 7665 return false; 7666} 7667 7668/// ActOnField - Each field of a C struct/union is passed into this in order 7669/// to create a FieldDecl object for it. 7670Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 7671 Declarator &D, ExprTy *BitfieldWidth) { 7672 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 7673 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 7674 /*HasInit=*/false, AS_public); 7675 return Res; 7676} 7677 7678/// HandleField - Analyze a field of a C struct or a C++ data member. 7679/// 7680FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 7681 SourceLocation DeclStart, 7682 Declarator &D, Expr *BitWidth, bool HasInit, 7683 AccessSpecifier AS) { 7684 IdentifierInfo *II = D.getIdentifier(); 7685 SourceLocation Loc = DeclStart; 7686 if (II) Loc = D.getIdentifierLoc(); 7687 7688 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7689 QualType T = TInfo->getType(); 7690 if (getLangOptions().CPlusPlus) { 7691 CheckExtraCXXDefaultArguments(D); 7692 7693 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 7694 UPPC_DataMemberType)) { 7695 D.setInvalidType(); 7696 T = Context.IntTy; 7697 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 7698 } 7699 } 7700 7701 DiagnoseFunctionSpecifiers(D); 7702 7703 if (D.getDeclSpec().isThreadSpecified()) 7704 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 7705 7706 // Check to see if this name was declared as a member previously 7707 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 7708 LookupName(Previous, S); 7709 assert((Previous.empty() || Previous.isOverloadedResult() || 7710 Previous.isSingleResult()) 7711 && "Lookup of member name should be either overloaded, single or null"); 7712 7713 // If the name is overloaded then get any declaration else get the single result 7714 NamedDecl *PrevDecl = Previous.isOverloadedResult() ? 7715 Previous.getRepresentativeDecl() : Previous.getAsSingle<NamedDecl>(); 7716 7717 if (PrevDecl && PrevDecl->isTemplateParameter()) { 7718 // Maybe we will complain about the shadowed template parameter. 7719 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7720 // Just pretend that we didn't see the previous declaration. 7721 PrevDecl = 0; 7722 } 7723 7724 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 7725 PrevDecl = 0; 7726 7727 bool Mutable 7728 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 7729 SourceLocation TSSL = D.getSourceRange().getBegin(); 7730 FieldDecl *NewFD 7731 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit, 7732 TSSL, AS, PrevDecl, &D); 7733 7734 if (NewFD->isInvalidDecl()) 7735 Record->setInvalidDecl(); 7736 7737 if (NewFD->isInvalidDecl() && PrevDecl) { 7738 // Don't introduce NewFD into scope; there's already something 7739 // with the same name in the same scope. 7740 } else if (II) { 7741 PushOnScopeChains(NewFD, S); 7742 } else 7743 Record->addDecl(NewFD); 7744 7745 return NewFD; 7746} 7747 7748/// \brief Build a new FieldDecl and check its well-formedness. 7749/// 7750/// This routine builds a new FieldDecl given the fields name, type, 7751/// record, etc. \p PrevDecl should refer to any previous declaration 7752/// with the same name and in the same scope as the field to be 7753/// created. 7754/// 7755/// \returns a new FieldDecl. 7756/// 7757/// \todo The Declarator argument is a hack. It will be removed once 7758FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 7759 TypeSourceInfo *TInfo, 7760 RecordDecl *Record, SourceLocation Loc, 7761 bool Mutable, Expr *BitWidth, bool HasInit, 7762 SourceLocation TSSL, 7763 AccessSpecifier AS, NamedDecl *PrevDecl, 7764 Declarator *D) { 7765 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7766 bool InvalidDecl = false; 7767 if (D) InvalidDecl = D->isInvalidType(); 7768 7769 // If we receive a broken type, recover by assuming 'int' and 7770 // marking this declaration as invalid. 7771 if (T.isNull()) { 7772 InvalidDecl = true; 7773 T = Context.IntTy; 7774 } 7775 7776 QualType EltTy = Context.getBaseElementType(T); 7777 if (!EltTy->isDependentType() && 7778 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 7779 // Fields of incomplete type force their record to be invalid. 7780 Record->setInvalidDecl(); 7781 InvalidDecl = true; 7782 } 7783 7784 // C99 6.7.2.1p8: A member of a structure or union may have any type other 7785 // than a variably modified type. 7786 if (!InvalidDecl && T->isVariablyModifiedType()) { 7787 bool SizeIsNegative; 7788 llvm::APSInt Oversized; 7789 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 7790 SizeIsNegative, 7791 Oversized); 7792 if (!FixedTy.isNull()) { 7793 Diag(Loc, diag::warn_illegal_constant_array_size); 7794 T = FixedTy; 7795 } else { 7796 if (SizeIsNegative) 7797 Diag(Loc, diag::err_typecheck_negative_array_size); 7798 else if (Oversized.getBoolValue()) 7799 Diag(Loc, diag::err_array_too_large) 7800 << Oversized.toString(10); 7801 else 7802 Diag(Loc, diag::err_typecheck_field_variable_size); 7803 InvalidDecl = true; 7804 } 7805 } 7806 7807 // Fields can not have abstract class types 7808 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 7809 diag::err_abstract_type_in_decl, 7810 AbstractFieldType)) 7811 InvalidDecl = true; 7812 7813 bool ZeroWidth = false; 7814 // If this is declared as a bit-field, check the bit-field. 7815 if (!InvalidDecl && BitWidth && 7816 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 7817 InvalidDecl = true; 7818 BitWidth = 0; 7819 ZeroWidth = false; 7820 } 7821 7822 // Check that 'mutable' is consistent with the type of the declaration. 7823 if (!InvalidDecl && Mutable) { 7824 unsigned DiagID = 0; 7825 if (T->isReferenceType()) 7826 DiagID = diag::err_mutable_reference; 7827 else if (T.isConstQualified()) 7828 DiagID = diag::err_mutable_const; 7829 7830 if (DiagID) { 7831 SourceLocation ErrLoc = Loc; 7832 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 7833 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 7834 Diag(ErrLoc, DiagID); 7835 Mutable = false; 7836 InvalidDecl = true; 7837 } 7838 } 7839 7840 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 7841 BitWidth, Mutable, HasInit); 7842 if (InvalidDecl) 7843 NewFD->setInvalidDecl(); 7844 7845 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 7846 Diag(Loc, diag::err_duplicate_member) << II; 7847 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 7848 NewFD->setInvalidDecl(); 7849 } 7850 7851 if (!InvalidDecl && getLangOptions().CPlusPlus) { 7852 if (Record->isUnion()) { 7853 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 7854 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 7855 if (RDecl->getDefinition()) { 7856 // C++ [class.union]p1: An object of a class with a non-trivial 7857 // constructor, a non-trivial copy constructor, a non-trivial 7858 // destructor, or a non-trivial copy assignment operator 7859 // cannot be a member of a union, nor can an array of such 7860 // objects. 7861 if (!getLangOptions().CPlusPlus0x && CheckNontrivialField(NewFD)) 7862 NewFD->setInvalidDecl(); 7863 } 7864 } 7865 7866 // C++ [class.union]p1: If a union contains a member of reference type, 7867 // the program is ill-formed. 7868 if (EltTy->isReferenceType()) { 7869 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 7870 << NewFD->getDeclName() << EltTy; 7871 NewFD->setInvalidDecl(); 7872 } 7873 } 7874 } 7875 7876 // FIXME: We need to pass in the attributes given an AST 7877 // representation, not a parser representation. 7878 if (D) 7879 // FIXME: What to pass instead of TUScope? 7880 ProcessDeclAttributes(TUScope, NewFD, *D); 7881 7882 // In auto-retain/release, infer strong retension for fields of 7883 // retainable type. 7884 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 7885 NewFD->setInvalidDecl(); 7886 7887 if (T.isObjCGCWeak()) 7888 Diag(Loc, diag::warn_attribute_weak_on_field); 7889 7890 NewFD->setAccess(AS); 7891 return NewFD; 7892} 7893 7894bool Sema::CheckNontrivialField(FieldDecl *FD) { 7895 assert(FD); 7896 assert(getLangOptions().CPlusPlus && "valid check only for C++"); 7897 7898 if (FD->isInvalidDecl()) 7899 return true; 7900 7901 QualType EltTy = Context.getBaseElementType(FD->getType()); 7902 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 7903 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 7904 if (RDecl->getDefinition()) { 7905 // We check for copy constructors before constructors 7906 // because otherwise we'll never get complaints about 7907 // copy constructors. 7908 7909 CXXSpecialMember member = CXXInvalid; 7910 if (!RDecl->hasTrivialCopyConstructor()) 7911 member = CXXCopyConstructor; 7912 else if (!RDecl->hasTrivialDefaultConstructor()) 7913 member = CXXDefaultConstructor; 7914 else if (!RDecl->hasTrivialCopyAssignment()) 7915 member = CXXCopyAssignment; 7916 else if (!RDecl->hasTrivialDestructor()) 7917 member = CXXDestructor; 7918 7919 if (member != CXXInvalid) { 7920 if (getLangOptions().ObjCAutoRefCount && RDecl->hasObjectMember()) { 7921 // Objective-C++ ARC: it is an error to have a non-trivial field of 7922 // a union. However, system headers in Objective-C programs 7923 // occasionally have Objective-C lifetime objects within unions, 7924 // and rather than cause the program to fail, we make those 7925 // members unavailable. 7926 SourceLocation Loc = FD->getLocation(); 7927 if (getSourceManager().isInSystemHeader(Loc)) { 7928 if (!FD->hasAttr<UnavailableAttr>()) 7929 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 7930 "this system field has retaining ownership")); 7931 return false; 7932 } 7933 } 7934 7935 Diag(FD->getLocation(), diag::err_illegal_union_or_anon_struct_member) 7936 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 7937 DiagnoseNontrivial(RT, member); 7938 return true; 7939 } 7940 } 7941 } 7942 7943 return false; 7944} 7945 7946/// DiagnoseNontrivial - Given that a class has a non-trivial 7947/// special member, figure out why. 7948void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 7949 QualType QT(T, 0U); 7950 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 7951 7952 // Check whether the member was user-declared. 7953 switch (member) { 7954 case CXXInvalid: 7955 break; 7956 7957 case CXXDefaultConstructor: 7958 if (RD->hasUserDeclaredConstructor()) { 7959 typedef CXXRecordDecl::ctor_iterator ctor_iter; 7960 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 7961 const FunctionDecl *body = 0; 7962 ci->hasBody(body); 7963 if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) { 7964 SourceLocation CtorLoc = ci->getLocation(); 7965 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 7966 return; 7967 } 7968 } 7969 7970 assert(0 && "found no user-declared constructors"); 7971 return; 7972 } 7973 break; 7974 7975 case CXXCopyConstructor: 7976 if (RD->hasUserDeclaredCopyConstructor()) { 7977 SourceLocation CtorLoc = 7978 RD->getCopyConstructor(0)->getLocation(); 7979 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 7980 return; 7981 } 7982 break; 7983 7984 case CXXMoveConstructor: 7985 if (RD->hasUserDeclaredMoveConstructor()) { 7986 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 7987 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 7988 return; 7989 } 7990 break; 7991 7992 case CXXCopyAssignment: 7993 if (RD->hasUserDeclaredCopyAssignment()) { 7994 // FIXME: this should use the location of the copy 7995 // assignment, not the type. 7996 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 7997 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 7998 return; 7999 } 8000 break; 8001 8002 case CXXMoveAssignment: 8003 if (RD->hasUserDeclaredMoveAssignment()) { 8004 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 8005 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 8006 return; 8007 } 8008 break; 8009 8010 case CXXDestructor: 8011 if (RD->hasUserDeclaredDestructor()) { 8012 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 8013 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 8014 return; 8015 } 8016 break; 8017 } 8018 8019 typedef CXXRecordDecl::base_class_iterator base_iter; 8020 8021 // Virtual bases and members inhibit trivial copying/construction, 8022 // but not trivial destruction. 8023 if (member != CXXDestructor) { 8024 // Check for virtual bases. vbases includes indirect virtual bases, 8025 // so we just iterate through the direct bases. 8026 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 8027 if (bi->isVirtual()) { 8028 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8029 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 8030 return; 8031 } 8032 8033 // Check for virtual methods. 8034 typedef CXXRecordDecl::method_iterator meth_iter; 8035 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 8036 ++mi) { 8037 if (mi->isVirtual()) { 8038 SourceLocation MLoc = mi->getSourceRange().getBegin(); 8039 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 8040 return; 8041 } 8042 } 8043 } 8044 8045 bool (CXXRecordDecl::*hasTrivial)() const; 8046 switch (member) { 8047 case CXXDefaultConstructor: 8048 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 8049 case CXXCopyConstructor: 8050 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 8051 case CXXCopyAssignment: 8052 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 8053 case CXXDestructor: 8054 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 8055 default: 8056 assert(0 && "unexpected special member"); return; 8057 } 8058 8059 // Check for nontrivial bases (and recurse). 8060 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 8061 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 8062 assert(BaseRT && "Don't know how to handle dependent bases"); 8063 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 8064 if (!(BaseRecTy->*hasTrivial)()) { 8065 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 8066 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 8067 DiagnoseNontrivial(BaseRT, member); 8068 return; 8069 } 8070 } 8071 8072 // Check for nontrivial members (and recurse). 8073 typedef RecordDecl::field_iterator field_iter; 8074 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 8075 ++fi) { 8076 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 8077 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 8078 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 8079 8080 if (!(EltRD->*hasTrivial)()) { 8081 SourceLocation FLoc = (*fi)->getLocation(); 8082 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 8083 DiagnoseNontrivial(EltRT, member); 8084 return; 8085 } 8086 } 8087 8088 if (EltTy->isObjCLifetimeType()) { 8089 switch (EltTy.getObjCLifetime()) { 8090 case Qualifiers::OCL_None: 8091 case Qualifiers::OCL_ExplicitNone: 8092 break; 8093 8094 case Qualifiers::OCL_Autoreleasing: 8095 case Qualifiers::OCL_Weak: 8096 case Qualifiers::OCL_Strong: 8097 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership) 8098 << QT << EltTy.getObjCLifetime(); 8099 return; 8100 } 8101 } 8102 } 8103 8104 assert(0 && "found no explanation for non-trivial member"); 8105} 8106 8107/// TranslateIvarVisibility - Translate visibility from a token ID to an 8108/// AST enum value. 8109static ObjCIvarDecl::AccessControl 8110TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 8111 switch (ivarVisibility) { 8112 default: assert(0 && "Unknown visitibility kind"); 8113 case tok::objc_private: return ObjCIvarDecl::Private; 8114 case tok::objc_public: return ObjCIvarDecl::Public; 8115 case tok::objc_protected: return ObjCIvarDecl::Protected; 8116 case tok::objc_package: return ObjCIvarDecl::Package; 8117 } 8118} 8119 8120/// ActOnIvar - Each ivar field of an objective-c class is passed into this 8121/// in order to create an IvarDecl object for it. 8122Decl *Sema::ActOnIvar(Scope *S, 8123 SourceLocation DeclStart, 8124 Decl *IntfDecl, 8125 Declarator &D, ExprTy *BitfieldWidth, 8126 tok::ObjCKeywordKind Visibility) { 8127 8128 IdentifierInfo *II = D.getIdentifier(); 8129 Expr *BitWidth = (Expr*)BitfieldWidth; 8130 SourceLocation Loc = DeclStart; 8131 if (II) Loc = D.getIdentifierLoc(); 8132 8133 // FIXME: Unnamed fields can be handled in various different ways, for 8134 // example, unnamed unions inject all members into the struct namespace! 8135 8136 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8137 QualType T = TInfo->getType(); 8138 8139 if (BitWidth) { 8140 // 6.7.2.1p3, 6.7.2.1p4 8141 if (VerifyBitField(Loc, II, T, BitWidth)) { 8142 D.setInvalidType(); 8143 BitWidth = 0; 8144 } 8145 } else { 8146 // Not a bitfield. 8147 8148 // validate II. 8149 8150 } 8151 if (T->isReferenceType()) { 8152 Diag(Loc, diag::err_ivar_reference_type); 8153 D.setInvalidType(); 8154 } 8155 // C99 6.7.2.1p8: A member of a structure or union may have any type other 8156 // than a variably modified type. 8157 else if (T->isVariablyModifiedType()) { 8158 Diag(Loc, diag::err_typecheck_ivar_variable_size); 8159 D.setInvalidType(); 8160 } 8161 8162 // Get the visibility (access control) for this ivar. 8163 ObjCIvarDecl::AccessControl ac = 8164 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 8165 : ObjCIvarDecl::None; 8166 // Must set ivar's DeclContext to its enclosing interface. 8167 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(IntfDecl); 8168 ObjCContainerDecl *EnclosingContext; 8169 if (ObjCImplementationDecl *IMPDecl = 8170 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8171 if (!LangOpts.ObjCNonFragileABI2) { 8172 // Case of ivar declared in an implementation. Context is that of its class. 8173 EnclosingContext = IMPDecl->getClassInterface(); 8174 assert(EnclosingContext && "Implementation has no class interface!"); 8175 } 8176 else 8177 EnclosingContext = EnclosingDecl; 8178 } else { 8179 if (ObjCCategoryDecl *CDecl = 8180 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8181 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 8182 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 8183 return 0; 8184 } 8185 } 8186 EnclosingContext = EnclosingDecl; 8187 } 8188 8189 // Construct the decl. 8190 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 8191 DeclStart, Loc, II, T, 8192 TInfo, ac, (Expr *)BitfieldWidth); 8193 8194 if (II) { 8195 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 8196 ForRedeclaration); 8197 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 8198 && !isa<TagDecl>(PrevDecl)) { 8199 Diag(Loc, diag::err_duplicate_member) << II; 8200 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8201 NewID->setInvalidDecl(); 8202 } 8203 } 8204 8205 // Process attributes attached to the ivar. 8206 ProcessDeclAttributes(S, NewID, D); 8207 8208 if (D.isInvalidType()) 8209 NewID->setInvalidDecl(); 8210 8211 // In ARC, infer 'retaining' for ivars of retainable type. 8212 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 8213 NewID->setInvalidDecl(); 8214 8215 if (II) { 8216 // FIXME: When interfaces are DeclContexts, we'll need to add 8217 // these to the interface. 8218 S->AddDecl(NewID); 8219 IdResolver.AddDecl(NewID); 8220 } 8221 8222 return NewID; 8223} 8224 8225/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 8226/// class and class extensions. For every class @interface and class 8227/// extension @interface, if the last ivar is a bitfield of any type, 8228/// then add an implicit `char :0` ivar to the end of that interface. 8229void Sema::ActOnLastBitfield(SourceLocation DeclLoc, Decl *EnclosingDecl, 8230 llvm::SmallVectorImpl<Decl *> &AllIvarDecls) { 8231 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 8232 return; 8233 8234 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 8235 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 8236 8237 if (!Ivar->isBitField()) 8238 return; 8239 uint64_t BitFieldSize = 8240 Ivar->getBitWidth()->EvaluateAsInt(Context).getZExtValue(); 8241 if (BitFieldSize == 0) 8242 return; 8243 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl); 8244 if (!ID) { 8245 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8246 if (!CD->IsClassExtension()) 8247 return; 8248 } 8249 // No need to add this to end of @implementation. 8250 else 8251 return; 8252 } 8253 // All conditions are met. Add a new bitfield to the tail end of ivars. 8254 llvm::APInt Zero(Context.getTypeSize(Context.CharTy), 0); 8255 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.CharTy, DeclLoc); 8256 8257 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(EnclosingDecl), 8258 DeclLoc, DeclLoc, 0, 8259 Context.CharTy, 8260 Context.CreateTypeSourceInfo(Context.CharTy), 8261 ObjCIvarDecl::Private, BW, 8262 true); 8263 AllIvarDecls.push_back(Ivar); 8264} 8265 8266void Sema::ActOnFields(Scope* S, 8267 SourceLocation RecLoc, Decl *EnclosingDecl, 8268 Decl **Fields, unsigned NumFields, 8269 SourceLocation LBrac, SourceLocation RBrac, 8270 AttributeList *Attr) { 8271 assert(EnclosingDecl && "missing record or interface decl"); 8272 8273 // If the decl this is being inserted into is invalid, then it may be a 8274 // redeclaration or some other bogus case. Don't try to add fields to it. 8275 if (EnclosingDecl->isInvalidDecl()) { 8276 // FIXME: Deallocate fields? 8277 return; 8278 } 8279 8280 8281 // Verify that all the fields are okay. 8282 unsigned NumNamedMembers = 0; 8283 llvm::SmallVector<FieldDecl*, 32> RecFields; 8284 8285 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 8286 bool ARCErrReported = false; 8287 for (unsigned i = 0; i != NumFields; ++i) { 8288 FieldDecl *FD = cast<FieldDecl>(Fields[i]); 8289 8290 // Get the type for the field. 8291 const Type *FDTy = FD->getType().getTypePtr(); 8292 8293 if (!FD->isAnonymousStructOrUnion()) { 8294 // Remember all fields written by the user. 8295 RecFields.push_back(FD); 8296 } 8297 8298 // If the field is already invalid for some reason, don't emit more 8299 // diagnostics about it. 8300 if (FD->isInvalidDecl()) { 8301 EnclosingDecl->setInvalidDecl(); 8302 continue; 8303 } 8304 8305 // C99 6.7.2.1p2: 8306 // A structure or union shall not contain a member with 8307 // incomplete or function type (hence, a structure shall not 8308 // contain an instance of itself, but may contain a pointer to 8309 // an instance of itself), except that the last member of a 8310 // structure with more than one named member may have incomplete 8311 // array type; such a structure (and any union containing, 8312 // possibly recursively, a member that is such a structure) 8313 // shall not be a member of a structure or an element of an 8314 // array. 8315 if (FDTy->isFunctionType()) { 8316 // Field declared as a function. 8317 Diag(FD->getLocation(), diag::err_field_declared_as_function) 8318 << FD->getDeclName(); 8319 FD->setInvalidDecl(); 8320 EnclosingDecl->setInvalidDecl(); 8321 continue; 8322 } else if (FDTy->isIncompleteArrayType() && Record && 8323 ((i == NumFields - 1 && !Record->isUnion()) || 8324 ((getLangOptions().Microsoft || getLangOptions().CPlusPlus) && 8325 (i == NumFields - 1 || Record->isUnion())))) { 8326 // Flexible array member. 8327 // Microsoft and g++ is more permissive regarding flexible array. 8328 // It will accept flexible array in union and also 8329 // as the sole element of a struct/class. 8330 if (getLangOptions().Microsoft) { 8331 if (Record->isUnion()) 8332 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 8333 << FD->getDeclName(); 8334 else if (NumFields == 1) 8335 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 8336 << FD->getDeclName() << Record->getTagKind(); 8337 } else if (getLangOptions().CPlusPlus) { 8338 if (Record->isUnion()) 8339 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 8340 << FD->getDeclName(); 8341 else if (NumFields == 1) 8342 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 8343 << FD->getDeclName() << Record->getTagKind(); 8344 } else if (NumNamedMembers < 1) { 8345 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 8346 << FD->getDeclName(); 8347 FD->setInvalidDecl(); 8348 EnclosingDecl->setInvalidDecl(); 8349 continue; 8350 } 8351 if (!FD->getType()->isDependentType() && 8352 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 8353 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 8354 << FD->getDeclName() << FD->getType(); 8355 FD->setInvalidDecl(); 8356 EnclosingDecl->setInvalidDecl(); 8357 continue; 8358 } 8359 // Okay, we have a legal flexible array member at the end of the struct. 8360 if (Record) 8361 Record->setHasFlexibleArrayMember(true); 8362 } else if (!FDTy->isDependentType() && 8363 RequireCompleteType(FD->getLocation(), FD->getType(), 8364 diag::err_field_incomplete)) { 8365 // Incomplete type 8366 FD->setInvalidDecl(); 8367 EnclosingDecl->setInvalidDecl(); 8368 continue; 8369 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 8370 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 8371 // If this is a member of a union, then entire union becomes "flexible". 8372 if (Record && Record->isUnion()) { 8373 Record->setHasFlexibleArrayMember(true); 8374 } else { 8375 // If this is a struct/class and this is not the last element, reject 8376 // it. Note that GCC supports variable sized arrays in the middle of 8377 // structures. 8378 if (i != NumFields-1) 8379 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 8380 << FD->getDeclName() << FD->getType(); 8381 else { 8382 // We support flexible arrays at the end of structs in 8383 // other structs as an extension. 8384 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 8385 << FD->getDeclName(); 8386 if (Record) 8387 Record->setHasFlexibleArrayMember(true); 8388 } 8389 } 8390 } 8391 if (Record && FDTTy->getDecl()->hasObjectMember()) 8392 Record->setHasObjectMember(true); 8393 } else if (FDTy->isObjCObjectType()) { 8394 /// A field cannot be an Objective-c object 8395 Diag(FD->getLocation(), diag::err_statically_allocated_object); 8396 FD->setInvalidDecl(); 8397 EnclosingDecl->setInvalidDecl(); 8398 continue; 8399 } 8400 else if (!getLangOptions().CPlusPlus) { 8401 if (getLangOptions().ObjCAutoRefCount && Record && !ARCErrReported) { 8402 // It's an error in ARC if a field has lifetime. 8403 // We don't want to report this in a system header, though, 8404 // so we just make the field unavailable. 8405 // FIXME: that's really not sufficient; we need to make the type 8406 // itself invalid to, say, initialize or copy. 8407 QualType T = FD->getType(); 8408 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 8409 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 8410 SourceLocation loc = FD->getLocation(); 8411 if (getSourceManager().isInSystemHeader(loc)) { 8412 if (!FD->hasAttr<UnavailableAttr>()) { 8413 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 8414 "this system field has retaining ownership")); 8415 } 8416 } else { 8417 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct); 8418 } 8419 ARCErrReported = true; 8420 } 8421 } 8422 else if (getLangOptions().ObjC1 && 8423 getLangOptions().getGCMode() != LangOptions::NonGC && 8424 Record && !Record->hasObjectMember()) { 8425 if (FD->getType()->isObjCObjectPointerType() || 8426 FD->getType().isObjCGCStrong()) 8427 Record->setHasObjectMember(true); 8428 else if (Context.getAsArrayType(FD->getType())) { 8429 QualType BaseType = Context.getBaseElementType(FD->getType()); 8430 if (BaseType->isRecordType() && 8431 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 8432 Record->setHasObjectMember(true); 8433 else if (BaseType->isObjCObjectPointerType() || 8434 BaseType.isObjCGCStrong()) 8435 Record->setHasObjectMember(true); 8436 } 8437 } 8438 } 8439 // Keep track of the number of named members. 8440 if (FD->getIdentifier()) 8441 ++NumNamedMembers; 8442 } 8443 8444 // Okay, we successfully defined 'Record'. 8445 if (Record) { 8446 bool Completed = false; 8447 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 8448 if (!CXXRecord->isInvalidDecl()) { 8449 // Set access bits correctly on the directly-declared conversions. 8450 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 8451 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 8452 I != E; ++I) 8453 Convs->setAccess(I, (*I)->getAccess()); 8454 8455 if (!CXXRecord->isDependentType()) { 8456 // Objective-C Automatic Reference Counting: 8457 // If a class has a non-static data member of Objective-C pointer 8458 // type (or array thereof), it is a non-POD type and its 8459 // default constructor (if any), copy constructor, copy assignment 8460 // operator, and destructor are non-trivial. 8461 // 8462 // This rule is also handled by CXXRecordDecl::completeDefinition(). 8463 // However, here we check whether this particular class is only 8464 // non-POD because of the presence of an Objective-C pointer member. 8465 // If so, objects of this type cannot be shared between code compiled 8466 // with instant objects and code compiled with manual retain/release. 8467 if (getLangOptions().ObjCAutoRefCount && 8468 CXXRecord->hasObjectMember() && 8469 CXXRecord->getLinkage() == ExternalLinkage) { 8470 if (CXXRecord->isPOD()) { 8471 Diag(CXXRecord->getLocation(), 8472 diag::warn_arc_non_pod_class_with_object_member) 8473 << CXXRecord; 8474 } else { 8475 // FIXME: Fix-Its would be nice here, but finding a good location 8476 // for them is going to be tricky. 8477 if (CXXRecord->hasTrivialCopyConstructor()) 8478 Diag(CXXRecord->getLocation(), 8479 diag::warn_arc_trivial_member_function_with_object_member) 8480 << CXXRecord << 0; 8481 if (CXXRecord->hasTrivialCopyAssignment()) 8482 Diag(CXXRecord->getLocation(), 8483 diag::warn_arc_trivial_member_function_with_object_member) 8484 << CXXRecord << 1; 8485 if (CXXRecord->hasTrivialDestructor()) 8486 Diag(CXXRecord->getLocation(), 8487 diag::warn_arc_trivial_member_function_with_object_member) 8488 << CXXRecord << 2; 8489 } 8490 } 8491 8492 // Adjust user-defined destructor exception spec. 8493 if (getLangOptions().CPlusPlus0x && 8494 CXXRecord->hasUserDeclaredDestructor()) 8495 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 8496 8497 // Add any implicitly-declared members to this class. 8498 AddImplicitlyDeclaredMembersToClass(CXXRecord); 8499 8500 // If we have virtual base classes, we may end up finding multiple 8501 // final overriders for a given virtual function. Check for this 8502 // problem now. 8503 if (CXXRecord->getNumVBases()) { 8504 CXXFinalOverriderMap FinalOverriders; 8505 CXXRecord->getFinalOverriders(FinalOverriders); 8506 8507 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 8508 MEnd = FinalOverriders.end(); 8509 M != MEnd; ++M) { 8510 for (OverridingMethods::iterator SO = M->second.begin(), 8511 SOEnd = M->second.end(); 8512 SO != SOEnd; ++SO) { 8513 assert(SO->second.size() > 0 && 8514 "Virtual function without overridding functions?"); 8515 if (SO->second.size() == 1) 8516 continue; 8517 8518 // C++ [class.virtual]p2: 8519 // In a derived class, if a virtual member function of a base 8520 // class subobject has more than one final overrider the 8521 // program is ill-formed. 8522 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 8523 << (NamedDecl *)M->first << Record; 8524 Diag(M->first->getLocation(), 8525 diag::note_overridden_virtual_function); 8526 for (OverridingMethods::overriding_iterator 8527 OM = SO->second.begin(), 8528 OMEnd = SO->second.end(); 8529 OM != OMEnd; ++OM) 8530 Diag(OM->Method->getLocation(), diag::note_final_overrider) 8531 << (NamedDecl *)M->first << OM->Method->getParent(); 8532 8533 Record->setInvalidDecl(); 8534 } 8535 } 8536 CXXRecord->completeDefinition(&FinalOverriders); 8537 Completed = true; 8538 } 8539 } 8540 } 8541 } 8542 8543 if (!Completed) 8544 Record->completeDefinition(); 8545 8546 // Now that the record is complete, do any delayed exception spec checks 8547 // we were missing. 8548 while (!DelayedDestructorExceptionSpecChecks.empty()) { 8549 const CXXDestructorDecl *Dtor = 8550 DelayedDestructorExceptionSpecChecks.back().first; 8551 if (Dtor->getParent() != Record) 8552 break; 8553 8554 assert(!Dtor->getParent()->isDependentType() && 8555 "Should not ever add destructors of templates into the list."); 8556 CheckOverridingFunctionExceptionSpec(Dtor, 8557 DelayedDestructorExceptionSpecChecks.back().second); 8558 DelayedDestructorExceptionSpecChecks.pop_back(); 8559 } 8560 8561 } else { 8562 ObjCIvarDecl **ClsFields = 8563 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 8564 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 8565 ID->setLocEnd(RBrac); 8566 // Add ivar's to class's DeclContext. 8567 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 8568 ClsFields[i]->setLexicalDeclContext(ID); 8569 ID->addDecl(ClsFields[i]); 8570 } 8571 // Must enforce the rule that ivars in the base classes may not be 8572 // duplicates. 8573 if (ID->getSuperClass()) 8574 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 8575 } else if (ObjCImplementationDecl *IMPDecl = 8576 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 8577 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 8578 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 8579 // Ivar declared in @implementation never belongs to the implementation. 8580 // Only it is in implementation's lexical context. 8581 ClsFields[I]->setLexicalDeclContext(IMPDecl); 8582 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 8583 } else if (ObjCCategoryDecl *CDecl = 8584 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 8585 // case of ivars in class extension; all other cases have been 8586 // reported as errors elsewhere. 8587 // FIXME. Class extension does not have a LocEnd field. 8588 // CDecl->setLocEnd(RBrac); 8589 // Add ivar's to class extension's DeclContext. 8590 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 8591 ClsFields[i]->setLexicalDeclContext(CDecl); 8592 CDecl->addDecl(ClsFields[i]); 8593 } 8594 } 8595 } 8596 8597 if (Attr) 8598 ProcessDeclAttributeList(S, Record, Attr); 8599 8600 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 8601 // set the visibility of this record. 8602 if (Record && !Record->getDeclContext()->isRecord()) 8603 AddPushedVisibilityAttribute(Record); 8604} 8605 8606/// \brief Determine whether the given integral value is representable within 8607/// the given type T. 8608static bool isRepresentableIntegerValue(ASTContext &Context, 8609 llvm::APSInt &Value, 8610 QualType T) { 8611 assert(T->isIntegralType(Context) && "Integral type required!"); 8612 unsigned BitWidth = Context.getIntWidth(T); 8613 8614 if (Value.isUnsigned() || Value.isNonNegative()) { 8615 if (T->isSignedIntegerOrEnumerationType()) 8616 --BitWidth; 8617 return Value.getActiveBits() <= BitWidth; 8618 } 8619 return Value.getMinSignedBits() <= BitWidth; 8620} 8621 8622// \brief Given an integral type, return the next larger integral type 8623// (or a NULL type of no such type exists). 8624static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 8625 // FIXME: Int128/UInt128 support, which also needs to be introduced into 8626 // enum checking below. 8627 assert(T->isIntegralType(Context) && "Integral type required!"); 8628 const unsigned NumTypes = 4; 8629 QualType SignedIntegralTypes[NumTypes] = { 8630 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 8631 }; 8632 QualType UnsignedIntegralTypes[NumTypes] = { 8633 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 8634 Context.UnsignedLongLongTy 8635 }; 8636 8637 unsigned BitWidth = Context.getTypeSize(T); 8638 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 8639 : UnsignedIntegralTypes; 8640 for (unsigned I = 0; I != NumTypes; ++I) 8641 if (Context.getTypeSize(Types[I]) > BitWidth) 8642 return Types[I]; 8643 8644 return QualType(); 8645} 8646 8647EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 8648 EnumConstantDecl *LastEnumConst, 8649 SourceLocation IdLoc, 8650 IdentifierInfo *Id, 8651 Expr *Val) { 8652 unsigned IntWidth = Context.Target.getIntWidth(); 8653 llvm::APSInt EnumVal(IntWidth); 8654 QualType EltTy; 8655 8656 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 8657 Val = 0; 8658 8659 if (Val) { 8660 if (Enum->isDependentType() || Val->isTypeDependent()) 8661 EltTy = Context.DependentTy; 8662 else { 8663 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 8664 SourceLocation ExpLoc; 8665 if (!Val->isValueDependent() && 8666 VerifyIntegerConstantExpression(Val, &EnumVal)) { 8667 Val = 0; 8668 } else { 8669 if (!getLangOptions().CPlusPlus) { 8670 // C99 6.7.2.2p2: 8671 // The expression that defines the value of an enumeration constant 8672 // shall be an integer constant expression that has a value 8673 // representable as an int. 8674 8675 // Complain if the value is not representable in an int. 8676 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 8677 Diag(IdLoc, diag::ext_enum_value_not_int) 8678 << EnumVal.toString(10) << Val->getSourceRange() 8679 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 8680 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 8681 // Force the type of the expression to 'int'. 8682 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 8683 } 8684 } 8685 8686 if (Enum->isFixed()) { 8687 EltTy = Enum->getIntegerType(); 8688 8689 // C++0x [dcl.enum]p5: 8690 // ... if the initializing value of an enumerator cannot be 8691 // represented by the underlying type, the program is ill-formed. 8692 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 8693 if (getLangOptions().Microsoft) { 8694 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 8695 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 8696 } else 8697 Diag(IdLoc, diag::err_enumerator_too_large) 8698 << EltTy; 8699 } else 8700 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 8701 } 8702 else { 8703 // C++0x [dcl.enum]p5: 8704 // If the underlying type is not fixed, the type of each enumerator 8705 // is the type of its initializing value: 8706 // - If an initializer is specified for an enumerator, the 8707 // initializing value has the same type as the expression. 8708 EltTy = Val->getType(); 8709 } 8710 } 8711 } 8712 } 8713 8714 if (!Val) { 8715 if (Enum->isDependentType()) 8716 EltTy = Context.DependentTy; 8717 else if (!LastEnumConst) { 8718 // C++0x [dcl.enum]p5: 8719 // If the underlying type is not fixed, the type of each enumerator 8720 // is the type of its initializing value: 8721 // - If no initializer is specified for the first enumerator, the 8722 // initializing value has an unspecified integral type. 8723 // 8724 // GCC uses 'int' for its unspecified integral type, as does 8725 // C99 6.7.2.2p3. 8726 if (Enum->isFixed()) { 8727 EltTy = Enum->getIntegerType(); 8728 } 8729 else { 8730 EltTy = Context.IntTy; 8731 } 8732 } else { 8733 // Assign the last value + 1. 8734 EnumVal = LastEnumConst->getInitVal(); 8735 ++EnumVal; 8736 EltTy = LastEnumConst->getType(); 8737 8738 // Check for overflow on increment. 8739 if (EnumVal < LastEnumConst->getInitVal()) { 8740 // C++0x [dcl.enum]p5: 8741 // If the underlying type is not fixed, the type of each enumerator 8742 // is the type of its initializing value: 8743 // 8744 // - Otherwise the type of the initializing value is the same as 8745 // the type of the initializing value of the preceding enumerator 8746 // unless the incremented value is not representable in that type, 8747 // in which case the type is an unspecified integral type 8748 // sufficient to contain the incremented value. If no such type 8749 // exists, the program is ill-formed. 8750 QualType T = getNextLargerIntegralType(Context, EltTy); 8751 if (T.isNull() || Enum->isFixed()) { 8752 // There is no integral type larger enough to represent this 8753 // value. Complain, then allow the value to wrap around. 8754 EnumVal = LastEnumConst->getInitVal(); 8755 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 8756 ++EnumVal; 8757 if (Enum->isFixed()) 8758 // When the underlying type is fixed, this is ill-formed. 8759 Diag(IdLoc, diag::err_enumerator_wrapped) 8760 << EnumVal.toString(10) 8761 << EltTy; 8762 else 8763 Diag(IdLoc, diag::warn_enumerator_too_large) 8764 << EnumVal.toString(10); 8765 } else { 8766 EltTy = T; 8767 } 8768 8769 // Retrieve the last enumerator's value, extent that type to the 8770 // type that is supposed to be large enough to represent the incremented 8771 // value, then increment. 8772 EnumVal = LastEnumConst->getInitVal(); 8773 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 8774 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 8775 ++EnumVal; 8776 8777 // If we're not in C++, diagnose the overflow of enumerator values, 8778 // which in C99 means that the enumerator value is not representable in 8779 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 8780 // permits enumerator values that are representable in some larger 8781 // integral type. 8782 if (!getLangOptions().CPlusPlus && !T.isNull()) 8783 Diag(IdLoc, diag::warn_enum_value_overflow); 8784 } else if (!getLangOptions().CPlusPlus && 8785 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 8786 // Enforce C99 6.7.2.2p2 even when we compute the next value. 8787 Diag(IdLoc, diag::ext_enum_value_not_int) 8788 << EnumVal.toString(10) << 1; 8789 } 8790 } 8791 } 8792 8793 if (!EltTy->isDependentType()) { 8794 // Make the enumerator value match the signedness and size of the 8795 // enumerator's type. 8796 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 8797 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 8798 } 8799 8800 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 8801 Val, EnumVal); 8802} 8803 8804 8805Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 8806 SourceLocation IdLoc, IdentifierInfo *Id, 8807 AttributeList *Attr, 8808 SourceLocation EqualLoc, ExprTy *val) { 8809 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 8810 EnumConstantDecl *LastEnumConst = 8811 cast_or_null<EnumConstantDecl>(lastEnumConst); 8812 Expr *Val = static_cast<Expr*>(val); 8813 8814 // The scope passed in may not be a decl scope. Zip up the scope tree until 8815 // we find one that is. 8816 S = getNonFieldDeclScope(S); 8817 8818 // Verify that there isn't already something declared with this name in this 8819 // scope. 8820 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 8821 ForRedeclaration); 8822 if (PrevDecl && PrevDecl->isTemplateParameter()) { 8823 // Maybe we will complain about the shadowed template parameter. 8824 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 8825 // Just pretend that we didn't see the previous declaration. 8826 PrevDecl = 0; 8827 } 8828 8829 if (PrevDecl) { 8830 // When in C++, we may get a TagDecl with the same name; in this case the 8831 // enum constant will 'hide' the tag. 8832 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 8833 "Received TagDecl when not in C++!"); 8834 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 8835 if (isa<EnumConstantDecl>(PrevDecl)) 8836 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 8837 else 8838 Diag(IdLoc, diag::err_redefinition) << Id; 8839 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8840 return 0; 8841 } 8842 } 8843 8844 // C++ [class.mem]p13: 8845 // If T is the name of a class, then each of the following shall have a 8846 // name different from T: 8847 // - every enumerator of every member of class T that is an enumerated 8848 // type 8849 if (CXXRecordDecl *Record 8850 = dyn_cast<CXXRecordDecl>( 8851 TheEnumDecl->getDeclContext()->getRedeclContext())) 8852 if (Record->getIdentifier() && Record->getIdentifier() == Id) 8853 Diag(IdLoc, diag::err_member_name_of_class) << Id; 8854 8855 EnumConstantDecl *New = 8856 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 8857 8858 if (New) { 8859 // Process attributes. 8860 if (Attr) ProcessDeclAttributeList(S, New, Attr); 8861 8862 // Register this decl in the current scope stack. 8863 New->setAccess(TheEnumDecl->getAccess()); 8864 PushOnScopeChains(New, S); 8865 } 8866 8867 return New; 8868} 8869 8870void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 8871 SourceLocation RBraceLoc, Decl *EnumDeclX, 8872 Decl **Elements, unsigned NumElements, 8873 Scope *S, AttributeList *Attr) { 8874 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 8875 QualType EnumType = Context.getTypeDeclType(Enum); 8876 8877 if (Attr) 8878 ProcessDeclAttributeList(S, Enum, Attr); 8879 8880 if (Enum->isDependentType()) { 8881 for (unsigned i = 0; i != NumElements; ++i) { 8882 EnumConstantDecl *ECD = 8883 cast_or_null<EnumConstantDecl>(Elements[i]); 8884 if (!ECD) continue; 8885 8886 ECD->setType(EnumType); 8887 } 8888 8889 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 8890 return; 8891 } 8892 8893 // TODO: If the result value doesn't fit in an int, it must be a long or long 8894 // long value. ISO C does not support this, but GCC does as an extension, 8895 // emit a warning. 8896 unsigned IntWidth = Context.Target.getIntWidth(); 8897 unsigned CharWidth = Context.Target.getCharWidth(); 8898 unsigned ShortWidth = Context.Target.getShortWidth(); 8899 8900 // Verify that all the values are okay, compute the size of the values, and 8901 // reverse the list. 8902 unsigned NumNegativeBits = 0; 8903 unsigned NumPositiveBits = 0; 8904 8905 // Keep track of whether all elements have type int. 8906 bool AllElementsInt = true; 8907 8908 for (unsigned i = 0; i != NumElements; ++i) { 8909 EnumConstantDecl *ECD = 8910 cast_or_null<EnumConstantDecl>(Elements[i]); 8911 if (!ECD) continue; // Already issued a diagnostic. 8912 8913 const llvm::APSInt &InitVal = ECD->getInitVal(); 8914 8915 // Keep track of the size of positive and negative values. 8916 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 8917 NumPositiveBits = std::max(NumPositiveBits, 8918 (unsigned)InitVal.getActiveBits()); 8919 else 8920 NumNegativeBits = std::max(NumNegativeBits, 8921 (unsigned)InitVal.getMinSignedBits()); 8922 8923 // Keep track of whether every enum element has type int (very commmon). 8924 if (AllElementsInt) 8925 AllElementsInt = ECD->getType() == Context.IntTy; 8926 } 8927 8928 // Figure out the type that should be used for this enum. 8929 QualType BestType; 8930 unsigned BestWidth; 8931 8932 // C++0x N3000 [conv.prom]p3: 8933 // An rvalue of an unscoped enumeration type whose underlying 8934 // type is not fixed can be converted to an rvalue of the first 8935 // of the following types that can represent all the values of 8936 // the enumeration: int, unsigned int, long int, unsigned long 8937 // int, long long int, or unsigned long long int. 8938 // C99 6.4.4.3p2: 8939 // An identifier declared as an enumeration constant has type int. 8940 // The C99 rule is modified by a gcc extension 8941 QualType BestPromotionType; 8942 8943 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 8944 // -fshort-enums is the equivalent to specifying the packed attribute on all 8945 // enum definitions. 8946 if (LangOpts.ShortEnums) 8947 Packed = true; 8948 8949 if (Enum->isFixed()) { 8950 BestType = BestPromotionType = Enum->getIntegerType(); 8951 // We don't need to set BestWidth, because BestType is going to be the type 8952 // of the enumerators, but we do anyway because otherwise some compilers 8953 // warn that it might be used uninitialized. 8954 BestWidth = CharWidth; 8955 } 8956 else if (NumNegativeBits) { 8957 // If there is a negative value, figure out the smallest integer type (of 8958 // int/long/longlong) that fits. 8959 // If it's packed, check also if it fits a char or a short. 8960 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 8961 BestType = Context.SignedCharTy; 8962 BestWidth = CharWidth; 8963 } else if (Packed && NumNegativeBits <= ShortWidth && 8964 NumPositiveBits < ShortWidth) { 8965 BestType = Context.ShortTy; 8966 BestWidth = ShortWidth; 8967 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 8968 BestType = Context.IntTy; 8969 BestWidth = IntWidth; 8970 } else { 8971 BestWidth = Context.Target.getLongWidth(); 8972 8973 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 8974 BestType = Context.LongTy; 8975 } else { 8976 BestWidth = Context.Target.getLongLongWidth(); 8977 8978 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 8979 Diag(Enum->getLocation(), diag::warn_enum_too_large); 8980 BestType = Context.LongLongTy; 8981 } 8982 } 8983 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 8984 } else { 8985 // If there is no negative value, figure out the smallest type that fits 8986 // all of the enumerator values. 8987 // If it's packed, check also if it fits a char or a short. 8988 if (Packed && NumPositiveBits <= CharWidth) { 8989 BestType = Context.UnsignedCharTy; 8990 BestPromotionType = Context.IntTy; 8991 BestWidth = CharWidth; 8992 } else if (Packed && NumPositiveBits <= ShortWidth) { 8993 BestType = Context.UnsignedShortTy; 8994 BestPromotionType = Context.IntTy; 8995 BestWidth = ShortWidth; 8996 } else if (NumPositiveBits <= IntWidth) { 8997 BestType = Context.UnsignedIntTy; 8998 BestWidth = IntWidth; 8999 BestPromotionType 9000 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9001 ? Context.UnsignedIntTy : Context.IntTy; 9002 } else if (NumPositiveBits <= 9003 (BestWidth = Context.Target.getLongWidth())) { 9004 BestType = Context.UnsignedLongTy; 9005 BestPromotionType 9006 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9007 ? Context.UnsignedLongTy : Context.LongTy; 9008 } else { 9009 BestWidth = Context.Target.getLongLongWidth(); 9010 assert(NumPositiveBits <= BestWidth && 9011 "How could an initializer get larger than ULL?"); 9012 BestType = Context.UnsignedLongLongTy; 9013 BestPromotionType 9014 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 9015 ? Context.UnsignedLongLongTy : Context.LongLongTy; 9016 } 9017 } 9018 9019 // Loop over all of the enumerator constants, changing their types to match 9020 // the type of the enum if needed. 9021 for (unsigned i = 0; i != NumElements; ++i) { 9022 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 9023 if (!ECD) continue; // Already issued a diagnostic. 9024 9025 // Standard C says the enumerators have int type, but we allow, as an 9026 // extension, the enumerators to be larger than int size. If each 9027 // enumerator value fits in an int, type it as an int, otherwise type it the 9028 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 9029 // that X has type 'int', not 'unsigned'. 9030 9031 // Determine whether the value fits into an int. 9032 llvm::APSInt InitVal = ECD->getInitVal(); 9033 9034 // If it fits into an integer type, force it. Otherwise force it to match 9035 // the enum decl type. 9036 QualType NewTy; 9037 unsigned NewWidth; 9038 bool NewSign; 9039 if (!getLangOptions().CPlusPlus && 9040 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 9041 NewTy = Context.IntTy; 9042 NewWidth = IntWidth; 9043 NewSign = true; 9044 } else if (ECD->getType() == BestType) { 9045 // Already the right type! 9046 if (getLangOptions().CPlusPlus) 9047 // C++ [dcl.enum]p4: Following the closing brace of an 9048 // enum-specifier, each enumerator has the type of its 9049 // enumeration. 9050 ECD->setType(EnumType); 9051 continue; 9052 } else { 9053 NewTy = BestType; 9054 NewWidth = BestWidth; 9055 NewSign = BestType->isSignedIntegerOrEnumerationType(); 9056 } 9057 9058 // Adjust the APSInt value. 9059 InitVal = InitVal.extOrTrunc(NewWidth); 9060 InitVal.setIsSigned(NewSign); 9061 ECD->setInitVal(InitVal); 9062 9063 // Adjust the Expr initializer and type. 9064 if (ECD->getInitExpr() && 9065 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 9066 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 9067 CK_IntegralCast, 9068 ECD->getInitExpr(), 9069 /*base paths*/ 0, 9070 VK_RValue)); 9071 if (getLangOptions().CPlusPlus) 9072 // C++ [dcl.enum]p4: Following the closing brace of an 9073 // enum-specifier, each enumerator has the type of its 9074 // enumeration. 9075 ECD->setType(EnumType); 9076 else 9077 ECD->setType(NewTy); 9078 } 9079 9080 Enum->completeDefinition(BestType, BestPromotionType, 9081 NumPositiveBits, NumNegativeBits); 9082} 9083 9084Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 9085 SourceLocation StartLoc, 9086 SourceLocation EndLoc) { 9087 StringLiteral *AsmString = cast<StringLiteral>(expr); 9088 9089 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 9090 AsmString, StartLoc, 9091 EndLoc); 9092 CurContext->addDecl(New); 9093 return New; 9094} 9095 9096void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 9097 SourceLocation PragmaLoc, 9098 SourceLocation NameLoc) { 9099 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 9100 9101 if (PrevDecl) { 9102 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 9103 } else { 9104 (void)WeakUndeclaredIdentifiers.insert( 9105 std::pair<IdentifierInfo*,WeakInfo> 9106 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 9107 } 9108} 9109 9110void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 9111 IdentifierInfo* AliasName, 9112 SourceLocation PragmaLoc, 9113 SourceLocation NameLoc, 9114 SourceLocation AliasNameLoc) { 9115 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 9116 LookupOrdinaryName); 9117 WeakInfo W = WeakInfo(Name, NameLoc); 9118 9119 if (PrevDecl) { 9120 if (!PrevDecl->hasAttr<AliasAttr>()) 9121 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 9122 DeclApplyPragmaWeak(TUScope, ND, W); 9123 } else { 9124 (void)WeakUndeclaredIdentifiers.insert( 9125 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 9126 } 9127} 9128