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