SemaDecl.cpp revision f30527901f84c9bf223db143b216a9061ee9e342
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 "TypeLocBuilder.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/CommentDiagnostic.h" 21#include "clang/AST/DeclCXX.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/DeclTemplate.h" 24#include "clang/AST/EvaluatedExprVisitor.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/StmtCXX.h" 27#include "clang/Basic/PartialDiagnostic.h" 28#include "clang/Basic/SourceManager.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 31#include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 32#include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 33#include "clang/Parse/ParseDiagnostic.h" 34#include "clang/Sema/CXXFieldCollector.h" 35#include "clang/Sema/DeclSpec.h" 36#include "clang/Sema/DelayedDiagnostic.h" 37#include "clang/Sema/Initialization.h" 38#include "clang/Sema/Lookup.h" 39#include "clang/Sema/ParsedTemplate.h" 40#include "clang/Sema/Scope.h" 41#include "clang/Sema/ScopeInfo.h" 42#include "llvm/ADT/SmallString.h" 43#include "llvm/ADT/Triple.h" 44#include <algorithm> 45#include <cstring> 46#include <functional> 47using namespace clang; 48using namespace sema; 49 50Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 51 if (OwnedType) { 52 Decl *Group[2] = { OwnedType, Ptr }; 53 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 54 } 55 56 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 57} 58 59namespace { 60 61class TypeNameValidatorCCC : public CorrectionCandidateCallback { 62 public: 63 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false) 64 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) { 65 WantExpressionKeywords = false; 66 WantCXXNamedCasts = false; 67 WantRemainingKeywords = false; 68 } 69 70 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 71 if (NamedDecl *ND = candidate.getCorrectionDecl()) 72 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 73 (AllowInvalidDecl || !ND->isInvalidDecl()); 74 else 75 return !WantClassName && candidate.isKeyword(); 76 } 77 78 private: 79 bool AllowInvalidDecl; 80 bool WantClassName; 81}; 82 83} 84 85/// \brief Determine whether the token kind starts a simple-type-specifier. 86bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 87 switch (Kind) { 88 // FIXME: Take into account the current language when deciding whether a 89 // token kind is a valid type specifier 90 case tok::kw_short: 91 case tok::kw_long: 92 case tok::kw___int64: 93 case tok::kw___int128: 94 case tok::kw_signed: 95 case tok::kw_unsigned: 96 case tok::kw_void: 97 case tok::kw_char: 98 case tok::kw_int: 99 case tok::kw_half: 100 case tok::kw_float: 101 case tok::kw_double: 102 case tok::kw_wchar_t: 103 case tok::kw_bool: 104 case tok::kw___underlying_type: 105 return true; 106 107 case tok::annot_typename: 108 case tok::kw_char16_t: 109 case tok::kw_char32_t: 110 case tok::kw_typeof: 111 case tok::kw_decltype: 112 return getLangOpts().CPlusPlus; 113 114 default: 115 break; 116 } 117 118 return false; 119} 120 121/// \brief If the identifier refers to a type name within this scope, 122/// return the declaration of that type. 123/// 124/// This routine performs ordinary name lookup of the identifier II 125/// within the given scope, with optional C++ scope specifier SS, to 126/// determine whether the name refers to a type. If so, returns an 127/// opaque pointer (actually a QualType) corresponding to that 128/// type. Otherwise, returns NULL. 129/// 130/// If name lookup results in an ambiguity, this routine will complain 131/// and then return NULL. 132ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 133 Scope *S, CXXScopeSpec *SS, 134 bool isClassName, bool HasTrailingDot, 135 ParsedType ObjectTypePtr, 136 bool IsCtorOrDtorName, 137 bool WantNontrivialTypeSourceInfo, 138 IdentifierInfo **CorrectedII) { 139 // Determine where we will perform name lookup. 140 DeclContext *LookupCtx = 0; 141 if (ObjectTypePtr) { 142 QualType ObjectType = ObjectTypePtr.get(); 143 if (ObjectType->isRecordType()) 144 LookupCtx = computeDeclContext(ObjectType); 145 } else if (SS && SS->isNotEmpty()) { 146 LookupCtx = computeDeclContext(*SS, false); 147 148 if (!LookupCtx) { 149 if (isDependentScopeSpecifier(*SS)) { 150 // C++ [temp.res]p3: 151 // A qualified-id that refers to a type and in which the 152 // nested-name-specifier depends on a template-parameter (14.6.2) 153 // shall be prefixed by the keyword typename to indicate that the 154 // qualified-id denotes a type, forming an 155 // elaborated-type-specifier (7.1.5.3). 156 // 157 // We therefore do not perform any name lookup if the result would 158 // refer to a member of an unknown specialization. 159 if (!isClassName && !IsCtorOrDtorName) 160 return ParsedType(); 161 162 // We know from the grammar that this name refers to a type, 163 // so build a dependent node to describe the type. 164 if (WantNontrivialTypeSourceInfo) 165 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 166 167 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 168 QualType T = 169 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 170 II, NameLoc); 171 172 return ParsedType::make(T); 173 } 174 175 return ParsedType(); 176 } 177 178 if (!LookupCtx->isDependentContext() && 179 RequireCompleteDeclContext(*SS, LookupCtx)) 180 return ParsedType(); 181 } 182 183 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 184 // lookup for class-names. 185 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 186 LookupOrdinaryName; 187 LookupResult Result(*this, &II, NameLoc, Kind); 188 if (LookupCtx) { 189 // Perform "qualified" name lookup into the declaration context we 190 // computed, which is either the type of the base of a member access 191 // expression or the declaration context associated with a prior 192 // nested-name-specifier. 193 LookupQualifiedName(Result, LookupCtx); 194 195 if (ObjectTypePtr && Result.empty()) { 196 // C++ [basic.lookup.classref]p3: 197 // If the unqualified-id is ~type-name, the type-name is looked up 198 // in the context of the entire postfix-expression. If the type T of 199 // the object expression is of a class type C, the type-name is also 200 // looked up in the scope of class C. At least one of the lookups shall 201 // find a name that refers to (possibly cv-qualified) T. 202 LookupName(Result, S); 203 } 204 } else { 205 // Perform unqualified name lookup. 206 LookupName(Result, S); 207 } 208 209 NamedDecl *IIDecl = 0; 210 switch (Result.getResultKind()) { 211 case LookupResult::NotFound: 212 case LookupResult::NotFoundInCurrentInstantiation: 213 if (CorrectedII) { 214 TypeNameValidatorCCC Validator(true, isClassName); 215 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 216 Kind, S, SS, Validator); 217 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 218 TemplateTy Template; 219 bool MemberOfUnknownSpecialization; 220 UnqualifiedId TemplateName; 221 TemplateName.setIdentifier(NewII, NameLoc); 222 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 223 CXXScopeSpec NewSS, *NewSSPtr = SS; 224 if (SS && NNS) { 225 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 226 NewSSPtr = &NewSS; 227 } 228 if (Correction && (NNS || NewII != &II) && 229 // Ignore a correction to a template type as the to-be-corrected 230 // identifier is not a template (typo correction for template names 231 // is handled elsewhere). 232 !(getLangOpts().CPlusPlus && NewSSPtr && 233 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 234 false, Template, MemberOfUnknownSpecialization))) { 235 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 236 isClassName, HasTrailingDot, ObjectTypePtr, 237 IsCtorOrDtorName, 238 WantNontrivialTypeSourceInfo); 239 if (Ty) { 240 std::string CorrectedStr(Correction.getAsString(getLangOpts())); 241 std::string CorrectedQuotedStr( 242 Correction.getQuoted(getLangOpts())); 243 Diag(NameLoc, diag::err_unknown_type_or_class_name_suggest) 244 << Result.getLookupName() << CorrectedQuotedStr << isClassName 245 << FixItHint::CreateReplacement(SourceRange(NameLoc), 246 CorrectedStr); 247 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 248 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 249 << CorrectedQuotedStr; 250 251 if (SS && NNS) 252 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 253 *CorrectedII = NewII; 254 return Ty; 255 } 256 } 257 } 258 // If typo correction failed or was not performed, fall through 259 case LookupResult::FoundOverloaded: 260 case LookupResult::FoundUnresolvedValue: 261 Result.suppressDiagnostics(); 262 return ParsedType(); 263 264 case LookupResult::Ambiguous: 265 // Recover from type-hiding ambiguities by hiding the type. We'll 266 // do the lookup again when looking for an object, and we can 267 // diagnose the error then. If we don't do this, then the error 268 // about hiding the type will be immediately followed by an error 269 // that only makes sense if the identifier was treated like a type. 270 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 271 Result.suppressDiagnostics(); 272 return ParsedType(); 273 } 274 275 // Look to see if we have a type anywhere in the list of results. 276 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 277 Res != ResEnd; ++Res) { 278 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 279 if (!IIDecl || 280 (*Res)->getLocation().getRawEncoding() < 281 IIDecl->getLocation().getRawEncoding()) 282 IIDecl = *Res; 283 } 284 } 285 286 if (!IIDecl) { 287 // None of the entities we found is a type, so there is no way 288 // to even assume that the result is a type. In this case, don't 289 // complain about the ambiguity. The parser will either try to 290 // perform this lookup again (e.g., as an object name), which 291 // will produce the ambiguity, or will complain that it expected 292 // a type name. 293 Result.suppressDiagnostics(); 294 return ParsedType(); 295 } 296 297 // We found a type within the ambiguous lookup; diagnose the 298 // ambiguity and then return that type. This might be the right 299 // answer, or it might not be, but it suppresses any attempt to 300 // perform the name lookup again. 301 break; 302 303 case LookupResult::Found: 304 IIDecl = Result.getFoundDecl(); 305 break; 306 } 307 308 assert(IIDecl && "Didn't find decl"); 309 310 QualType T; 311 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 312 DiagnoseUseOfDecl(IIDecl, NameLoc); 313 314 if (T.isNull()) 315 T = Context.getTypeDeclType(TD); 316 317 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 318 // constructor or destructor name (in such a case, the scope specifier 319 // will be attached to the enclosing Expr or Decl node). 320 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 321 if (WantNontrivialTypeSourceInfo) { 322 // Construct a type with type-source information. 323 TypeLocBuilder Builder; 324 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 325 326 T = getElaboratedType(ETK_None, *SS, T); 327 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 328 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 329 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 330 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 331 } else { 332 T = getElaboratedType(ETK_None, *SS, T); 333 } 334 } 335 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 336 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 337 if (!HasTrailingDot) 338 T = Context.getObjCInterfaceType(IDecl); 339 } 340 341 if (T.isNull()) { 342 // If it's not plausibly a type, suppress diagnostics. 343 Result.suppressDiagnostics(); 344 return ParsedType(); 345 } 346 return ParsedType::make(T); 347} 348 349/// isTagName() - This method is called *for error recovery purposes only* 350/// to determine if the specified name is a valid tag name ("struct foo"). If 351/// so, this returns the TST for the tag corresponding to it (TST_enum, 352/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 353/// cases in C where the user forgot to specify the tag. 354DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 355 // Do a tag name lookup in this scope. 356 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 357 LookupName(R, S, false); 358 R.suppressDiagnostics(); 359 if (R.getResultKind() == LookupResult::Found) 360 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 361 switch (TD->getTagKind()) { 362 case TTK_Struct: return DeclSpec::TST_struct; 363 case TTK_Interface: return DeclSpec::TST_interface; 364 case TTK_Union: return DeclSpec::TST_union; 365 case TTK_Class: return DeclSpec::TST_class; 366 case TTK_Enum: return DeclSpec::TST_enum; 367 } 368 } 369 370 return DeclSpec::TST_unspecified; 371} 372 373/// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 374/// if a CXXScopeSpec's type is equal to the type of one of the base classes 375/// then downgrade the missing typename error to a warning. 376/// This is needed for MSVC compatibility; Example: 377/// @code 378/// template<class T> class A { 379/// public: 380/// typedef int TYPE; 381/// }; 382/// template<class T> class B : public A<T> { 383/// public: 384/// A<T>::TYPE a; // no typename required because A<T> is a base class. 385/// }; 386/// @endcode 387bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 388 if (CurContext->isRecord()) { 389 const Type *Ty = SS->getScopeRep()->getAsType(); 390 391 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 392 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 393 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 394 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 395 return true; 396 return S->isFunctionPrototypeScope(); 397 } 398 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 399} 400 401bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 402 SourceLocation IILoc, 403 Scope *S, 404 CXXScopeSpec *SS, 405 ParsedType &SuggestedType) { 406 // We don't have anything to suggest (yet). 407 SuggestedType = ParsedType(); 408 409 // There may have been a typo in the name of the type. Look up typo 410 // results, in case we have something that we can suggest. 411 TypeNameValidatorCCC Validator(false); 412 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 413 LookupOrdinaryName, S, SS, 414 Validator)) { 415 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 416 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 417 418 if (Corrected.isKeyword()) { 419 // We corrected to a keyword. 420 IdentifierInfo *NewII = Corrected.getCorrectionAsIdentifierInfo(); 421 if (!isSimpleTypeSpecifier(NewII->getTokenID())) 422 CorrectedQuotedStr = "the keyword " + CorrectedQuotedStr; 423 Diag(IILoc, diag::err_unknown_typename_suggest) 424 << II << CorrectedQuotedStr 425 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 426 II = NewII; 427 } else { 428 NamedDecl *Result = Corrected.getCorrectionDecl(); 429 // We found a similarly-named type or interface; suggest that. 430 if (!SS || !SS->isSet()) 431 Diag(IILoc, diag::err_unknown_typename_suggest) 432 << II << CorrectedQuotedStr 433 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 434 else if (DeclContext *DC = computeDeclContext(*SS, false)) 435 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 436 << II << DC << CorrectedQuotedStr << SS->getRange() 437 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 438 CorrectedStr); 439 else 440 llvm_unreachable("could not have corrected a typo here"); 441 442 Diag(Result->getLocation(), diag::note_previous_decl) 443 << CorrectedQuotedStr; 444 445 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 446 false, false, ParsedType(), 447 /*IsCtorOrDtorName=*/false, 448 /*NonTrivialTypeSourceInfo=*/true); 449 } 450 return true; 451 } 452 453 if (getLangOpts().CPlusPlus) { 454 // See if II is a class template that the user forgot to pass arguments to. 455 UnqualifiedId Name; 456 Name.setIdentifier(II, IILoc); 457 CXXScopeSpec EmptySS; 458 TemplateTy TemplateResult; 459 bool MemberOfUnknownSpecialization; 460 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 461 Name, ParsedType(), true, TemplateResult, 462 MemberOfUnknownSpecialization) == TNK_Type_template) { 463 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 464 Diag(IILoc, diag::err_template_missing_args) << TplName; 465 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 466 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 467 << TplDecl->getTemplateParameters()->getSourceRange(); 468 } 469 return true; 470 } 471 } 472 473 // FIXME: Should we move the logic that tries to recover from a missing tag 474 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 475 476 if (!SS || (!SS->isSet() && !SS->isInvalid())) 477 Diag(IILoc, diag::err_unknown_typename) << II; 478 else if (DeclContext *DC = computeDeclContext(*SS, false)) 479 Diag(IILoc, diag::err_typename_nested_not_found) 480 << II << DC << SS->getRange(); 481 else if (isDependentScopeSpecifier(*SS)) { 482 unsigned DiagID = diag::err_typename_missing; 483 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 484 DiagID = diag::warn_typename_missing; 485 486 Diag(SS->getRange().getBegin(), DiagID) 487 << (NestedNameSpecifier *)SS->getScopeRep() << II->getName() 488 << SourceRange(SS->getRange().getBegin(), IILoc) 489 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 490 SuggestedType = ActOnTypenameType(S, SourceLocation(), 491 *SS, *II, IILoc).get(); 492 } else { 493 assert(SS && SS->isInvalid() && 494 "Invalid scope specifier has already been diagnosed"); 495 } 496 497 return true; 498} 499 500/// \brief Determine whether the given result set contains either a type name 501/// or 502static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 503 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 504 NextToken.is(tok::less); 505 506 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 507 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 508 return true; 509 510 if (CheckTemplate && isa<TemplateDecl>(*I)) 511 return true; 512 } 513 514 return false; 515} 516 517static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 518 Scope *S, CXXScopeSpec &SS, 519 IdentifierInfo *&Name, 520 SourceLocation NameLoc) { 521 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 522 SemaRef.LookupParsedName(R, S, &SS); 523 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 524 const char *TagName = 0; 525 const char *FixItTagName = 0; 526 switch (Tag->getTagKind()) { 527 case TTK_Class: 528 TagName = "class"; 529 FixItTagName = "class "; 530 break; 531 532 case TTK_Enum: 533 TagName = "enum"; 534 FixItTagName = "enum "; 535 break; 536 537 case TTK_Struct: 538 TagName = "struct"; 539 FixItTagName = "struct "; 540 break; 541 542 case TTK_Interface: 543 TagName = "__interface"; 544 FixItTagName = "__interface "; 545 break; 546 547 case TTK_Union: 548 TagName = "union"; 549 FixItTagName = "union "; 550 break; 551 } 552 553 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 554 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 555 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 556 557 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 558 I != IEnd; ++I) 559 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 560 << Name << TagName; 561 562 // Replace lookup results with just the tag decl. 563 Result.clear(Sema::LookupTagName); 564 SemaRef.LookupParsedName(Result, S, &SS); 565 return true; 566 } 567 568 return false; 569} 570 571/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 572static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 573 QualType T, SourceLocation NameLoc) { 574 ASTContext &Context = S.Context; 575 576 TypeLocBuilder Builder; 577 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 578 579 T = S.getElaboratedType(ETK_None, SS, T); 580 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 581 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 582 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 583 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 584} 585 586Sema::NameClassification Sema::ClassifyName(Scope *S, 587 CXXScopeSpec &SS, 588 IdentifierInfo *&Name, 589 SourceLocation NameLoc, 590 const Token &NextToken, 591 bool IsAddressOfOperand, 592 CorrectionCandidateCallback *CCC) { 593 DeclarationNameInfo NameInfo(Name, NameLoc); 594 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 595 596 if (NextToken.is(tok::coloncolon)) { 597 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 598 QualType(), false, SS, 0, false); 599 600 } 601 602 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 603 LookupParsedName(Result, S, &SS, !CurMethod); 604 605 // Perform lookup for Objective-C instance variables (including automatically 606 // synthesized instance variables), if we're in an Objective-C method. 607 // FIXME: This lookup really, really needs to be folded in to the normal 608 // unqualified lookup mechanism. 609 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 610 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 611 if (E.get() || E.isInvalid()) 612 return E; 613 } 614 615 bool SecondTry = false; 616 bool IsFilteredTemplateName = false; 617 618Corrected: 619 switch (Result.getResultKind()) { 620 case LookupResult::NotFound: 621 // If an unqualified-id is followed by a '(', then we have a function 622 // call. 623 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 624 // In C++, this is an ADL-only call. 625 // FIXME: Reference? 626 if (getLangOpts().CPlusPlus) 627 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 628 629 // C90 6.3.2.2: 630 // If the expression that precedes the parenthesized argument list in a 631 // function call consists solely of an identifier, and if no 632 // declaration is visible for this identifier, the identifier is 633 // implicitly declared exactly as if, in the innermost block containing 634 // the function call, the declaration 635 // 636 // extern int identifier (); 637 // 638 // appeared. 639 // 640 // We also allow this in C99 as an extension. 641 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 642 Result.addDecl(D); 643 Result.resolveKind(); 644 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 645 } 646 } 647 648 // In C, we first see whether there is a tag type by the same name, in 649 // which case it's likely that the user just forget to write "enum", 650 // "struct", or "union". 651 if (!getLangOpts().CPlusPlus && !SecondTry && 652 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 653 break; 654 } 655 656 // Perform typo correction to determine if there is another name that is 657 // close to this name. 658 if (!SecondTry && CCC) { 659 SecondTry = true; 660 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 661 Result.getLookupKind(), S, 662 &SS, *CCC)) { 663 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 664 unsigned QualifiedDiag = diag::err_no_member_suggest; 665 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 666 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 667 668 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 669 NamedDecl *UnderlyingFirstDecl 670 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 671 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 672 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 673 UnqualifiedDiag = diag::err_no_template_suggest; 674 QualifiedDiag = diag::err_no_member_template_suggest; 675 } else if (UnderlyingFirstDecl && 676 (isa<TypeDecl>(UnderlyingFirstDecl) || 677 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 678 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 679 UnqualifiedDiag = diag::err_unknown_typename_suggest; 680 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 681 } 682 683 if (SS.isEmpty()) 684 Diag(NameLoc, UnqualifiedDiag) 685 << Name << CorrectedQuotedStr 686 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 687 else // FIXME: is this even reachable? Test it. 688 Diag(NameLoc, QualifiedDiag) 689 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 690 << SS.getRange() 691 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 692 CorrectedStr); 693 694 // Update the name, so that the caller has the new name. 695 Name = Corrected.getCorrectionAsIdentifierInfo(); 696 697 // Typo correction corrected to a keyword. 698 if (Corrected.isKeyword()) 699 return Corrected.getCorrectionAsIdentifierInfo(); 700 701 // Also update the LookupResult... 702 // FIXME: This should probably go away at some point 703 Result.clear(); 704 Result.setLookupName(Corrected.getCorrection()); 705 if (FirstDecl) { 706 Result.addDecl(FirstDecl); 707 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 708 << CorrectedQuotedStr; 709 } 710 711 // If we found an Objective-C instance variable, let 712 // LookupInObjCMethod build the appropriate expression to 713 // reference the ivar. 714 // FIXME: This is a gross hack. 715 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 716 Result.clear(); 717 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 718 return E; 719 } 720 721 goto Corrected; 722 } 723 } 724 725 // We failed to correct; just fall through and let the parser deal with it. 726 Result.suppressDiagnostics(); 727 return NameClassification::Unknown(); 728 729 case LookupResult::NotFoundInCurrentInstantiation: { 730 // We performed name lookup into the current instantiation, and there were 731 // dependent bases, so we treat this result the same way as any other 732 // dependent nested-name-specifier. 733 734 // C++ [temp.res]p2: 735 // A name used in a template declaration or definition and that is 736 // dependent on a template-parameter is assumed not to name a type 737 // unless the applicable name lookup finds a type name or the name is 738 // qualified by the keyword typename. 739 // 740 // FIXME: If the next token is '<', we might want to ask the parser to 741 // perform some heroics to see if we actually have a 742 // template-argument-list, which would indicate a missing 'template' 743 // keyword here. 744 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 745 NameInfo, IsAddressOfOperand, 746 /*TemplateArgs=*/0); 747 } 748 749 case LookupResult::Found: 750 case LookupResult::FoundOverloaded: 751 case LookupResult::FoundUnresolvedValue: 752 break; 753 754 case LookupResult::Ambiguous: 755 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 756 hasAnyAcceptableTemplateNames(Result)) { 757 // C++ [temp.local]p3: 758 // A lookup that finds an injected-class-name (10.2) can result in an 759 // ambiguity in certain cases (for example, if it is found in more than 760 // one base class). If all of the injected-class-names that are found 761 // refer to specializations of the same class template, and if the name 762 // is followed by a template-argument-list, the reference refers to the 763 // class template itself and not a specialization thereof, and is not 764 // ambiguous. 765 // 766 // This filtering can make an ambiguous result into an unambiguous one, 767 // so try again after filtering out template names. 768 FilterAcceptableTemplateNames(Result); 769 if (!Result.isAmbiguous()) { 770 IsFilteredTemplateName = true; 771 break; 772 } 773 } 774 775 // Diagnose the ambiguity and return an error. 776 return NameClassification::Error(); 777 } 778 779 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 780 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 781 // C++ [temp.names]p3: 782 // After name lookup (3.4) finds that a name is a template-name or that 783 // an operator-function-id or a literal- operator-id refers to a set of 784 // overloaded functions any member of which is a function template if 785 // this is followed by a <, the < is always taken as the delimiter of a 786 // template-argument-list and never as the less-than operator. 787 if (!IsFilteredTemplateName) 788 FilterAcceptableTemplateNames(Result); 789 790 if (!Result.empty()) { 791 bool IsFunctionTemplate; 792 TemplateName Template; 793 if (Result.end() - Result.begin() > 1) { 794 IsFunctionTemplate = true; 795 Template = Context.getOverloadedTemplateName(Result.begin(), 796 Result.end()); 797 } else { 798 TemplateDecl *TD 799 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 800 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 801 802 if (SS.isSet() && !SS.isInvalid()) 803 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 804 /*TemplateKeyword=*/false, 805 TD); 806 else 807 Template = TemplateName(TD); 808 } 809 810 if (IsFunctionTemplate) { 811 // Function templates always go through overload resolution, at which 812 // point we'll perform the various checks (e.g., accessibility) we need 813 // to based on which function we selected. 814 Result.suppressDiagnostics(); 815 816 return NameClassification::FunctionTemplate(Template); 817 } 818 819 return NameClassification::TypeTemplate(Template); 820 } 821 } 822 823 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 824 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 825 DiagnoseUseOfDecl(Type, NameLoc); 826 QualType T = Context.getTypeDeclType(Type); 827 if (SS.isNotEmpty()) 828 return buildNestedType(*this, SS, T, NameLoc); 829 return ParsedType::make(T); 830 } 831 832 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 833 if (!Class) { 834 // FIXME: It's unfortunate that we don't have a Type node for handling this. 835 if (ObjCCompatibleAliasDecl *Alias 836 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 837 Class = Alias->getClassInterface(); 838 } 839 840 if (Class) { 841 DiagnoseUseOfDecl(Class, NameLoc); 842 843 if (NextToken.is(tok::period)) { 844 // Interface. <something> is parsed as a property reference expression. 845 // Just return "unknown" as a fall-through for now. 846 Result.suppressDiagnostics(); 847 return NameClassification::Unknown(); 848 } 849 850 QualType T = Context.getObjCInterfaceType(Class); 851 return ParsedType::make(T); 852 } 853 854 // We can have a type template here if we're classifying a template argument. 855 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 856 return NameClassification::TypeTemplate( 857 TemplateName(cast<TemplateDecl>(FirstDecl))); 858 859 // Check for a tag type hidden by a non-type decl in a few cases where it 860 // seems likely a type is wanted instead of the non-type that was found. 861 if (!getLangOpts().ObjC1) { 862 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 863 if ((NextToken.is(tok::identifier) || 864 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 865 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 866 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 867 DiagnoseUseOfDecl(Type, NameLoc); 868 QualType T = Context.getTypeDeclType(Type); 869 if (SS.isNotEmpty()) 870 return buildNestedType(*this, SS, T, NameLoc); 871 return ParsedType::make(T); 872 } 873 } 874 875 if (FirstDecl->isCXXClassMember()) 876 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 877 878 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 879 return BuildDeclarationNameExpr(SS, Result, ADL); 880} 881 882// Determines the context to return to after temporarily entering a 883// context. This depends in an unnecessarily complicated way on the 884// exact ordering of callbacks from the parser. 885DeclContext *Sema::getContainingDC(DeclContext *DC) { 886 887 // Functions defined inline within classes aren't parsed until we've 888 // finished parsing the top-level class, so the top-level class is 889 // the context we'll need to return to. 890 if (isa<FunctionDecl>(DC)) { 891 DC = DC->getLexicalParent(); 892 893 // A function not defined within a class will always return to its 894 // lexical context. 895 if (!isa<CXXRecordDecl>(DC)) 896 return DC; 897 898 // A C++ inline method/friend is parsed *after* the topmost class 899 // it was declared in is fully parsed ("complete"); the topmost 900 // class is the context we need to return to. 901 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 902 DC = RD; 903 904 // Return the declaration context of the topmost class the inline method is 905 // declared in. 906 return DC; 907 } 908 909 return DC->getLexicalParent(); 910} 911 912void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 913 assert(getContainingDC(DC) == CurContext && 914 "The next DeclContext should be lexically contained in the current one."); 915 CurContext = DC; 916 S->setEntity(DC); 917} 918 919void Sema::PopDeclContext() { 920 assert(CurContext && "DeclContext imbalance!"); 921 922 CurContext = getContainingDC(CurContext); 923 assert(CurContext && "Popped translation unit!"); 924} 925 926/// EnterDeclaratorContext - Used when we must lookup names in the context 927/// of a declarator's nested name specifier. 928/// 929void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 930 // C++0x [basic.lookup.unqual]p13: 931 // A name used in the definition of a static data member of class 932 // X (after the qualified-id of the static member) is looked up as 933 // if the name was used in a member function of X. 934 // C++0x [basic.lookup.unqual]p14: 935 // If a variable member of a namespace is defined outside of the 936 // scope of its namespace then any name used in the definition of 937 // the variable member (after the declarator-id) is looked up as 938 // if the definition of the variable member occurred in its 939 // namespace. 940 // Both of these imply that we should push a scope whose context 941 // is the semantic context of the declaration. We can't use 942 // PushDeclContext here because that context is not necessarily 943 // lexically contained in the current context. Fortunately, 944 // the containing scope should have the appropriate information. 945 946 assert(!S->getEntity() && "scope already has entity"); 947 948#ifndef NDEBUG 949 Scope *Ancestor = S->getParent(); 950 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 951 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 952#endif 953 954 CurContext = DC; 955 S->setEntity(DC); 956} 957 958void Sema::ExitDeclaratorContext(Scope *S) { 959 assert(S->getEntity() == CurContext && "Context imbalance!"); 960 961 // Switch back to the lexical context. The safety of this is 962 // enforced by an assert in EnterDeclaratorContext. 963 Scope *Ancestor = S->getParent(); 964 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 965 CurContext = (DeclContext*) Ancestor->getEntity(); 966 967 // We don't need to do anything with the scope, which is going to 968 // disappear. 969} 970 971 972void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 973 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 974 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 975 // We assume that the caller has already called 976 // ActOnReenterTemplateScope 977 FD = TFD->getTemplatedDecl(); 978 } 979 if (!FD) 980 return; 981 982 // Same implementation as PushDeclContext, but enters the context 983 // from the lexical parent, rather than the top-level class. 984 assert(CurContext == FD->getLexicalParent() && 985 "The next DeclContext should be lexically contained in the current one."); 986 CurContext = FD; 987 S->setEntity(CurContext); 988 989 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 990 ParmVarDecl *Param = FD->getParamDecl(P); 991 // If the parameter has an identifier, then add it to the scope 992 if (Param->getIdentifier()) { 993 S->AddDecl(Param); 994 IdResolver.AddDecl(Param); 995 } 996 } 997} 998 999 1000void Sema::ActOnExitFunctionContext() { 1001 // Same implementation as PopDeclContext, but returns to the lexical parent, 1002 // rather than the top-level class. 1003 assert(CurContext && "DeclContext imbalance!"); 1004 CurContext = CurContext->getLexicalParent(); 1005 assert(CurContext && "Popped translation unit!"); 1006} 1007 1008 1009/// \brief Determine whether we allow overloading of the function 1010/// PrevDecl with another declaration. 1011/// 1012/// This routine determines whether overloading is possible, not 1013/// whether some new function is actually an overload. It will return 1014/// true in C++ (where we can always provide overloads) or, as an 1015/// extension, in C when the previous function is already an 1016/// overloaded function declaration or has the "overloadable" 1017/// attribute. 1018static bool AllowOverloadingOfFunction(LookupResult &Previous, 1019 ASTContext &Context) { 1020 if (Context.getLangOpts().CPlusPlus) 1021 return true; 1022 1023 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1024 return true; 1025 1026 return (Previous.getResultKind() == LookupResult::Found 1027 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1028} 1029 1030/// Add this decl to the scope shadowed decl chains. 1031void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1032 // Move up the scope chain until we find the nearest enclosing 1033 // non-transparent context. The declaration will be introduced into this 1034 // scope. 1035 while (S->getEntity() && 1036 ((DeclContext *)S->getEntity())->isTransparentContext()) 1037 S = S->getParent(); 1038 1039 // Add scoped declarations into their context, so that they can be 1040 // found later. Declarations without a context won't be inserted 1041 // into any context. 1042 if (AddToContext) 1043 CurContext->addDecl(D); 1044 1045 // Out-of-line definitions shouldn't be pushed into scope in C++. 1046 // Out-of-line variable and function definitions shouldn't even in C. 1047 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 1048 D->isOutOfLine() && 1049 !D->getDeclContext()->getRedeclContext()->Equals( 1050 D->getLexicalDeclContext()->getRedeclContext())) 1051 return; 1052 1053 // Template instantiations should also not be pushed into scope. 1054 if (isa<FunctionDecl>(D) && 1055 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1056 return; 1057 1058 // If this replaces anything in the current scope, 1059 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1060 IEnd = IdResolver.end(); 1061 for (; I != IEnd; ++I) { 1062 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1063 S->RemoveDecl(*I); 1064 IdResolver.RemoveDecl(*I); 1065 1066 // Should only need to replace one decl. 1067 break; 1068 } 1069 } 1070 1071 S->AddDecl(D); 1072 1073 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1074 // Implicitly-generated labels may end up getting generated in an order that 1075 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1076 // the label at the appropriate place in the identifier chain. 1077 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1078 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1079 if (IDC == CurContext) { 1080 if (!S->isDeclScope(*I)) 1081 continue; 1082 } else if (IDC->Encloses(CurContext)) 1083 break; 1084 } 1085 1086 IdResolver.InsertDeclAfter(I, D); 1087 } else { 1088 IdResolver.AddDecl(D); 1089 } 1090} 1091 1092void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1093 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1094 TUScope->AddDecl(D); 1095} 1096 1097bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 1098 bool ExplicitInstantiationOrSpecialization) { 1099 return IdResolver.isDeclInScope(D, Ctx, S, 1100 ExplicitInstantiationOrSpecialization); 1101} 1102 1103Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1104 DeclContext *TargetDC = DC->getPrimaryContext(); 1105 do { 1106 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 1107 if (ScopeDC->getPrimaryContext() == TargetDC) 1108 return S; 1109 } while ((S = S->getParent())); 1110 1111 return 0; 1112} 1113 1114static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1115 DeclContext*, 1116 ASTContext&); 1117 1118/// Filters out lookup results that don't fall within the given scope 1119/// as determined by isDeclInScope. 1120void Sema::FilterLookupForScope(LookupResult &R, 1121 DeclContext *Ctx, Scope *S, 1122 bool ConsiderLinkage, 1123 bool ExplicitInstantiationOrSpecialization) { 1124 LookupResult::Filter F = R.makeFilter(); 1125 while (F.hasNext()) { 1126 NamedDecl *D = F.next(); 1127 1128 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 1129 continue; 1130 1131 if (ConsiderLinkage && 1132 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1133 continue; 1134 1135 F.erase(); 1136 } 1137 1138 F.done(); 1139} 1140 1141static bool isUsingDecl(NamedDecl *D) { 1142 return isa<UsingShadowDecl>(D) || 1143 isa<UnresolvedUsingTypenameDecl>(D) || 1144 isa<UnresolvedUsingValueDecl>(D); 1145} 1146 1147/// Removes using shadow declarations from the lookup results. 1148static void RemoveUsingDecls(LookupResult &R) { 1149 LookupResult::Filter F = R.makeFilter(); 1150 while (F.hasNext()) 1151 if (isUsingDecl(F.next())) 1152 F.erase(); 1153 1154 F.done(); 1155} 1156 1157/// \brief Check for this common pattern: 1158/// @code 1159/// class S { 1160/// S(const S&); // DO NOT IMPLEMENT 1161/// void operator=(const S&); // DO NOT IMPLEMENT 1162/// }; 1163/// @endcode 1164static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1165 // FIXME: Should check for private access too but access is set after we get 1166 // the decl here. 1167 if (D->doesThisDeclarationHaveABody()) 1168 return false; 1169 1170 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1171 return CD->isCopyConstructor(); 1172 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1173 return Method->isCopyAssignmentOperator(); 1174 return false; 1175} 1176 1177bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1178 assert(D); 1179 1180 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1181 return false; 1182 1183 // Ignore class templates. 1184 if (D->getDeclContext()->isDependentContext() || 1185 D->getLexicalDeclContext()->isDependentContext()) 1186 return false; 1187 1188 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1189 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1190 return false; 1191 1192 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1193 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1194 return false; 1195 } else { 1196 // 'static inline' functions are used in headers; don't warn. 1197 if (FD->getStorageClass() == SC_Static && 1198 FD->isInlineSpecified()) 1199 return false; 1200 } 1201 1202 if (FD->doesThisDeclarationHaveABody() && 1203 Context.DeclMustBeEmitted(FD)) 1204 return false; 1205 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1206 // Don't warn on variables of const-qualified or reference type, since their 1207 // values can be used even if though they're not odr-used, and because const 1208 // qualified variables can appear in headers in contexts where they're not 1209 // intended to be used. 1210 // FIXME: Use more principled rules for these exemptions. 1211 if (!VD->isFileVarDecl() || 1212 VD->getType().isConstQualified() || 1213 VD->getType()->isReferenceType() || 1214 Context.DeclMustBeEmitted(VD)) 1215 return false; 1216 1217 if (VD->isStaticDataMember() && 1218 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1219 return false; 1220 1221 } else { 1222 return false; 1223 } 1224 1225 // Only warn for unused decls internal to the translation unit. 1226 if (D->getLinkage() == ExternalLinkage) 1227 return false; 1228 1229 return true; 1230} 1231 1232void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1233 if (!D) 1234 return; 1235 1236 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1237 const FunctionDecl *First = FD->getFirstDeclaration(); 1238 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1239 return; // First should already be in the vector. 1240 } 1241 1242 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1243 const VarDecl *First = VD->getFirstDeclaration(); 1244 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1245 return; // First should already be in the vector. 1246 } 1247 1248 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1249 UnusedFileScopedDecls.push_back(D); 1250} 1251 1252static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1253 if (D->isInvalidDecl()) 1254 return false; 1255 1256 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1257 return false; 1258 1259 if (isa<LabelDecl>(D)) 1260 return true; 1261 1262 // White-list anything that isn't a local variable. 1263 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1264 !D->getDeclContext()->isFunctionOrMethod()) 1265 return false; 1266 1267 // Types of valid local variables should be complete, so this should succeed. 1268 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1269 1270 // White-list anything with an __attribute__((unused)) type. 1271 QualType Ty = VD->getType(); 1272 1273 // Only look at the outermost level of typedef. 1274 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1275 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1276 return false; 1277 } 1278 1279 // If we failed to complete the type for some reason, or if the type is 1280 // dependent, don't diagnose the variable. 1281 if (Ty->isIncompleteType() || Ty->isDependentType()) 1282 return false; 1283 1284 if (const TagType *TT = Ty->getAs<TagType>()) { 1285 const TagDecl *Tag = TT->getDecl(); 1286 if (Tag->hasAttr<UnusedAttr>()) 1287 return false; 1288 1289 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1290 if (!RD->hasTrivialDestructor()) 1291 return false; 1292 1293 if (const Expr *Init = VD->getInit()) { 1294 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1295 Init = Cleanups->getSubExpr(); 1296 const CXXConstructExpr *Construct = 1297 dyn_cast<CXXConstructExpr>(Init); 1298 if (Construct && !Construct->isElidable()) { 1299 CXXConstructorDecl *CD = Construct->getConstructor(); 1300 if (!CD->isTrivial()) 1301 return false; 1302 } 1303 } 1304 } 1305 } 1306 1307 // TODO: __attribute__((unused)) templates? 1308 } 1309 1310 return true; 1311} 1312 1313static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1314 FixItHint &Hint) { 1315 if (isa<LabelDecl>(D)) { 1316 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1317 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1318 if (AfterColon.isInvalid()) 1319 return; 1320 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1321 getCharRange(D->getLocStart(), AfterColon)); 1322 } 1323 return; 1324} 1325 1326/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1327/// unless they are marked attr(unused). 1328void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1329 FixItHint Hint; 1330 if (!ShouldDiagnoseUnusedDecl(D)) 1331 return; 1332 1333 GenerateFixForUnusedDecl(D, Context, Hint); 1334 1335 unsigned DiagID; 1336 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1337 DiagID = diag::warn_unused_exception_param; 1338 else if (isa<LabelDecl>(D)) 1339 DiagID = diag::warn_unused_label; 1340 else 1341 DiagID = diag::warn_unused_variable; 1342 1343 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1344} 1345 1346static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1347 // Verify that we have no forward references left. If so, there was a goto 1348 // or address of a label taken, but no definition of it. Label fwd 1349 // definitions are indicated with a null substmt. 1350 if (L->getStmt() == 0) 1351 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1352} 1353 1354void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1355 if (S->decl_empty()) return; 1356 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1357 "Scope shouldn't contain decls!"); 1358 1359 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1360 I != E; ++I) { 1361 Decl *TmpD = (*I); 1362 assert(TmpD && "This decl didn't get pushed??"); 1363 1364 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1365 NamedDecl *D = cast<NamedDecl>(TmpD); 1366 1367 if (!D->getDeclName()) continue; 1368 1369 // Diagnose unused variables in this scope. 1370 if (!S->hasErrorOccurred()) 1371 DiagnoseUnusedDecl(D); 1372 1373 // If this was a forward reference to a label, verify it was defined. 1374 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1375 CheckPoppedLabel(LD, *this); 1376 1377 // Remove this name from our lexical scope. 1378 IdResolver.RemoveDecl(D); 1379 } 1380} 1381 1382void Sema::ActOnStartFunctionDeclarator() { 1383 ++InFunctionDeclarator; 1384} 1385 1386void Sema::ActOnEndFunctionDeclarator() { 1387 assert(InFunctionDeclarator); 1388 --InFunctionDeclarator; 1389} 1390 1391/// \brief Look for an Objective-C class in the translation unit. 1392/// 1393/// \param Id The name of the Objective-C class we're looking for. If 1394/// typo-correction fixes this name, the Id will be updated 1395/// to the fixed name. 1396/// 1397/// \param IdLoc The location of the name in the translation unit. 1398/// 1399/// \param DoTypoCorrection If true, this routine will attempt typo correction 1400/// if there is no class with the given name. 1401/// 1402/// \returns The declaration of the named Objective-C class, or NULL if the 1403/// class could not be found. 1404ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1405 SourceLocation IdLoc, 1406 bool DoTypoCorrection) { 1407 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1408 // creation from this context. 1409 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1410 1411 if (!IDecl && DoTypoCorrection) { 1412 // Perform typo correction at the given location, but only if we 1413 // find an Objective-C class name. 1414 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1415 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1416 LookupOrdinaryName, TUScope, NULL, 1417 Validator)) { 1418 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1419 Diag(IdLoc, diag::err_undef_interface_suggest) 1420 << Id << IDecl->getDeclName() 1421 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1422 Diag(IDecl->getLocation(), diag::note_previous_decl) 1423 << IDecl->getDeclName(); 1424 1425 Id = IDecl->getIdentifier(); 1426 } 1427 } 1428 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1429 // This routine must always return a class definition, if any. 1430 if (Def && Def->getDefinition()) 1431 Def = Def->getDefinition(); 1432 return Def; 1433} 1434 1435/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1436/// from S, where a non-field would be declared. This routine copes 1437/// with the difference between C and C++ scoping rules in structs and 1438/// unions. For example, the following code is well-formed in C but 1439/// ill-formed in C++: 1440/// @code 1441/// struct S6 { 1442/// enum { BAR } e; 1443/// }; 1444/// 1445/// void test_S6() { 1446/// struct S6 a; 1447/// a.e = BAR; 1448/// } 1449/// @endcode 1450/// For the declaration of BAR, this routine will return a different 1451/// scope. The scope S will be the scope of the unnamed enumeration 1452/// within S6. In C++, this routine will return the scope associated 1453/// with S6, because the enumeration's scope is a transparent 1454/// context but structures can contain non-field names. In C, this 1455/// routine will return the translation unit scope, since the 1456/// enumeration's scope is a transparent context and structures cannot 1457/// contain non-field names. 1458Scope *Sema::getNonFieldDeclScope(Scope *S) { 1459 while (((S->getFlags() & Scope::DeclScope) == 0) || 1460 (S->getEntity() && 1461 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1462 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1463 S = S->getParent(); 1464 return S; 1465} 1466 1467/// \brief Looks up the declaration of "struct objc_super" and 1468/// saves it for later use in building builtin declaration of 1469/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1470/// pre-existing declaration exists no action takes place. 1471static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1472 IdentifierInfo *II) { 1473 if (!II->isStr("objc_msgSendSuper")) 1474 return; 1475 ASTContext &Context = ThisSema.Context; 1476 1477 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1478 SourceLocation(), Sema::LookupTagName); 1479 ThisSema.LookupName(Result, S); 1480 if (Result.getResultKind() == LookupResult::Found) 1481 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1482 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1483} 1484 1485/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1486/// file scope. lazily create a decl for it. ForRedeclaration is true 1487/// if we're creating this built-in in anticipation of redeclaring the 1488/// built-in. 1489NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1490 Scope *S, bool ForRedeclaration, 1491 SourceLocation Loc) { 1492 LookupPredefedObjCSuperType(*this, S, II); 1493 1494 Builtin::ID BID = (Builtin::ID)bid; 1495 1496 ASTContext::GetBuiltinTypeError Error; 1497 QualType R = Context.GetBuiltinType(BID, Error); 1498 switch (Error) { 1499 case ASTContext::GE_None: 1500 // Okay 1501 break; 1502 1503 case ASTContext::GE_Missing_stdio: 1504 if (ForRedeclaration) 1505 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1506 << Context.BuiltinInfo.GetName(BID); 1507 return 0; 1508 1509 case ASTContext::GE_Missing_setjmp: 1510 if (ForRedeclaration) 1511 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1512 << Context.BuiltinInfo.GetName(BID); 1513 return 0; 1514 1515 case ASTContext::GE_Missing_ucontext: 1516 if (ForRedeclaration) 1517 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1518 << Context.BuiltinInfo.GetName(BID); 1519 return 0; 1520 } 1521 1522 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1523 Diag(Loc, diag::ext_implicit_lib_function_decl) 1524 << Context.BuiltinInfo.GetName(BID) 1525 << R; 1526 if (Context.BuiltinInfo.getHeaderName(BID) && 1527 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1528 != DiagnosticsEngine::Ignored) 1529 Diag(Loc, diag::note_please_include_header) 1530 << Context.BuiltinInfo.getHeaderName(BID) 1531 << Context.BuiltinInfo.GetName(BID); 1532 } 1533 1534 FunctionDecl *New = FunctionDecl::Create(Context, 1535 Context.getTranslationUnitDecl(), 1536 Loc, Loc, II, R, /*TInfo=*/0, 1537 SC_Extern, 1538 SC_None, false, 1539 /*hasPrototype=*/true); 1540 New->setImplicit(); 1541 1542 // Create Decl objects for each parameter, adding them to the 1543 // FunctionDecl. 1544 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1545 SmallVector<ParmVarDecl*, 16> Params; 1546 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1547 ParmVarDecl *parm = 1548 ParmVarDecl::Create(Context, New, SourceLocation(), 1549 SourceLocation(), 0, 1550 FT->getArgType(i), /*TInfo=*/0, 1551 SC_None, SC_None, 0); 1552 parm->setScopeInfo(0, i); 1553 Params.push_back(parm); 1554 } 1555 New->setParams(Params); 1556 } 1557 1558 AddKnownFunctionAttributes(New); 1559 1560 // TUScope is the translation-unit scope to insert this function into. 1561 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1562 // relate Scopes to DeclContexts, and probably eliminate CurContext 1563 // entirely, but we're not there yet. 1564 DeclContext *SavedContext = CurContext; 1565 CurContext = Context.getTranslationUnitDecl(); 1566 PushOnScopeChains(New, TUScope); 1567 CurContext = SavedContext; 1568 return New; 1569} 1570 1571/// \brief Filter out any previous declarations that the given declaration 1572/// should not consider because they are not permitted to conflict, e.g., 1573/// because they come from hidden sub-modules and do not refer to the same 1574/// entity. 1575static void filterNonConflictingPreviousDecls(ASTContext &context, 1576 NamedDecl *decl, 1577 LookupResult &previous){ 1578 // This is only interesting when modules are enabled. 1579 if (!context.getLangOpts().Modules) 1580 return; 1581 1582 // Empty sets are uninteresting. 1583 if (previous.empty()) 1584 return; 1585 1586 // If this declaration has external 1587 bool hasExternalLinkage = (decl->getLinkage() == ExternalLinkage); 1588 1589 LookupResult::Filter filter = previous.makeFilter(); 1590 while (filter.hasNext()) { 1591 NamedDecl *old = filter.next(); 1592 1593 // Non-hidden declarations are never ignored. 1594 if (!old->isHidden()) 1595 continue; 1596 1597 // If either has no-external linkage, ignore the old declaration. 1598 if (!hasExternalLinkage || old->getLinkage() != ExternalLinkage) 1599 filter.erase(); 1600 } 1601 1602 filter.done(); 1603} 1604 1605bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1606 QualType OldType; 1607 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1608 OldType = OldTypedef->getUnderlyingType(); 1609 else 1610 OldType = Context.getTypeDeclType(Old); 1611 QualType NewType = New->getUnderlyingType(); 1612 1613 if (NewType->isVariablyModifiedType()) { 1614 // Must not redefine a typedef with a variably-modified type. 1615 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1616 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1617 << Kind << NewType; 1618 if (Old->getLocation().isValid()) 1619 Diag(Old->getLocation(), diag::note_previous_definition); 1620 New->setInvalidDecl(); 1621 return true; 1622 } 1623 1624 if (OldType != NewType && 1625 !OldType->isDependentType() && 1626 !NewType->isDependentType() && 1627 !Context.hasSameType(OldType, NewType)) { 1628 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1629 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1630 << Kind << NewType << OldType; 1631 if (Old->getLocation().isValid()) 1632 Diag(Old->getLocation(), diag::note_previous_definition); 1633 New->setInvalidDecl(); 1634 return true; 1635 } 1636 return false; 1637} 1638 1639/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1640/// same name and scope as a previous declaration 'Old'. Figure out 1641/// how to resolve this situation, merging decls or emitting 1642/// diagnostics as appropriate. If there was an error, set New to be invalid. 1643/// 1644void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1645 // If the new decl is known invalid already, don't bother doing any 1646 // merging checks. 1647 if (New->isInvalidDecl()) return; 1648 1649 // Allow multiple definitions for ObjC built-in typedefs. 1650 // FIXME: Verify the underlying types are equivalent! 1651 if (getLangOpts().ObjC1) { 1652 const IdentifierInfo *TypeID = New->getIdentifier(); 1653 switch (TypeID->getLength()) { 1654 default: break; 1655 case 2: 1656 { 1657 if (!TypeID->isStr("id")) 1658 break; 1659 QualType T = New->getUnderlyingType(); 1660 if (!T->isPointerType()) 1661 break; 1662 if (!T->isVoidPointerType()) { 1663 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1664 if (!PT->isStructureType()) 1665 break; 1666 } 1667 Context.setObjCIdRedefinitionType(T); 1668 // Install the built-in type for 'id', ignoring the current definition. 1669 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1670 return; 1671 } 1672 case 5: 1673 if (!TypeID->isStr("Class")) 1674 break; 1675 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1676 // Install the built-in type for 'Class', ignoring the current definition. 1677 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1678 return; 1679 case 3: 1680 if (!TypeID->isStr("SEL")) 1681 break; 1682 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1683 // Install the built-in type for 'SEL', ignoring the current definition. 1684 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1685 return; 1686 } 1687 // Fall through - the typedef name was not a builtin type. 1688 } 1689 1690 // Verify the old decl was also a type. 1691 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1692 if (!Old) { 1693 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1694 << New->getDeclName(); 1695 1696 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1697 if (OldD->getLocation().isValid()) 1698 Diag(OldD->getLocation(), diag::note_previous_definition); 1699 1700 return New->setInvalidDecl(); 1701 } 1702 1703 // If the old declaration is invalid, just give up here. 1704 if (Old->isInvalidDecl()) 1705 return New->setInvalidDecl(); 1706 1707 // If the typedef types are not identical, reject them in all languages and 1708 // with any extensions enabled. 1709 if (isIncompatibleTypedef(Old, New)) 1710 return; 1711 1712 // The types match. Link up the redeclaration chain if the old 1713 // declaration was a typedef. 1714 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1715 New->setPreviousDeclaration(Typedef); 1716 1717 if (getLangOpts().MicrosoftExt) 1718 return; 1719 1720 if (getLangOpts().CPlusPlus) { 1721 // C++ [dcl.typedef]p2: 1722 // In a given non-class scope, a typedef specifier can be used to 1723 // redefine the name of any type declared in that scope to refer 1724 // to the type to which it already refers. 1725 if (!isa<CXXRecordDecl>(CurContext)) 1726 return; 1727 1728 // C++0x [dcl.typedef]p4: 1729 // In a given class scope, a typedef specifier can be used to redefine 1730 // any class-name declared in that scope that is not also a typedef-name 1731 // to refer to the type to which it already refers. 1732 // 1733 // This wording came in via DR424, which was a correction to the 1734 // wording in DR56, which accidentally banned code like: 1735 // 1736 // struct S { 1737 // typedef struct A { } A; 1738 // }; 1739 // 1740 // in the C++03 standard. We implement the C++0x semantics, which 1741 // allow the above but disallow 1742 // 1743 // struct S { 1744 // typedef int I; 1745 // typedef int I; 1746 // }; 1747 // 1748 // since that was the intent of DR56. 1749 if (!isa<TypedefNameDecl>(Old)) 1750 return; 1751 1752 Diag(New->getLocation(), diag::err_redefinition) 1753 << New->getDeclName(); 1754 Diag(Old->getLocation(), diag::note_previous_definition); 1755 return New->setInvalidDecl(); 1756 } 1757 1758 // Modules always permit redefinition of typedefs, as does C11. 1759 if (getLangOpts().Modules || getLangOpts().C11) 1760 return; 1761 1762 // If we have a redefinition of a typedef in C, emit a warning. This warning 1763 // is normally mapped to an error, but can be controlled with 1764 // -Wtypedef-redefinition. If either the original or the redefinition is 1765 // in a system header, don't emit this for compatibility with GCC. 1766 if (getDiagnostics().getSuppressSystemWarnings() && 1767 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1768 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1769 return; 1770 1771 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1772 << New->getDeclName(); 1773 Diag(Old->getLocation(), diag::note_previous_definition); 1774 return; 1775} 1776 1777/// DeclhasAttr - returns true if decl Declaration already has the target 1778/// attribute. 1779static bool 1780DeclHasAttr(const Decl *D, const Attr *A) { 1781 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1782 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1783 // responsible for making sure they are consistent. 1784 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1785 if (AA) 1786 return false; 1787 1788 // The following thread safety attributes can also be duplicated. 1789 switch (A->getKind()) { 1790 case attr::ExclusiveLocksRequired: 1791 case attr::SharedLocksRequired: 1792 case attr::LocksExcluded: 1793 case attr::ExclusiveLockFunction: 1794 case attr::SharedLockFunction: 1795 case attr::UnlockFunction: 1796 case attr::ExclusiveTrylockFunction: 1797 case attr::SharedTrylockFunction: 1798 case attr::GuardedBy: 1799 case attr::PtGuardedBy: 1800 case attr::AcquiredBefore: 1801 case attr::AcquiredAfter: 1802 return false; 1803 default: 1804 ; 1805 } 1806 1807 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1808 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1809 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1810 if ((*i)->getKind() == A->getKind()) { 1811 if (Ann) { 1812 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1813 return true; 1814 continue; 1815 } 1816 // FIXME: Don't hardcode this check 1817 if (OA && isa<OwnershipAttr>(*i)) 1818 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1819 return true; 1820 } 1821 1822 return false; 1823} 1824 1825bool Sema::mergeDeclAttribute(NamedDecl *D, InheritableAttr *Attr, 1826 bool Override) { 1827 InheritableAttr *NewAttr = NULL; 1828 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1829 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1830 AA->getIntroduced(), AA->getDeprecated(), 1831 AA->getObsoleted(), AA->getUnavailable(), 1832 AA->getMessage(), Override); 1833 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1834 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility()); 1835 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1836 NewAttr = mergeDLLImportAttr(D, ImportA->getRange()); 1837 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1838 NewAttr = mergeDLLExportAttr(D, ExportA->getRange()); 1839 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1840 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(), 1841 FA->getFormatIdx(), FA->getFirstArg()); 1842 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1843 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName()); 1844 else if (!DeclHasAttr(D, Attr)) 1845 NewAttr = cast<InheritableAttr>(Attr->clone(Context)); 1846 1847 if (NewAttr) { 1848 NewAttr->setInherited(true); 1849 D->addAttr(NewAttr); 1850 return true; 1851 } 1852 1853 return false; 1854} 1855 1856static const Decl *getDefinition(const Decl *D) { 1857 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1858 return TD->getDefinition(); 1859 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 1860 return VD->getDefinition(); 1861 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1862 const FunctionDecl* Def; 1863 if (FD->hasBody(Def)) 1864 return Def; 1865 } 1866 return NULL; 1867} 1868 1869static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1870 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 1871 I != E; ++I) { 1872 Attr *Attribute = *I; 1873 if (Attribute->getKind() == Kind) 1874 return true; 1875 } 1876 return false; 1877} 1878 1879/// checkNewAttributesAfterDef - If we already have a definition, check that 1880/// there are no new attributes in this declaration. 1881static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 1882 if (!New->hasAttrs()) 1883 return; 1884 1885 const Decl *Def = getDefinition(Old); 1886 if (!Def || Def == New) 1887 return; 1888 1889 AttrVec &NewAttributes = New->getAttrs(); 1890 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 1891 const Attr *NewAttribute = NewAttributes[I]; 1892 if (hasAttribute(Def, NewAttribute->getKind())) { 1893 ++I; 1894 continue; // regular attr merging will take care of validating this. 1895 } 1896 S.Diag(NewAttribute->getLocation(), 1897 diag::warn_attribute_precede_definition); 1898 S.Diag(Def->getLocation(), diag::note_previous_definition); 1899 NewAttributes.erase(NewAttributes.begin() + I); 1900 --E; 1901 } 1902} 1903 1904/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 1905void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 1906 AvailabilityMergeKind AMK) { 1907 // attributes declared post-definition are currently ignored 1908 checkNewAttributesAfterDef(*this, New, Old); 1909 1910 if (!Old->hasAttrs()) 1911 return; 1912 1913 bool foundAny = New->hasAttrs(); 1914 1915 // Ensure that any moving of objects within the allocated map is done before 1916 // we process them. 1917 if (!foundAny) New->setAttrs(AttrVec()); 1918 1919 for (specific_attr_iterator<InheritableAttr> 1920 i = Old->specific_attr_begin<InheritableAttr>(), 1921 e = Old->specific_attr_end<InheritableAttr>(); 1922 i != e; ++i) { 1923 bool Override = false; 1924 // Ignore deprecated/unavailable/availability attributes if requested. 1925 if (isa<DeprecatedAttr>(*i) || 1926 isa<UnavailableAttr>(*i) || 1927 isa<AvailabilityAttr>(*i)) { 1928 switch (AMK) { 1929 case AMK_None: 1930 continue; 1931 1932 case AMK_Redeclaration: 1933 break; 1934 1935 case AMK_Override: 1936 Override = true; 1937 break; 1938 } 1939 } 1940 1941 if (mergeDeclAttribute(New, *i, Override)) 1942 foundAny = true; 1943 } 1944 1945 if (!foundAny) New->dropAttrs(); 1946} 1947 1948/// mergeParamDeclAttributes - Copy attributes from the old parameter 1949/// to the new one. 1950static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 1951 const ParmVarDecl *oldDecl, 1952 ASTContext &C) { 1953 if (!oldDecl->hasAttrs()) 1954 return; 1955 1956 bool foundAny = newDecl->hasAttrs(); 1957 1958 // Ensure that any moving of objects within the allocated map is 1959 // done before we process them. 1960 if (!foundAny) newDecl->setAttrs(AttrVec()); 1961 1962 for (specific_attr_iterator<InheritableParamAttr> 1963 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 1964 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 1965 if (!DeclHasAttr(newDecl, *i)) { 1966 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 1967 newAttr->setInherited(true); 1968 newDecl->addAttr(newAttr); 1969 foundAny = true; 1970 } 1971 } 1972 1973 if (!foundAny) newDecl->dropAttrs(); 1974} 1975 1976namespace { 1977 1978/// Used in MergeFunctionDecl to keep track of function parameters in 1979/// C. 1980struct GNUCompatibleParamWarning { 1981 ParmVarDecl *OldParm; 1982 ParmVarDecl *NewParm; 1983 QualType PromotedType; 1984}; 1985 1986} 1987 1988/// getSpecialMember - get the special member enum for a method. 1989Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 1990 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 1991 if (Ctor->isDefaultConstructor()) 1992 return Sema::CXXDefaultConstructor; 1993 1994 if (Ctor->isCopyConstructor()) 1995 return Sema::CXXCopyConstructor; 1996 1997 if (Ctor->isMoveConstructor()) 1998 return Sema::CXXMoveConstructor; 1999 } else if (isa<CXXDestructorDecl>(MD)) { 2000 return Sema::CXXDestructor; 2001 } else if (MD->isCopyAssignmentOperator()) { 2002 return Sema::CXXCopyAssignment; 2003 } else if (MD->isMoveAssignmentOperator()) { 2004 return Sema::CXXMoveAssignment; 2005 } 2006 2007 return Sema::CXXInvalid; 2008} 2009 2010/// canRedefineFunction - checks if a function can be redefined. Currently, 2011/// only extern inline functions can be redefined, and even then only in 2012/// GNU89 mode. 2013static bool canRedefineFunction(const FunctionDecl *FD, 2014 const LangOptions& LangOpts) { 2015 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2016 !LangOpts.CPlusPlus && 2017 FD->isInlineSpecified() && 2018 FD->getStorageClass() == SC_Extern); 2019} 2020 2021/// Is the given calling convention the ABI default for the given 2022/// declaration? 2023static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) { 2024 CallingConv ABIDefaultCC; 2025 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 2026 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic()); 2027 } else { 2028 // Free C function or a static method. 2029 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C); 2030 } 2031 return ABIDefaultCC == CC; 2032} 2033 2034/// MergeFunctionDecl - We just parsed a function 'New' from 2035/// declarator D which has the same name and scope as a previous 2036/// declaration 'Old'. Figure out how to resolve this situation, 2037/// merging decls or emitting diagnostics as appropriate. 2038/// 2039/// In C++, New and Old must be declarations that are not 2040/// overloaded. Use IsOverload to determine whether New and Old are 2041/// overloaded, and to select the Old declaration that New should be 2042/// merged with. 2043/// 2044/// Returns true if there was an error, false otherwise. 2045bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 2046 // Verify the old decl was also a function. 2047 FunctionDecl *Old = 0; 2048 if (FunctionTemplateDecl *OldFunctionTemplate 2049 = dyn_cast<FunctionTemplateDecl>(OldD)) 2050 Old = OldFunctionTemplate->getTemplatedDecl(); 2051 else 2052 Old = dyn_cast<FunctionDecl>(OldD); 2053 if (!Old) { 2054 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2055 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2056 Diag(Shadow->getTargetDecl()->getLocation(), 2057 diag::note_using_decl_target); 2058 Diag(Shadow->getUsingDecl()->getLocation(), 2059 diag::note_using_decl) << 0; 2060 return true; 2061 } 2062 2063 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2064 << New->getDeclName(); 2065 Diag(OldD->getLocation(), diag::note_previous_definition); 2066 return true; 2067 } 2068 2069 // Determine whether the previous declaration was a definition, 2070 // implicit declaration, or a declaration. 2071 diag::kind PrevDiag; 2072 if (Old->isThisDeclarationADefinition()) 2073 PrevDiag = diag::note_previous_definition; 2074 else if (Old->isImplicit()) 2075 PrevDiag = diag::note_previous_implicit_declaration; 2076 else 2077 PrevDiag = diag::note_previous_declaration; 2078 2079 QualType OldQType = Context.getCanonicalType(Old->getType()); 2080 QualType NewQType = Context.getCanonicalType(New->getType()); 2081 2082 // Don't complain about this if we're in GNU89 mode and the old function 2083 // is an extern inline function. 2084 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2085 New->getStorageClass() == SC_Static && 2086 Old->getStorageClass() != SC_Static && 2087 !canRedefineFunction(Old, getLangOpts())) { 2088 if (getLangOpts().MicrosoftExt) { 2089 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2090 Diag(Old->getLocation(), PrevDiag); 2091 } else { 2092 Diag(New->getLocation(), diag::err_static_non_static) << New; 2093 Diag(Old->getLocation(), PrevDiag); 2094 return true; 2095 } 2096 } 2097 2098 // If a function is first declared with a calling convention, but is 2099 // later declared or defined without one, the second decl assumes the 2100 // calling convention of the first. 2101 // 2102 // It's OK if a function is first declared without a calling convention, 2103 // but is later declared or defined with the default calling convention. 2104 // 2105 // For the new decl, we have to look at the NON-canonical type to tell the 2106 // difference between a function that really doesn't have a calling 2107 // convention and one that is declared cdecl. That's because in 2108 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 2109 // because it is the default calling convention. 2110 // 2111 // Note also that we DO NOT return at this point, because we still have 2112 // other tests to run. 2113 const FunctionType *OldType = cast<FunctionType>(OldQType); 2114 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 2115 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2116 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2117 bool RequiresAdjustment = false; 2118 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) { 2119 // Fast path: nothing to do. 2120 2121 // Inherit the CC from the previous declaration if it was specified 2122 // there but not here. 2123 } else if (NewTypeInfo.getCC() == CC_Default) { 2124 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2125 RequiresAdjustment = true; 2126 2127 // Don't complain about mismatches when the default CC is 2128 // effectively the same as the explict one. 2129 } else if (OldTypeInfo.getCC() == CC_Default && 2130 isABIDefaultCC(*this, NewTypeInfo.getCC(), New)) { 2131 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2132 RequiresAdjustment = true; 2133 2134 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 2135 NewTypeInfo.getCC())) { 2136 // Calling conventions really aren't compatible, so complain. 2137 Diag(New->getLocation(), diag::err_cconv_change) 2138 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2139 << (OldTypeInfo.getCC() == CC_Default) 2140 << (OldTypeInfo.getCC() == CC_Default ? "" : 2141 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 2142 Diag(Old->getLocation(), diag::note_previous_declaration); 2143 return true; 2144 } 2145 2146 // FIXME: diagnose the other way around? 2147 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2148 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2149 RequiresAdjustment = true; 2150 } 2151 2152 // Merge regparm attribute. 2153 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2154 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2155 if (NewTypeInfo.getHasRegParm()) { 2156 Diag(New->getLocation(), diag::err_regparm_mismatch) 2157 << NewType->getRegParmType() 2158 << OldType->getRegParmType(); 2159 Diag(Old->getLocation(), diag::note_previous_declaration); 2160 return true; 2161 } 2162 2163 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2164 RequiresAdjustment = true; 2165 } 2166 2167 // Merge ns_returns_retained attribute. 2168 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2169 if (NewTypeInfo.getProducesResult()) { 2170 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2171 Diag(Old->getLocation(), diag::note_previous_declaration); 2172 return true; 2173 } 2174 2175 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2176 RequiresAdjustment = true; 2177 } 2178 2179 if (RequiresAdjustment) { 2180 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 2181 New->setType(QualType(NewType, 0)); 2182 NewQType = Context.getCanonicalType(New->getType()); 2183 } 2184 2185 if (getLangOpts().CPlusPlus) { 2186 // (C++98 13.1p2): 2187 // Certain function declarations cannot be overloaded: 2188 // -- Function declarations that differ only in the return type 2189 // cannot be overloaded. 2190 QualType OldReturnType = OldType->getResultType(); 2191 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2192 QualType ResQT; 2193 if (OldReturnType != NewReturnType) { 2194 if (NewReturnType->isObjCObjectPointerType() 2195 && OldReturnType->isObjCObjectPointerType()) 2196 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2197 if (ResQT.isNull()) { 2198 if (New->isCXXClassMember() && New->isOutOfLine()) 2199 Diag(New->getLocation(), 2200 diag::err_member_def_does_not_match_ret_type) << New; 2201 else 2202 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2203 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2204 return true; 2205 } 2206 else 2207 NewQType = ResQT; 2208 } 2209 2210 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 2211 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 2212 if (OldMethod && NewMethod) { 2213 // Preserve triviality. 2214 NewMethod->setTrivial(OldMethod->isTrivial()); 2215 2216 // MSVC allows explicit template specialization at class scope: 2217 // 2 CXMethodDecls referring to the same function will be injected. 2218 // We don't want a redeclartion error. 2219 bool IsClassScopeExplicitSpecialization = 2220 OldMethod->isFunctionTemplateSpecialization() && 2221 NewMethod->isFunctionTemplateSpecialization(); 2222 bool isFriend = NewMethod->getFriendObjectKind(); 2223 2224 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2225 !IsClassScopeExplicitSpecialization) { 2226 // -- Member function declarations with the same name and the 2227 // same parameter types cannot be overloaded if any of them 2228 // is a static member function declaration. 2229 if (OldMethod->isStatic() || NewMethod->isStatic()) { 2230 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2231 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2232 return true; 2233 } 2234 2235 // C++ [class.mem]p1: 2236 // [...] A member shall not be declared twice in the 2237 // member-specification, except that a nested class or member 2238 // class template can be declared and then later defined. 2239 if (ActiveTemplateInstantiations.empty()) { 2240 unsigned NewDiag; 2241 if (isa<CXXConstructorDecl>(OldMethod)) 2242 NewDiag = diag::err_constructor_redeclared; 2243 else if (isa<CXXDestructorDecl>(NewMethod)) 2244 NewDiag = diag::err_destructor_redeclared; 2245 else if (isa<CXXConversionDecl>(NewMethod)) 2246 NewDiag = diag::err_conv_function_redeclared; 2247 else 2248 NewDiag = diag::err_member_redeclared; 2249 2250 Diag(New->getLocation(), NewDiag); 2251 } else { 2252 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2253 << New << New->getType(); 2254 } 2255 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2256 2257 // Complain if this is an explicit declaration of a special 2258 // member that was initially declared implicitly. 2259 // 2260 // As an exception, it's okay to befriend such methods in order 2261 // to permit the implicit constructor/destructor/operator calls. 2262 } else if (OldMethod->isImplicit()) { 2263 if (isFriend) { 2264 NewMethod->setImplicit(); 2265 } else { 2266 Diag(NewMethod->getLocation(), 2267 diag::err_definition_of_implicitly_declared_member) 2268 << New << getSpecialMember(OldMethod); 2269 return true; 2270 } 2271 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2272 Diag(NewMethod->getLocation(), 2273 diag::err_definition_of_explicitly_defaulted_member) 2274 << getSpecialMember(OldMethod); 2275 return true; 2276 } 2277 } 2278 2279 // C++11 [dcl.attr.noreturn]p1: 2280 // The first declaration of a function shall specify the noreturn 2281 // attribute if any declaration of that function specifies the noreturn 2282 // attribute. 2283 if (New->hasAttr<CXX11NoReturnAttr>() && 2284 !Old->hasAttr<CXX11NoReturnAttr>()) { 2285 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2286 diag::err_noreturn_missing_on_first_decl); 2287 Diag(Old->getFirstDeclaration()->getLocation(), 2288 diag::note_noreturn_missing_first_decl); 2289 } 2290 2291 // (C++98 8.3.5p3): 2292 // All declarations for a function shall agree exactly in both the 2293 // return type and the parameter-type-list. 2294 // We also want to respect all the extended bits except noreturn. 2295 2296 // noreturn should now match unless the old type info didn't have it. 2297 QualType OldQTypeForComparison = OldQType; 2298 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2299 assert(OldQType == QualType(OldType, 0)); 2300 const FunctionType *OldTypeForComparison 2301 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2302 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2303 assert(OldQTypeForComparison.isCanonical()); 2304 } 2305 2306 if (!Old->hasCLanguageLinkage() && New->hasCLanguageLinkage()) { 2307 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2308 Diag(Old->getLocation(), PrevDiag); 2309 return true; 2310 } 2311 2312 if (OldQTypeForComparison == NewQType) 2313 return MergeCompatibleFunctionDecls(New, Old, S); 2314 2315 // Fall through for conflicting redeclarations and redefinitions. 2316 } 2317 2318 // C: Function types need to be compatible, not identical. This handles 2319 // duplicate function decls like "void f(int); void f(enum X);" properly. 2320 if (!getLangOpts().CPlusPlus && 2321 Context.typesAreCompatible(OldQType, NewQType)) { 2322 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2323 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2324 const FunctionProtoType *OldProto = 0; 2325 if (isa<FunctionNoProtoType>(NewFuncType) && 2326 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2327 // The old declaration provided a function prototype, but the 2328 // new declaration does not. Merge in the prototype. 2329 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2330 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2331 OldProto->arg_type_end()); 2332 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2333 ParamTypes.data(), ParamTypes.size(), 2334 OldProto->getExtProtoInfo()); 2335 New->setType(NewQType); 2336 New->setHasInheritedPrototype(); 2337 2338 // Synthesize a parameter for each argument type. 2339 SmallVector<ParmVarDecl*, 16> Params; 2340 for (FunctionProtoType::arg_type_iterator 2341 ParamType = OldProto->arg_type_begin(), 2342 ParamEnd = OldProto->arg_type_end(); 2343 ParamType != ParamEnd; ++ParamType) { 2344 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2345 SourceLocation(), 2346 SourceLocation(), 0, 2347 *ParamType, /*TInfo=*/0, 2348 SC_None, SC_None, 2349 0); 2350 Param->setScopeInfo(0, Params.size()); 2351 Param->setImplicit(); 2352 Params.push_back(Param); 2353 } 2354 2355 New->setParams(Params); 2356 } 2357 2358 return MergeCompatibleFunctionDecls(New, Old, S); 2359 } 2360 2361 // GNU C permits a K&R definition to follow a prototype declaration 2362 // if the declared types of the parameters in the K&R definition 2363 // match the types in the prototype declaration, even when the 2364 // promoted types of the parameters from the K&R definition differ 2365 // from the types in the prototype. GCC then keeps the types from 2366 // the prototype. 2367 // 2368 // If a variadic prototype is followed by a non-variadic K&R definition, 2369 // the K&R definition becomes variadic. This is sort of an edge case, but 2370 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2371 // C99 6.9.1p8. 2372 if (!getLangOpts().CPlusPlus && 2373 Old->hasPrototype() && !New->hasPrototype() && 2374 New->getType()->getAs<FunctionProtoType>() && 2375 Old->getNumParams() == New->getNumParams()) { 2376 SmallVector<QualType, 16> ArgTypes; 2377 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2378 const FunctionProtoType *OldProto 2379 = Old->getType()->getAs<FunctionProtoType>(); 2380 const FunctionProtoType *NewProto 2381 = New->getType()->getAs<FunctionProtoType>(); 2382 2383 // Determine whether this is the GNU C extension. 2384 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2385 NewProto->getResultType()); 2386 bool LooseCompatible = !MergedReturn.isNull(); 2387 for (unsigned Idx = 0, End = Old->getNumParams(); 2388 LooseCompatible && Idx != End; ++Idx) { 2389 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2390 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2391 if (Context.typesAreCompatible(OldParm->getType(), 2392 NewProto->getArgType(Idx))) { 2393 ArgTypes.push_back(NewParm->getType()); 2394 } else if (Context.typesAreCompatible(OldParm->getType(), 2395 NewParm->getType(), 2396 /*CompareUnqualified=*/true)) { 2397 GNUCompatibleParamWarning Warn 2398 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2399 Warnings.push_back(Warn); 2400 ArgTypes.push_back(NewParm->getType()); 2401 } else 2402 LooseCompatible = false; 2403 } 2404 2405 if (LooseCompatible) { 2406 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2407 Diag(Warnings[Warn].NewParm->getLocation(), 2408 diag::ext_param_promoted_not_compatible_with_prototype) 2409 << Warnings[Warn].PromotedType 2410 << Warnings[Warn].OldParm->getType(); 2411 if (Warnings[Warn].OldParm->getLocation().isValid()) 2412 Diag(Warnings[Warn].OldParm->getLocation(), 2413 diag::note_previous_declaration); 2414 } 2415 2416 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 2417 ArgTypes.size(), 2418 OldProto->getExtProtoInfo())); 2419 return MergeCompatibleFunctionDecls(New, Old, S); 2420 } 2421 2422 // Fall through to diagnose conflicting types. 2423 } 2424 2425 // A function that has already been declared has been redeclared or defined 2426 // with a different type- show appropriate diagnostic 2427 if (unsigned BuiltinID = Old->getBuiltinID()) { 2428 // The user has declared a builtin function with an incompatible 2429 // signature. 2430 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2431 // The function the user is redeclaring is a library-defined 2432 // function like 'malloc' or 'printf'. Warn about the 2433 // redeclaration, then pretend that we don't know about this 2434 // library built-in. 2435 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2436 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2437 << Old << Old->getType(); 2438 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2439 Old->setInvalidDecl(); 2440 return false; 2441 } 2442 2443 PrevDiag = diag::note_previous_builtin_declaration; 2444 } 2445 2446 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2447 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2448 return true; 2449} 2450 2451/// \brief Completes the merge of two function declarations that are 2452/// known to be compatible. 2453/// 2454/// This routine handles the merging of attributes and other 2455/// properties of function declarations form the old declaration to 2456/// the new declaration, once we know that New is in fact a 2457/// redeclaration of Old. 2458/// 2459/// \returns false 2460bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2461 Scope *S) { 2462 // Merge the attributes 2463 mergeDeclAttributes(New, Old); 2464 2465 // Merge the storage class. 2466 if (Old->getStorageClass() != SC_Extern && 2467 Old->getStorageClass() != SC_None) 2468 New->setStorageClass(Old->getStorageClass()); 2469 2470 // Merge "pure" flag. 2471 if (Old->isPure()) 2472 New->setPure(); 2473 2474 // Merge "used" flag. 2475 if (Old->isUsed(false)) 2476 New->setUsed(); 2477 2478 // Merge attributes from the parameters. These can mismatch with K&R 2479 // declarations. 2480 if (New->getNumParams() == Old->getNumParams()) 2481 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2482 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2483 Context); 2484 2485 if (getLangOpts().CPlusPlus) 2486 return MergeCXXFunctionDecl(New, Old, S); 2487 2488 // Merge the function types so the we get the composite types for the return 2489 // and argument types. 2490 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2491 if (!Merged.isNull()) 2492 New->setType(Merged); 2493 2494 return false; 2495} 2496 2497 2498void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2499 ObjCMethodDecl *oldMethod) { 2500 2501 // Merge the attributes, including deprecated/unavailable 2502 mergeDeclAttributes(newMethod, oldMethod, AMK_Override); 2503 2504 // Merge attributes from the parameters. 2505 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2506 oe = oldMethod->param_end(); 2507 for (ObjCMethodDecl::param_iterator 2508 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2509 ni != ne && oi != oe; ++ni, ++oi) 2510 mergeParamDeclAttributes(*ni, *oi, Context); 2511 2512 CheckObjCMethodOverride(newMethod, oldMethod); 2513} 2514 2515/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2516/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2517/// emitting diagnostics as appropriate. 2518/// 2519/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2520/// to here in AddInitializerToDecl. We can't check them before the initializer 2521/// is attached. 2522void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2523 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2524 return; 2525 2526 QualType MergedT; 2527 if (getLangOpts().CPlusPlus) { 2528 AutoType *AT = New->getType()->getContainedAutoType(); 2529 if (AT && !AT->isDeduced()) { 2530 // We don't know what the new type is until the initializer is attached. 2531 return; 2532 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2533 // These could still be something that needs exception specs checked. 2534 return MergeVarDeclExceptionSpecs(New, Old); 2535 } 2536 // C++ [basic.link]p10: 2537 // [...] the types specified by all declarations referring to a given 2538 // object or function shall be identical, except that declarations for an 2539 // array object can specify array types that differ by the presence or 2540 // absence of a major array bound (8.3.4). 2541 else if (Old->getType()->isIncompleteArrayType() && 2542 New->getType()->isArrayType()) { 2543 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2544 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2545 if (Context.hasSameType(OldArray->getElementType(), 2546 NewArray->getElementType())) 2547 MergedT = New->getType(); 2548 } else if (Old->getType()->isArrayType() && 2549 New->getType()->isIncompleteArrayType()) { 2550 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2551 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2552 if (Context.hasSameType(OldArray->getElementType(), 2553 NewArray->getElementType())) 2554 MergedT = Old->getType(); 2555 } else if (New->getType()->isObjCObjectPointerType() 2556 && Old->getType()->isObjCObjectPointerType()) { 2557 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2558 Old->getType()); 2559 } 2560 } else { 2561 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2562 } 2563 if (MergedT.isNull()) { 2564 Diag(New->getLocation(), diag::err_redefinition_different_type) 2565 << New->getDeclName() << New->getType() << Old->getType(); 2566 Diag(Old->getLocation(), diag::note_previous_definition); 2567 return New->setInvalidDecl(); 2568 } 2569 New->setType(MergedT); 2570} 2571 2572/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2573/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2574/// situation, merging decls or emitting diagnostics as appropriate. 2575/// 2576/// Tentative definition rules (C99 6.9.2p2) are checked by 2577/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2578/// definitions here, since the initializer hasn't been attached. 2579/// 2580void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2581 // If the new decl is already invalid, don't do any other checking. 2582 if (New->isInvalidDecl()) 2583 return; 2584 2585 // Verify the old decl was also a variable. 2586 VarDecl *Old = 0; 2587 if (!Previous.isSingleResult() || 2588 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2589 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2590 << New->getDeclName(); 2591 Diag(Previous.getRepresentativeDecl()->getLocation(), 2592 diag::note_previous_definition); 2593 return New->setInvalidDecl(); 2594 } 2595 2596 // C++ [class.mem]p1: 2597 // A member shall not be declared twice in the member-specification [...] 2598 // 2599 // Here, we need only consider static data members. 2600 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2601 Diag(New->getLocation(), diag::err_duplicate_member) 2602 << New->getIdentifier(); 2603 Diag(Old->getLocation(), diag::note_previous_declaration); 2604 New->setInvalidDecl(); 2605 } 2606 2607 mergeDeclAttributes(New, Old); 2608 // Warn if an already-declared variable is made a weak_import in a subsequent 2609 // declaration 2610 if (New->getAttr<WeakImportAttr>() && 2611 Old->getStorageClass() == SC_None && 2612 !Old->getAttr<WeakImportAttr>()) { 2613 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2614 Diag(Old->getLocation(), diag::note_previous_definition); 2615 // Remove weak_import attribute on new declaration. 2616 New->dropAttr<WeakImportAttr>(); 2617 } 2618 2619 // Merge the types. 2620 MergeVarDeclTypes(New, Old); 2621 if (New->isInvalidDecl()) 2622 return; 2623 2624 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2625 if (New->getStorageClass() == SC_Static && 2626 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2627 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2628 Diag(Old->getLocation(), diag::note_previous_definition); 2629 return New->setInvalidDecl(); 2630 } 2631 // C99 6.2.2p4: 2632 // For an identifier declared with the storage-class specifier 2633 // extern in a scope in which a prior declaration of that 2634 // identifier is visible,23) if the prior declaration specifies 2635 // internal or external linkage, the linkage of the identifier at 2636 // the later declaration is the same as the linkage specified at 2637 // the prior declaration. If no prior declaration is visible, or 2638 // if the prior declaration specifies no linkage, then the 2639 // identifier has external linkage. 2640 if (New->hasExternalStorage() && Old->hasLinkage()) 2641 /* Okay */; 2642 else if (New->getStorageClass() != SC_Static && 2643 Old->getStorageClass() == SC_Static) { 2644 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2645 Diag(Old->getLocation(), diag::note_previous_definition); 2646 return New->setInvalidDecl(); 2647 } 2648 2649 // Check if extern is followed by non-extern and vice-versa. 2650 if (New->hasExternalStorage() && 2651 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2652 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2653 Diag(Old->getLocation(), diag::note_previous_definition); 2654 return New->setInvalidDecl(); 2655 } 2656 if (Old->hasExternalStorage() && 2657 !New->hasLinkage() && New->isLocalVarDecl()) { 2658 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2659 Diag(Old->getLocation(), diag::note_previous_definition); 2660 return New->setInvalidDecl(); 2661 } 2662 2663 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2664 2665 // FIXME: The test for external storage here seems wrong? We still 2666 // need to check for mismatches. 2667 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2668 // Don't complain about out-of-line definitions of static members. 2669 !(Old->getLexicalDeclContext()->isRecord() && 2670 !New->getLexicalDeclContext()->isRecord())) { 2671 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2672 Diag(Old->getLocation(), diag::note_previous_definition); 2673 return New->setInvalidDecl(); 2674 } 2675 2676 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2677 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2678 Diag(Old->getLocation(), diag::note_previous_definition); 2679 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2680 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2681 Diag(Old->getLocation(), diag::note_previous_definition); 2682 } 2683 2684 // C++ doesn't have tentative definitions, so go right ahead and check here. 2685 const VarDecl *Def; 2686 if (getLangOpts().CPlusPlus && 2687 New->isThisDeclarationADefinition() == VarDecl::Definition && 2688 (Def = Old->getDefinition())) { 2689 Diag(New->getLocation(), diag::err_redefinition) 2690 << New->getDeclName(); 2691 Diag(Def->getLocation(), diag::note_previous_definition); 2692 New->setInvalidDecl(); 2693 return; 2694 } 2695 2696 if (!Old->hasCLanguageLinkage() && New->hasCLanguageLinkage()) { 2697 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2698 Diag(Old->getLocation(), diag::note_previous_definition); 2699 New->setInvalidDecl(); 2700 return; 2701 } 2702 2703 // c99 6.2.2 P4. 2704 // For an identifier declared with the storage-class specifier extern in a 2705 // scope in which a prior declaration of that identifier is visible, if 2706 // the prior declaration specifies internal or external linkage, the linkage 2707 // of the identifier at the later declaration is the same as the linkage 2708 // specified at the prior declaration. 2709 // FIXME. revisit this code. 2710 if (New->hasExternalStorage() && 2711 Old->getLinkage() == InternalLinkage) 2712 New->setStorageClass(Old->getStorageClass()); 2713 2714 // Merge "used" flag. 2715 if (Old->isUsed(false)) 2716 New->setUsed(); 2717 2718 // Keep a chain of previous declarations. 2719 New->setPreviousDeclaration(Old); 2720 2721 // Inherit access appropriately. 2722 New->setAccess(Old->getAccess()); 2723} 2724 2725/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2726/// no declarator (e.g. "struct foo;") is parsed. 2727Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2728 DeclSpec &DS) { 2729 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 2730} 2731 2732/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2733/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2734/// parameters to cope with template friend declarations. 2735Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2736 DeclSpec &DS, 2737 MultiTemplateParamsArg TemplateParams) { 2738 Decl *TagD = 0; 2739 TagDecl *Tag = 0; 2740 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2741 DS.getTypeSpecType() == DeclSpec::TST_struct || 2742 DS.getTypeSpecType() == DeclSpec::TST_interface || 2743 DS.getTypeSpecType() == DeclSpec::TST_union || 2744 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2745 TagD = DS.getRepAsDecl(); 2746 2747 if (!TagD) // We probably had an error 2748 return 0; 2749 2750 // Note that the above type specs guarantee that the 2751 // type rep is a Decl, whereas in many of the others 2752 // it's a Type. 2753 if (isa<TagDecl>(TagD)) 2754 Tag = cast<TagDecl>(TagD); 2755 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 2756 Tag = CTD->getTemplatedDecl(); 2757 } 2758 2759 if (Tag) { 2760 getASTContext().addUnnamedTag(Tag); 2761 Tag->setFreeStanding(); 2762 if (Tag->isInvalidDecl()) 2763 return Tag; 2764 } 2765 2766 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 2767 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 2768 // or incomplete types shall not be restrict-qualified." 2769 if (TypeQuals & DeclSpec::TQ_restrict) 2770 Diag(DS.getRestrictSpecLoc(), 2771 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 2772 << DS.getSourceRange(); 2773 } 2774 2775 if (DS.isConstexprSpecified()) { 2776 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 2777 // and definitions of functions and variables. 2778 if (Tag) 2779 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 2780 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 2781 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 2782 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 2783 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 2784 else 2785 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 2786 // Don't emit warnings after this error. 2787 return TagD; 2788 } 2789 2790 if (DS.isFriendSpecified()) { 2791 // If we're dealing with a decl but not a TagDecl, assume that 2792 // whatever routines created it handled the friendship aspect. 2793 if (TagD && !Tag) 2794 return 0; 2795 return ActOnFriendTypeDecl(S, DS, TemplateParams); 2796 } 2797 2798 // Track whether we warned about the fact that there aren't any 2799 // declarators. 2800 bool emittedWarning = false; 2801 2802 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 2803 if (!Record->getDeclName() && Record->isCompleteDefinition() && 2804 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 2805 if (getLangOpts().CPlusPlus || 2806 Record->getDeclContext()->isRecord()) 2807 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 2808 2809 Diag(DS.getLocStart(), diag::ext_no_declarators) 2810 << DS.getSourceRange(); 2811 emittedWarning = true; 2812 } 2813 } 2814 2815 // Check for Microsoft C extension: anonymous struct. 2816 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 2817 CurContext->isRecord() && 2818 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 2819 // Handle 2 kinds of anonymous struct: 2820 // struct STRUCT; 2821 // and 2822 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 2823 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 2824 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 2825 (DS.getTypeSpecType() == DeclSpec::TST_typename && 2826 DS.getRepAsType().get()->isStructureType())) { 2827 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 2828 << DS.getSourceRange(); 2829 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 2830 } 2831 } 2832 2833 if (getLangOpts().CPlusPlus && 2834 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 2835 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 2836 if (Enum->enumerator_begin() == Enum->enumerator_end() && 2837 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 2838 Diag(Enum->getLocation(), diag::ext_no_declarators) 2839 << DS.getSourceRange(); 2840 emittedWarning = true; 2841 } 2842 2843 // Skip all the checks below if we have a type error. 2844 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 2845 2846 if (!DS.isMissingDeclaratorOk()) { 2847 // Warn about typedefs of enums without names, since this is an 2848 // extension in both Microsoft and GNU. 2849 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 2850 Tag && isa<EnumDecl>(Tag)) { 2851 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 2852 << DS.getSourceRange(); 2853 return Tag; 2854 } 2855 2856 Diag(DS.getLocStart(), diag::ext_no_declarators) 2857 << DS.getSourceRange(); 2858 emittedWarning = true; 2859 } 2860 2861 // We're going to complain about a bunch of spurious specifiers; 2862 // only do this if we're declaring a tag, because otherwise we 2863 // should be getting diag::ext_no_declarators. 2864 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 2865 return TagD; 2866 2867 // Note that a linkage-specification sets a storage class, but 2868 // 'extern "C" struct foo;' is actually valid and not theoretically 2869 // useless. 2870 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 2871 if (!DS.isExternInLinkageSpec()) 2872 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 2873 << DeclSpec::getSpecifierName(scs); 2874 2875 if (DS.isThreadSpecified()) 2876 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 2877 if (DS.getTypeQualifiers()) { 2878 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 2879 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 2880 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 2881 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 2882 // Restrict is covered above. 2883 } 2884 if (DS.isInlineSpecified()) 2885 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 2886 if (DS.isVirtualSpecified()) 2887 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 2888 if (DS.isExplicitSpecified()) 2889 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 2890 2891 if (DS.isModulePrivateSpecified() && 2892 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 2893 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 2894 << Tag->getTagKind() 2895 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 2896 2897 // Warn about ignored type attributes, for example: 2898 // __attribute__((aligned)) struct A; 2899 // Attributes should be placed after tag to apply to type declaration. 2900 if (!DS.getAttributes().empty()) { 2901 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 2902 if (TypeSpecType == DeclSpec::TST_class || 2903 TypeSpecType == DeclSpec::TST_struct || 2904 TypeSpecType == DeclSpec::TST_interface || 2905 TypeSpecType == DeclSpec::TST_union || 2906 TypeSpecType == DeclSpec::TST_enum) { 2907 AttributeList* attrs = DS.getAttributes().getList(); 2908 while (attrs) { 2909 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 2910 << attrs->getName() 2911 << (TypeSpecType == DeclSpec::TST_class ? 0 : 2912 TypeSpecType == DeclSpec::TST_struct ? 1 : 2913 TypeSpecType == DeclSpec::TST_union ? 2 : 2914 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 2915 attrs = attrs->getNext(); 2916 } 2917 } 2918 } 2919 2920 ActOnDocumentableDecl(TagD); 2921 2922 return TagD; 2923} 2924 2925/// We are trying to inject an anonymous member into the given scope; 2926/// check if there's an existing declaration that can't be overloaded. 2927/// 2928/// \return true if this is a forbidden redeclaration 2929static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 2930 Scope *S, 2931 DeclContext *Owner, 2932 DeclarationName Name, 2933 SourceLocation NameLoc, 2934 unsigned diagnostic) { 2935 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 2936 Sema::ForRedeclaration); 2937 if (!SemaRef.LookupName(R, S)) return false; 2938 2939 if (R.getAsSingle<TagDecl>()) 2940 return false; 2941 2942 // Pick a representative declaration. 2943 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 2944 assert(PrevDecl && "Expected a non-null Decl"); 2945 2946 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 2947 return false; 2948 2949 SemaRef.Diag(NameLoc, diagnostic) << Name; 2950 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 2951 2952 return true; 2953} 2954 2955/// InjectAnonymousStructOrUnionMembers - Inject the members of the 2956/// anonymous struct or union AnonRecord into the owning context Owner 2957/// and scope S. This routine will be invoked just after we realize 2958/// that an unnamed union or struct is actually an anonymous union or 2959/// struct, e.g., 2960/// 2961/// @code 2962/// union { 2963/// int i; 2964/// float f; 2965/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 2966/// // f into the surrounding scope.x 2967/// @endcode 2968/// 2969/// This routine is recursive, injecting the names of nested anonymous 2970/// structs/unions into the owning context and scope as well. 2971static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 2972 DeclContext *Owner, 2973 RecordDecl *AnonRecord, 2974 AccessSpecifier AS, 2975 SmallVector<NamedDecl*, 2> &Chaining, 2976 bool MSAnonStruct) { 2977 unsigned diagKind 2978 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 2979 : diag::err_anonymous_struct_member_redecl; 2980 2981 bool Invalid = false; 2982 2983 // Look every FieldDecl and IndirectFieldDecl with a name. 2984 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 2985 DEnd = AnonRecord->decls_end(); 2986 D != DEnd; ++D) { 2987 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 2988 cast<NamedDecl>(*D)->getDeclName()) { 2989 ValueDecl *VD = cast<ValueDecl>(*D); 2990 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 2991 VD->getLocation(), diagKind)) { 2992 // C++ [class.union]p2: 2993 // The names of the members of an anonymous union shall be 2994 // distinct from the names of any other entity in the 2995 // scope in which the anonymous union is declared. 2996 Invalid = true; 2997 } else { 2998 // C++ [class.union]p2: 2999 // For the purpose of name lookup, after the anonymous union 3000 // definition, the members of the anonymous union are 3001 // considered to have been defined in the scope in which the 3002 // anonymous union is declared. 3003 unsigned OldChainingSize = Chaining.size(); 3004 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3005 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3006 PE = IF->chain_end(); PI != PE; ++PI) 3007 Chaining.push_back(*PI); 3008 else 3009 Chaining.push_back(VD); 3010 3011 assert(Chaining.size() >= 2); 3012 NamedDecl **NamedChain = 3013 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3014 for (unsigned i = 0; i < Chaining.size(); i++) 3015 NamedChain[i] = Chaining[i]; 3016 3017 IndirectFieldDecl* IndirectField = 3018 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3019 VD->getIdentifier(), VD->getType(), 3020 NamedChain, Chaining.size()); 3021 3022 IndirectField->setAccess(AS); 3023 IndirectField->setImplicit(); 3024 SemaRef.PushOnScopeChains(IndirectField, S); 3025 3026 // That includes picking up the appropriate access specifier. 3027 if (AS != AS_none) IndirectField->setAccess(AS); 3028 3029 Chaining.resize(OldChainingSize); 3030 } 3031 } 3032 } 3033 3034 return Invalid; 3035} 3036 3037/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3038/// a VarDecl::StorageClass. Any error reporting is up to the caller: 3039/// illegal input values are mapped to SC_None. 3040static StorageClass 3041StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3042 switch (StorageClassSpec) { 3043 case DeclSpec::SCS_unspecified: return SC_None; 3044 case DeclSpec::SCS_extern: return SC_Extern; 3045 case DeclSpec::SCS_static: return SC_Static; 3046 case DeclSpec::SCS_auto: return SC_Auto; 3047 case DeclSpec::SCS_register: return SC_Register; 3048 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3049 // Illegal SCSs map to None: error reporting is up to the caller. 3050 case DeclSpec::SCS_mutable: // Fall through. 3051 case DeclSpec::SCS_typedef: return SC_None; 3052 } 3053 llvm_unreachable("unknown storage class specifier"); 3054} 3055 3056/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 3057/// a StorageClass. Any error reporting is up to the caller: 3058/// illegal input values are mapped to SC_None. 3059static StorageClass 3060StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3061 switch (StorageClassSpec) { 3062 case DeclSpec::SCS_unspecified: return SC_None; 3063 case DeclSpec::SCS_extern: return SC_Extern; 3064 case DeclSpec::SCS_static: return SC_Static; 3065 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3066 // Illegal SCSs map to None: error reporting is up to the caller. 3067 case DeclSpec::SCS_auto: // Fall through. 3068 case DeclSpec::SCS_mutable: // Fall through. 3069 case DeclSpec::SCS_register: // Fall through. 3070 case DeclSpec::SCS_typedef: return SC_None; 3071 } 3072 llvm_unreachable("unknown storage class specifier"); 3073} 3074 3075/// BuildAnonymousStructOrUnion - Handle the declaration of an 3076/// anonymous structure or union. Anonymous unions are a C++ feature 3077/// (C++ [class.union]) and a C11 feature; anonymous structures 3078/// are a C11 feature and GNU C++ extension. 3079Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3080 AccessSpecifier AS, 3081 RecordDecl *Record) { 3082 DeclContext *Owner = Record->getDeclContext(); 3083 3084 // Diagnose whether this anonymous struct/union is an extension. 3085 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3086 Diag(Record->getLocation(), diag::ext_anonymous_union); 3087 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3088 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3089 else if (!Record->isUnion() && !getLangOpts().C11) 3090 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3091 3092 // C and C++ require different kinds of checks for anonymous 3093 // structs/unions. 3094 bool Invalid = false; 3095 if (getLangOpts().CPlusPlus) { 3096 const char* PrevSpec = 0; 3097 unsigned DiagID; 3098 if (Record->isUnion()) { 3099 // C++ [class.union]p6: 3100 // Anonymous unions declared in a named namespace or in the 3101 // global namespace shall be declared static. 3102 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3103 (isa<TranslationUnitDecl>(Owner) || 3104 (isa<NamespaceDecl>(Owner) && 3105 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3106 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3107 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3108 3109 // Recover by adding 'static'. 3110 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3111 PrevSpec, DiagID); 3112 } 3113 // C++ [class.union]p6: 3114 // A storage class is not allowed in a declaration of an 3115 // anonymous union in a class scope. 3116 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3117 isa<RecordDecl>(Owner)) { 3118 Diag(DS.getStorageClassSpecLoc(), 3119 diag::err_anonymous_union_with_storage_spec) 3120 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3121 3122 // Recover by removing the storage specifier. 3123 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3124 SourceLocation(), 3125 PrevSpec, DiagID); 3126 } 3127 } 3128 3129 // Ignore const/volatile/restrict qualifiers. 3130 if (DS.getTypeQualifiers()) { 3131 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3132 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3133 << Record->isUnion() << 0 3134 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3135 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3136 Diag(DS.getVolatileSpecLoc(), 3137 diag::ext_anonymous_struct_union_qualified) 3138 << Record->isUnion() << 1 3139 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3140 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3141 Diag(DS.getRestrictSpecLoc(), 3142 diag::ext_anonymous_struct_union_qualified) 3143 << Record->isUnion() << 2 3144 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3145 3146 DS.ClearTypeQualifiers(); 3147 } 3148 3149 // C++ [class.union]p2: 3150 // The member-specification of an anonymous union shall only 3151 // define non-static data members. [Note: nested types and 3152 // functions cannot be declared within an anonymous union. ] 3153 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3154 MemEnd = Record->decls_end(); 3155 Mem != MemEnd; ++Mem) { 3156 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3157 // C++ [class.union]p3: 3158 // An anonymous union shall not have private or protected 3159 // members (clause 11). 3160 assert(FD->getAccess() != AS_none); 3161 if (FD->getAccess() != AS_public) { 3162 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3163 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3164 Invalid = true; 3165 } 3166 3167 // C++ [class.union]p1 3168 // An object of a class with a non-trivial constructor, a non-trivial 3169 // copy constructor, a non-trivial destructor, or a non-trivial copy 3170 // assignment operator cannot be a member of a union, nor can an 3171 // array of such objects. 3172 if (CheckNontrivialField(FD)) 3173 Invalid = true; 3174 } else if ((*Mem)->isImplicit()) { 3175 // Any implicit members are fine. 3176 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3177 // This is a type that showed up in an 3178 // elaborated-type-specifier inside the anonymous struct or 3179 // union, but which actually declares a type outside of the 3180 // anonymous struct or union. It's okay. 3181 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3182 if (!MemRecord->isAnonymousStructOrUnion() && 3183 MemRecord->getDeclName()) { 3184 // Visual C++ allows type definition in anonymous struct or union. 3185 if (getLangOpts().MicrosoftExt) 3186 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3187 << (int)Record->isUnion(); 3188 else { 3189 // This is a nested type declaration. 3190 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3191 << (int)Record->isUnion(); 3192 Invalid = true; 3193 } 3194 } 3195 } else if (isa<AccessSpecDecl>(*Mem)) { 3196 // Any access specifier is fine. 3197 } else { 3198 // We have something that isn't a non-static data 3199 // member. Complain about it. 3200 unsigned DK = diag::err_anonymous_record_bad_member; 3201 if (isa<TypeDecl>(*Mem)) 3202 DK = diag::err_anonymous_record_with_type; 3203 else if (isa<FunctionDecl>(*Mem)) 3204 DK = diag::err_anonymous_record_with_function; 3205 else if (isa<VarDecl>(*Mem)) 3206 DK = diag::err_anonymous_record_with_static; 3207 3208 // Visual C++ allows type definition in anonymous struct or union. 3209 if (getLangOpts().MicrosoftExt && 3210 DK == diag::err_anonymous_record_with_type) 3211 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3212 << (int)Record->isUnion(); 3213 else { 3214 Diag((*Mem)->getLocation(), DK) 3215 << (int)Record->isUnion(); 3216 Invalid = true; 3217 } 3218 } 3219 } 3220 } 3221 3222 if (!Record->isUnion() && !Owner->isRecord()) { 3223 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3224 << (int)getLangOpts().CPlusPlus; 3225 Invalid = true; 3226 } 3227 3228 // Mock up a declarator. 3229 Declarator Dc(DS, Declarator::MemberContext); 3230 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3231 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3232 3233 // Create a declaration for this anonymous struct/union. 3234 NamedDecl *Anon = 0; 3235 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3236 Anon = FieldDecl::Create(Context, OwningClass, 3237 DS.getLocStart(), 3238 Record->getLocation(), 3239 /*IdentifierInfo=*/0, 3240 Context.getTypeDeclType(Record), 3241 TInfo, 3242 /*BitWidth=*/0, /*Mutable=*/false, 3243 /*InitStyle=*/ICIS_NoInit); 3244 Anon->setAccess(AS); 3245 if (getLangOpts().CPlusPlus) 3246 FieldCollector->Add(cast<FieldDecl>(Anon)); 3247 } else { 3248 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3249 assert(SCSpec != DeclSpec::SCS_typedef && 3250 "Parser allowed 'typedef' as storage class VarDecl."); 3251 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3252 if (SCSpec == DeclSpec::SCS_mutable) { 3253 // mutable can only appear on non-static class members, so it's always 3254 // an error here 3255 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3256 Invalid = true; 3257 SC = SC_None; 3258 } 3259 SCSpec = DS.getStorageClassSpecAsWritten(); 3260 VarDecl::StorageClass SCAsWritten 3261 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3262 3263 Anon = VarDecl::Create(Context, Owner, 3264 DS.getLocStart(), 3265 Record->getLocation(), /*IdentifierInfo=*/0, 3266 Context.getTypeDeclType(Record), 3267 TInfo, SC, SCAsWritten); 3268 3269 // Default-initialize the implicit variable. This initialization will be 3270 // trivial in almost all cases, except if a union member has an in-class 3271 // initializer: 3272 // union { int n = 0; }; 3273 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3274 } 3275 Anon->setImplicit(); 3276 3277 // Add the anonymous struct/union object to the current 3278 // context. We'll be referencing this object when we refer to one of 3279 // its members. 3280 Owner->addDecl(Anon); 3281 3282 // Inject the members of the anonymous struct/union into the owning 3283 // context and into the identifier resolver chain for name lookup 3284 // purposes. 3285 SmallVector<NamedDecl*, 2> Chain; 3286 Chain.push_back(Anon); 3287 3288 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3289 Chain, false)) 3290 Invalid = true; 3291 3292 // Mark this as an anonymous struct/union type. Note that we do not 3293 // do this until after we have already checked and injected the 3294 // members of this anonymous struct/union type, because otherwise 3295 // the members could be injected twice: once by DeclContext when it 3296 // builds its lookup table, and once by 3297 // InjectAnonymousStructOrUnionMembers. 3298 Record->setAnonymousStructOrUnion(true); 3299 3300 if (Invalid) 3301 Anon->setInvalidDecl(); 3302 3303 return Anon; 3304} 3305 3306/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3307/// Microsoft C anonymous structure. 3308/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3309/// Example: 3310/// 3311/// struct A { int a; }; 3312/// struct B { struct A; int b; }; 3313/// 3314/// void foo() { 3315/// B var; 3316/// var.a = 3; 3317/// } 3318/// 3319Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3320 RecordDecl *Record) { 3321 3322 // If there is no Record, get the record via the typedef. 3323 if (!Record) 3324 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3325 3326 // Mock up a declarator. 3327 Declarator Dc(DS, Declarator::TypeNameContext); 3328 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3329 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3330 3331 // Create a declaration for this anonymous struct. 3332 NamedDecl* Anon = FieldDecl::Create(Context, 3333 cast<RecordDecl>(CurContext), 3334 DS.getLocStart(), 3335 DS.getLocStart(), 3336 /*IdentifierInfo=*/0, 3337 Context.getTypeDeclType(Record), 3338 TInfo, 3339 /*BitWidth=*/0, /*Mutable=*/false, 3340 /*InitStyle=*/ICIS_NoInit); 3341 Anon->setImplicit(); 3342 3343 // Add the anonymous struct object to the current context. 3344 CurContext->addDecl(Anon); 3345 3346 // Inject the members of the anonymous struct into the current 3347 // context and into the identifier resolver chain for name lookup 3348 // purposes. 3349 SmallVector<NamedDecl*, 2> Chain; 3350 Chain.push_back(Anon); 3351 3352 RecordDecl *RecordDef = Record->getDefinition(); 3353 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3354 RecordDef, AS_none, 3355 Chain, true)) 3356 Anon->setInvalidDecl(); 3357 3358 return Anon; 3359} 3360 3361/// GetNameForDeclarator - Determine the full declaration name for the 3362/// given Declarator. 3363DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3364 return GetNameFromUnqualifiedId(D.getName()); 3365} 3366 3367/// \brief Retrieves the declaration name from a parsed unqualified-id. 3368DeclarationNameInfo 3369Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3370 DeclarationNameInfo NameInfo; 3371 NameInfo.setLoc(Name.StartLocation); 3372 3373 switch (Name.getKind()) { 3374 3375 case UnqualifiedId::IK_ImplicitSelfParam: 3376 case UnqualifiedId::IK_Identifier: 3377 NameInfo.setName(Name.Identifier); 3378 NameInfo.setLoc(Name.StartLocation); 3379 return NameInfo; 3380 3381 case UnqualifiedId::IK_OperatorFunctionId: 3382 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3383 Name.OperatorFunctionId.Operator)); 3384 NameInfo.setLoc(Name.StartLocation); 3385 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3386 = Name.OperatorFunctionId.SymbolLocations[0]; 3387 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3388 = Name.EndLocation.getRawEncoding(); 3389 return NameInfo; 3390 3391 case UnqualifiedId::IK_LiteralOperatorId: 3392 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3393 Name.Identifier)); 3394 NameInfo.setLoc(Name.StartLocation); 3395 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3396 return NameInfo; 3397 3398 case UnqualifiedId::IK_ConversionFunctionId: { 3399 TypeSourceInfo *TInfo; 3400 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3401 if (Ty.isNull()) 3402 return DeclarationNameInfo(); 3403 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3404 Context.getCanonicalType(Ty))); 3405 NameInfo.setLoc(Name.StartLocation); 3406 NameInfo.setNamedTypeInfo(TInfo); 3407 return NameInfo; 3408 } 3409 3410 case UnqualifiedId::IK_ConstructorName: { 3411 TypeSourceInfo *TInfo; 3412 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3413 if (Ty.isNull()) 3414 return DeclarationNameInfo(); 3415 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3416 Context.getCanonicalType(Ty))); 3417 NameInfo.setLoc(Name.StartLocation); 3418 NameInfo.setNamedTypeInfo(TInfo); 3419 return NameInfo; 3420 } 3421 3422 case UnqualifiedId::IK_ConstructorTemplateId: { 3423 // In well-formed code, we can only have a constructor 3424 // template-id that refers to the current context, so go there 3425 // to find the actual type being constructed. 3426 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3427 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3428 return DeclarationNameInfo(); 3429 3430 // Determine the type of the class being constructed. 3431 QualType CurClassType = Context.getTypeDeclType(CurClass); 3432 3433 // FIXME: Check two things: that the template-id names the same type as 3434 // CurClassType, and that the template-id does not occur when the name 3435 // was qualified. 3436 3437 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3438 Context.getCanonicalType(CurClassType))); 3439 NameInfo.setLoc(Name.StartLocation); 3440 // FIXME: should we retrieve TypeSourceInfo? 3441 NameInfo.setNamedTypeInfo(0); 3442 return NameInfo; 3443 } 3444 3445 case UnqualifiedId::IK_DestructorName: { 3446 TypeSourceInfo *TInfo; 3447 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3448 if (Ty.isNull()) 3449 return DeclarationNameInfo(); 3450 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3451 Context.getCanonicalType(Ty))); 3452 NameInfo.setLoc(Name.StartLocation); 3453 NameInfo.setNamedTypeInfo(TInfo); 3454 return NameInfo; 3455 } 3456 3457 case UnqualifiedId::IK_TemplateId: { 3458 TemplateName TName = Name.TemplateId->Template.get(); 3459 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3460 return Context.getNameForTemplate(TName, TNameLoc); 3461 } 3462 3463 } // switch (Name.getKind()) 3464 3465 llvm_unreachable("Unknown name kind"); 3466} 3467 3468static QualType getCoreType(QualType Ty) { 3469 do { 3470 if (Ty->isPointerType() || Ty->isReferenceType()) 3471 Ty = Ty->getPointeeType(); 3472 else if (Ty->isArrayType()) 3473 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3474 else 3475 return Ty.withoutLocalFastQualifiers(); 3476 } while (true); 3477} 3478 3479/// hasSimilarParameters - Determine whether the C++ functions Declaration 3480/// and Definition have "nearly" matching parameters. This heuristic is 3481/// used to improve diagnostics in the case where an out-of-line function 3482/// definition doesn't match any declaration within the class or namespace. 3483/// Also sets Params to the list of indices to the parameters that differ 3484/// between the declaration and the definition. If hasSimilarParameters 3485/// returns true and Params is empty, then all of the parameters match. 3486static bool hasSimilarParameters(ASTContext &Context, 3487 FunctionDecl *Declaration, 3488 FunctionDecl *Definition, 3489 SmallVectorImpl<unsigned> &Params) { 3490 Params.clear(); 3491 if (Declaration->param_size() != Definition->param_size()) 3492 return false; 3493 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3494 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3495 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3496 3497 // The parameter types are identical 3498 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3499 continue; 3500 3501 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3502 QualType DefParamBaseTy = getCoreType(DefParamTy); 3503 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3504 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3505 3506 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3507 (DeclTyName && DeclTyName == DefTyName)) 3508 Params.push_back(Idx); 3509 else // The two parameters aren't even close 3510 return false; 3511 } 3512 3513 return true; 3514} 3515 3516/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3517/// declarator needs to be rebuilt in the current instantiation. 3518/// Any bits of declarator which appear before the name are valid for 3519/// consideration here. That's specifically the type in the decl spec 3520/// and the base type in any member-pointer chunks. 3521static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3522 DeclarationName Name) { 3523 // The types we specifically need to rebuild are: 3524 // - typenames, typeofs, and decltypes 3525 // - types which will become injected class names 3526 // Of course, we also need to rebuild any type referencing such a 3527 // type. It's safest to just say "dependent", but we call out a 3528 // few cases here. 3529 3530 DeclSpec &DS = D.getMutableDeclSpec(); 3531 switch (DS.getTypeSpecType()) { 3532 case DeclSpec::TST_typename: 3533 case DeclSpec::TST_typeofType: 3534 case DeclSpec::TST_underlyingType: 3535 case DeclSpec::TST_atomic: { 3536 // Grab the type from the parser. 3537 TypeSourceInfo *TSI = 0; 3538 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3539 if (T.isNull() || !T->isDependentType()) break; 3540 3541 // Make sure there's a type source info. This isn't really much 3542 // of a waste; most dependent types should have type source info 3543 // attached already. 3544 if (!TSI) 3545 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3546 3547 // Rebuild the type in the current instantiation. 3548 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3549 if (!TSI) return true; 3550 3551 // Store the new type back in the decl spec. 3552 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3553 DS.UpdateTypeRep(LocType); 3554 break; 3555 } 3556 3557 case DeclSpec::TST_decltype: 3558 case DeclSpec::TST_typeofExpr: { 3559 Expr *E = DS.getRepAsExpr(); 3560 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3561 if (Result.isInvalid()) return true; 3562 DS.UpdateExprRep(Result.get()); 3563 break; 3564 } 3565 3566 default: 3567 // Nothing to do for these decl specs. 3568 break; 3569 } 3570 3571 // It doesn't matter what order we do this in. 3572 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3573 DeclaratorChunk &Chunk = D.getTypeObject(I); 3574 3575 // The only type information in the declarator which can come 3576 // before the declaration name is the base type of a member 3577 // pointer. 3578 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3579 continue; 3580 3581 // Rebuild the scope specifier in-place. 3582 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3583 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3584 return true; 3585 } 3586 3587 return false; 3588} 3589 3590Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3591 D.setFunctionDefinitionKind(FDK_Declaration); 3592 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 3593 3594 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3595 Dcl && Dcl->getDeclContext()->isFileContext()) 3596 Dcl->setTopLevelDeclInObjCContainer(); 3597 3598 return Dcl; 3599} 3600 3601/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3602/// If T is the name of a class, then each of the following shall have a 3603/// name different from T: 3604/// - every static data member of class T; 3605/// - every member function of class T 3606/// - every member of class T that is itself a type; 3607/// \returns true if the declaration name violates these rules. 3608bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3609 DeclarationNameInfo NameInfo) { 3610 DeclarationName Name = NameInfo.getName(); 3611 3612 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3613 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3614 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3615 return true; 3616 } 3617 3618 return false; 3619} 3620 3621/// \brief Diagnose a declaration whose declarator-id has the given 3622/// nested-name-specifier. 3623/// 3624/// \param SS The nested-name-specifier of the declarator-id. 3625/// 3626/// \param DC The declaration context to which the nested-name-specifier 3627/// resolves. 3628/// 3629/// \param Name The name of the entity being declared. 3630/// 3631/// \param Loc The location of the name of the entity being declared. 3632/// 3633/// \returns true if we cannot safely recover from this error, false otherwise. 3634bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3635 DeclarationName Name, 3636 SourceLocation Loc) { 3637 DeclContext *Cur = CurContext; 3638 while (isa<LinkageSpecDecl>(Cur)) 3639 Cur = Cur->getParent(); 3640 3641 // C++ [dcl.meaning]p1: 3642 // A declarator-id shall not be qualified except for the definition 3643 // of a member function (9.3) or static data member (9.4) outside of 3644 // its class, the definition or explicit instantiation of a function 3645 // or variable member of a namespace outside of its namespace, or the 3646 // definition of an explicit specialization outside of its namespace, 3647 // or the declaration of a friend function that is a member of 3648 // another class or namespace (11.3). [...] 3649 3650 // The user provided a superfluous scope specifier that refers back to the 3651 // class or namespaces in which the entity is already declared. 3652 // 3653 // class X { 3654 // void X::f(); 3655 // }; 3656 if (Cur->Equals(DC)) { 3657 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 3658 : diag::err_member_extra_qualification) 3659 << Name << FixItHint::CreateRemoval(SS.getRange()); 3660 SS.clear(); 3661 return false; 3662 } 3663 3664 // Check whether the qualifying scope encloses the scope of the original 3665 // declaration. 3666 if (!Cur->Encloses(DC)) { 3667 if (Cur->isRecord()) 3668 Diag(Loc, diag::err_member_qualification) 3669 << Name << SS.getRange(); 3670 else if (isa<TranslationUnitDecl>(DC)) 3671 Diag(Loc, diag::err_invalid_declarator_global_scope) 3672 << Name << SS.getRange(); 3673 else if (isa<FunctionDecl>(Cur)) 3674 Diag(Loc, diag::err_invalid_declarator_in_function) 3675 << Name << SS.getRange(); 3676 else 3677 Diag(Loc, diag::err_invalid_declarator_scope) 3678 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3679 3680 return true; 3681 } 3682 3683 if (Cur->isRecord()) { 3684 // Cannot qualify members within a class. 3685 Diag(Loc, diag::err_member_qualification) 3686 << Name << SS.getRange(); 3687 SS.clear(); 3688 3689 // C++ constructors and destructors with incorrect scopes can break 3690 // our AST invariants by having the wrong underlying types. If 3691 // that's the case, then drop this declaration entirely. 3692 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3693 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3694 !Context.hasSameType(Name.getCXXNameType(), 3695 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3696 return true; 3697 3698 return false; 3699 } 3700 3701 // C++11 [dcl.meaning]p1: 3702 // [...] "The nested-name-specifier of the qualified declarator-id shall 3703 // not begin with a decltype-specifer" 3704 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3705 while (SpecLoc.getPrefix()) 3706 SpecLoc = SpecLoc.getPrefix(); 3707 if (dyn_cast_or_null<DecltypeType>( 3708 SpecLoc.getNestedNameSpecifier()->getAsType())) 3709 Diag(Loc, diag::err_decltype_in_declarator) 3710 << SpecLoc.getTypeLoc().getSourceRange(); 3711 3712 return false; 3713} 3714 3715NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3716 MultiTemplateParamsArg TemplateParamLists) { 3717 // TODO: consider using NameInfo for diagnostic. 3718 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3719 DeclarationName Name = NameInfo.getName(); 3720 3721 // All of these full declarators require an identifier. If it doesn't have 3722 // one, the ParsedFreeStandingDeclSpec action should be used. 3723 if (!Name) { 3724 if (!D.isInvalidType()) // Reject this if we think it is valid. 3725 Diag(D.getDeclSpec().getLocStart(), 3726 diag::err_declarator_need_ident) 3727 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3728 return 0; 3729 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3730 return 0; 3731 3732 // The scope passed in may not be a decl scope. Zip up the scope tree until 3733 // we find one that is. 3734 while ((S->getFlags() & Scope::DeclScope) == 0 || 3735 (S->getFlags() & Scope::TemplateParamScope) != 0) 3736 S = S->getParent(); 3737 3738 DeclContext *DC = CurContext; 3739 if (D.getCXXScopeSpec().isInvalid()) 3740 D.setInvalidType(); 3741 else if (D.getCXXScopeSpec().isSet()) { 3742 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 3743 UPPC_DeclarationQualifier)) 3744 return 0; 3745 3746 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 3747 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 3748 if (!DC) { 3749 // If we could not compute the declaration context, it's because the 3750 // declaration context is dependent but does not refer to a class, 3751 // class template, or class template partial specialization. Complain 3752 // and return early, to avoid the coming semantic disaster. 3753 Diag(D.getIdentifierLoc(), 3754 diag::err_template_qualified_declarator_no_match) 3755 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 3756 << D.getCXXScopeSpec().getRange(); 3757 return 0; 3758 } 3759 bool IsDependentContext = DC->isDependentContext(); 3760 3761 if (!IsDependentContext && 3762 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 3763 return 0; 3764 3765 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 3766 Diag(D.getIdentifierLoc(), 3767 diag::err_member_def_undefined_record) 3768 << Name << DC << D.getCXXScopeSpec().getRange(); 3769 D.setInvalidType(); 3770 } else if (!D.getDeclSpec().isFriendSpecified()) { 3771 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 3772 Name, D.getIdentifierLoc())) { 3773 if (DC->isRecord()) 3774 return 0; 3775 3776 D.setInvalidType(); 3777 } 3778 } 3779 3780 // Check whether we need to rebuild the type of the given 3781 // declaration in the current instantiation. 3782 if (EnteringContext && IsDependentContext && 3783 TemplateParamLists.size() != 0) { 3784 ContextRAII SavedContext(*this, DC); 3785 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 3786 D.setInvalidType(); 3787 } 3788 } 3789 3790 if (DiagnoseClassNameShadow(DC, NameInfo)) 3791 // If this is a typedef, we'll end up spewing multiple diagnostics. 3792 // Just return early; it's safer. 3793 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3794 return 0; 3795 3796 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3797 QualType R = TInfo->getType(); 3798 3799 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 3800 UPPC_DeclarationType)) 3801 D.setInvalidType(); 3802 3803 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 3804 ForRedeclaration); 3805 3806 // See if this is a redefinition of a variable in the same scope. 3807 if (!D.getCXXScopeSpec().isSet()) { 3808 bool IsLinkageLookup = false; 3809 3810 // If the declaration we're planning to build will be a function 3811 // or object with linkage, then look for another declaration with 3812 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 3813 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 3814 /* Do nothing*/; 3815 else if (R->isFunctionType()) { 3816 if (CurContext->isFunctionOrMethod() || 3817 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3818 IsLinkageLookup = true; 3819 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 3820 IsLinkageLookup = true; 3821 else if (CurContext->getRedeclContext()->isTranslationUnit() && 3822 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 3823 IsLinkageLookup = true; 3824 3825 if (IsLinkageLookup) 3826 Previous.clear(LookupRedeclarationWithLinkage); 3827 3828 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 3829 } else { // Something like "int foo::x;" 3830 LookupQualifiedName(Previous, DC); 3831 3832 // C++ [dcl.meaning]p1: 3833 // When the declarator-id is qualified, the declaration shall refer to a 3834 // previously declared member of the class or namespace to which the 3835 // qualifier refers (or, in the case of a namespace, of an element of the 3836 // inline namespace set of that namespace (7.3.1)) or to a specialization 3837 // thereof; [...] 3838 // 3839 // Note that we already checked the context above, and that we do not have 3840 // enough information to make sure that Previous contains the declaration 3841 // we want to match. For example, given: 3842 // 3843 // class X { 3844 // void f(); 3845 // void f(float); 3846 // }; 3847 // 3848 // void X::f(int) { } // ill-formed 3849 // 3850 // In this case, Previous will point to the overload set 3851 // containing the two f's declared in X, but neither of them 3852 // matches. 3853 3854 // C++ [dcl.meaning]p1: 3855 // [...] the member shall not merely have been introduced by a 3856 // using-declaration in the scope of the class or namespace nominated by 3857 // the nested-name-specifier of the declarator-id. 3858 RemoveUsingDecls(Previous); 3859 } 3860 3861 if (Previous.isSingleResult() && 3862 Previous.getFoundDecl()->isTemplateParameter()) { 3863 // Maybe we will complain about the shadowed template parameter. 3864 if (!D.isInvalidType()) 3865 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 3866 Previous.getFoundDecl()); 3867 3868 // Just pretend that we didn't see the previous declaration. 3869 Previous.clear(); 3870 } 3871 3872 // In C++, the previous declaration we find might be a tag type 3873 // (class or enum). In this case, the new declaration will hide the 3874 // tag type. Note that this does does not apply if we're declaring a 3875 // typedef (C++ [dcl.typedef]p4). 3876 if (Previous.isSingleTagDecl() && 3877 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 3878 Previous.clear(); 3879 3880 NamedDecl *New; 3881 3882 bool AddToScope = true; 3883 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 3884 if (TemplateParamLists.size()) { 3885 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 3886 return 0; 3887 } 3888 3889 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 3890 } else if (R->isFunctionType()) { 3891 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 3892 TemplateParamLists, 3893 AddToScope); 3894 } else { 3895 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 3896 TemplateParamLists); 3897 } 3898 3899 if (New == 0) 3900 return 0; 3901 3902 // If this has an identifier and is not an invalid redeclaration or 3903 // function template specialization, add it to the scope stack. 3904 if (New->getDeclName() && AddToScope && 3905 !(D.isRedeclaration() && New->isInvalidDecl())) 3906 PushOnScopeChains(New, S); 3907 3908 return New; 3909} 3910 3911/// Helper method to turn variable array types into constant array 3912/// types in certain situations which would otherwise be errors (for 3913/// GCC compatibility). 3914static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3915 ASTContext &Context, 3916 bool &SizeIsNegative, 3917 llvm::APSInt &Oversized) { 3918 // This method tries to turn a variable array into a constant 3919 // array even when the size isn't an ICE. This is necessary 3920 // for compatibility with code that depends on gcc's buggy 3921 // constant expression folding, like struct {char x[(int)(char*)2];} 3922 SizeIsNegative = false; 3923 Oversized = 0; 3924 3925 if (T->isDependentType()) 3926 return QualType(); 3927 3928 QualifierCollector Qs; 3929 const Type *Ty = Qs.strip(T); 3930 3931 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 3932 QualType Pointee = PTy->getPointeeType(); 3933 QualType FixedType = 3934 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 3935 Oversized); 3936 if (FixedType.isNull()) return FixedType; 3937 FixedType = Context.getPointerType(FixedType); 3938 return Qs.apply(Context, FixedType); 3939 } 3940 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 3941 QualType Inner = PTy->getInnerType(); 3942 QualType FixedType = 3943 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 3944 Oversized); 3945 if (FixedType.isNull()) return FixedType; 3946 FixedType = Context.getParenType(FixedType); 3947 return Qs.apply(Context, FixedType); 3948 } 3949 3950 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3951 if (!VLATy) 3952 return QualType(); 3953 // FIXME: We should probably handle this case 3954 if (VLATy->getElementType()->isVariablyModifiedType()) 3955 return QualType(); 3956 3957 llvm::APSInt Res; 3958 if (!VLATy->getSizeExpr() || 3959 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 3960 return QualType(); 3961 3962 // Check whether the array size is negative. 3963 if (Res.isSigned() && Res.isNegative()) { 3964 SizeIsNegative = true; 3965 return QualType(); 3966 } 3967 3968 // Check whether the array is too large to be addressed. 3969 unsigned ActiveSizeBits 3970 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 3971 Res); 3972 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 3973 Oversized = Res; 3974 return QualType(); 3975 } 3976 3977 return Context.getConstantArrayType(VLATy->getElementType(), 3978 Res, ArrayType::Normal, 0); 3979} 3980 3981static void 3982FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 3983 if (PointerTypeLoc* SrcPTL = dyn_cast<PointerTypeLoc>(&SrcTL)) { 3984 PointerTypeLoc* DstPTL = cast<PointerTypeLoc>(&DstTL); 3985 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getPointeeLoc(), 3986 DstPTL->getPointeeLoc()); 3987 DstPTL->setStarLoc(SrcPTL->getStarLoc()); 3988 return; 3989 } 3990 if (ParenTypeLoc* SrcPTL = dyn_cast<ParenTypeLoc>(&SrcTL)) { 3991 ParenTypeLoc* DstPTL = cast<ParenTypeLoc>(&DstTL); 3992 FixInvalidVariablyModifiedTypeLoc(SrcPTL->getInnerLoc(), 3993 DstPTL->getInnerLoc()); 3994 DstPTL->setLParenLoc(SrcPTL->getLParenLoc()); 3995 DstPTL->setRParenLoc(SrcPTL->getRParenLoc()); 3996 return; 3997 } 3998 ArrayTypeLoc* SrcATL = cast<ArrayTypeLoc>(&SrcTL); 3999 ArrayTypeLoc* DstATL = cast<ArrayTypeLoc>(&DstTL); 4000 TypeLoc SrcElemTL = SrcATL->getElementLoc(); 4001 TypeLoc DstElemTL = DstATL->getElementLoc(); 4002 DstElemTL.initializeFullCopy(SrcElemTL); 4003 DstATL->setLBracketLoc(SrcATL->getLBracketLoc()); 4004 DstATL->setSizeExpr(SrcATL->getSizeExpr()); 4005 DstATL->setRBracketLoc(SrcATL->getRBracketLoc()); 4006} 4007 4008/// Helper method to turn variable array types into constant array 4009/// types in certain situations which would otherwise be errors (for 4010/// GCC compatibility). 4011static TypeSourceInfo* 4012TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4013 ASTContext &Context, 4014 bool &SizeIsNegative, 4015 llvm::APSInt &Oversized) { 4016 QualType FixedTy 4017 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4018 SizeIsNegative, Oversized); 4019 if (FixedTy.isNull()) 4020 return 0; 4021 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4022 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4023 FixedTInfo->getTypeLoc()); 4024 return FixedTInfo; 4025} 4026 4027/// \brief Register the given locally-scoped extern "C" declaration so 4028/// that it can be found later for redeclarations 4029void 4030Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 4031 const LookupResult &Previous, 4032 Scope *S) { 4033 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 4034 "Decl is not a locally-scoped decl!"); 4035 // Note that we have a locally-scoped external with this name. 4036 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4037 4038 if (!Previous.isSingleResult()) 4039 return; 4040 4041 NamedDecl *PrevDecl = Previous.getFoundDecl(); 4042 4043 // If there was a previous declaration of this entity, it may be in 4044 // our identifier chain. Update the identifier chain with the new 4045 // declaration. 4046 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 4047 // The previous declaration was found on the identifer resolver 4048 // chain, so remove it from its scope. 4049 4050 if (S->isDeclScope(PrevDecl)) { 4051 // Special case for redeclarations in the SAME scope. 4052 // Because this declaration is going to be added to the identifier chain 4053 // later, we should temporarily take it OFF the chain. 4054 IdResolver.RemoveDecl(ND); 4055 4056 } else { 4057 // Find the scope for the original declaration. 4058 while (S && !S->isDeclScope(PrevDecl)) 4059 S = S->getParent(); 4060 } 4061 4062 if (S) 4063 S->RemoveDecl(PrevDecl); 4064 } 4065} 4066 4067llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 4068Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4069 if (ExternalSource) { 4070 // Load locally-scoped external decls from the external source. 4071 SmallVector<NamedDecl *, 4> Decls; 4072 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4073 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4074 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4075 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4076 if (Pos == LocallyScopedExternCDecls.end()) 4077 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4078 } 4079 } 4080 4081 return LocallyScopedExternCDecls.find(Name); 4082} 4083 4084/// \brief Diagnose function specifiers on a declaration of an identifier that 4085/// does not identify a function. 4086void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 4087 // FIXME: We should probably indicate the identifier in question to avoid 4088 // confusion for constructs like "inline int a(), b;" 4089 if (D.getDeclSpec().isInlineSpecified()) 4090 Diag(D.getDeclSpec().getInlineSpecLoc(), 4091 diag::err_inline_non_function); 4092 4093 if (D.getDeclSpec().isVirtualSpecified()) 4094 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4095 diag::err_virtual_non_function); 4096 4097 if (D.getDeclSpec().isExplicitSpecified()) 4098 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4099 diag::err_explicit_non_function); 4100 4101 if (D.getDeclSpec().isNoreturnSpecified()) 4102 Diag(D.getDeclSpec().getNoreturnSpecLoc(), 4103 diag::err_noreturn_non_function); 4104} 4105 4106NamedDecl* 4107Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4108 TypeSourceInfo *TInfo, LookupResult &Previous) { 4109 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4110 if (D.getCXXScopeSpec().isSet()) { 4111 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4112 << D.getCXXScopeSpec().getRange(); 4113 D.setInvalidType(); 4114 // Pretend we didn't see the scope specifier. 4115 DC = CurContext; 4116 Previous.clear(); 4117 } 4118 4119 if (getLangOpts().CPlusPlus) { 4120 // Check that there are no default arguments (C++ only). 4121 CheckExtraCXXDefaultArguments(D); 4122 } 4123 4124 DiagnoseFunctionSpecifiers(D); 4125 4126 if (D.getDeclSpec().isThreadSpecified()) 4127 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4128 if (D.getDeclSpec().isConstexprSpecified()) 4129 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4130 << 1; 4131 4132 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4133 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4134 << D.getName().getSourceRange(); 4135 return 0; 4136 } 4137 4138 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4139 if (!NewTD) return 0; 4140 4141 // Handle attributes prior to checking for duplicates in MergeVarDecl 4142 ProcessDeclAttributes(S, NewTD, D); 4143 4144 CheckTypedefForVariablyModifiedType(S, NewTD); 4145 4146 bool Redeclaration = D.isRedeclaration(); 4147 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4148 D.setRedeclaration(Redeclaration); 4149 return ND; 4150} 4151 4152void 4153Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4154 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4155 // then it shall have block scope. 4156 // Note that variably modified types must be fixed before merging the decl so 4157 // that redeclarations will match. 4158 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4159 QualType T = TInfo->getType(); 4160 if (T->isVariablyModifiedType()) { 4161 getCurFunction()->setHasBranchProtectedScope(); 4162 4163 if (S->getFnParent() == 0) { 4164 bool SizeIsNegative; 4165 llvm::APSInt Oversized; 4166 TypeSourceInfo *FixedTInfo = 4167 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4168 SizeIsNegative, 4169 Oversized); 4170 if (FixedTInfo) { 4171 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4172 NewTD->setTypeSourceInfo(FixedTInfo); 4173 } else { 4174 if (SizeIsNegative) 4175 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4176 else if (T->isVariableArrayType()) 4177 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4178 else if (Oversized.getBoolValue()) 4179 Diag(NewTD->getLocation(), diag::err_array_too_large) 4180 << Oversized.toString(10); 4181 else 4182 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4183 NewTD->setInvalidDecl(); 4184 } 4185 } 4186 } 4187} 4188 4189 4190/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4191/// declares a typedef-name, either using the 'typedef' type specifier or via 4192/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4193NamedDecl* 4194Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4195 LookupResult &Previous, bool &Redeclaration) { 4196 // Merge the decl with the existing one if appropriate. If the decl is 4197 // in an outer scope, it isn't the same thing. 4198 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4199 /*ExplicitInstantiationOrSpecialization=*/false); 4200 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4201 if (!Previous.empty()) { 4202 Redeclaration = true; 4203 MergeTypedefNameDecl(NewTD, Previous); 4204 } 4205 4206 // If this is the C FILE type, notify the AST context. 4207 if (IdentifierInfo *II = NewTD->getIdentifier()) 4208 if (!NewTD->isInvalidDecl() && 4209 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4210 if (II->isStr("FILE")) 4211 Context.setFILEDecl(NewTD); 4212 else if (II->isStr("jmp_buf")) 4213 Context.setjmp_bufDecl(NewTD); 4214 else if (II->isStr("sigjmp_buf")) 4215 Context.setsigjmp_bufDecl(NewTD); 4216 else if (II->isStr("ucontext_t")) 4217 Context.setucontext_tDecl(NewTD); 4218 } 4219 4220 return NewTD; 4221} 4222 4223/// \brief Determines whether the given declaration is an out-of-scope 4224/// previous declaration. 4225/// 4226/// This routine should be invoked when name lookup has found a 4227/// previous declaration (PrevDecl) that is not in the scope where a 4228/// new declaration by the same name is being introduced. If the new 4229/// declaration occurs in a local scope, previous declarations with 4230/// linkage may still be considered previous declarations (C99 4231/// 6.2.2p4-5, C++ [basic.link]p6). 4232/// 4233/// \param PrevDecl the previous declaration found by name 4234/// lookup 4235/// 4236/// \param DC the context in which the new declaration is being 4237/// declared. 4238/// 4239/// \returns true if PrevDecl is an out-of-scope previous declaration 4240/// for a new delcaration with the same name. 4241static bool 4242isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4243 ASTContext &Context) { 4244 if (!PrevDecl) 4245 return false; 4246 4247 if (!PrevDecl->hasLinkage()) 4248 return false; 4249 4250 if (Context.getLangOpts().CPlusPlus) { 4251 // C++ [basic.link]p6: 4252 // If there is a visible declaration of an entity with linkage 4253 // having the same name and type, ignoring entities declared 4254 // outside the innermost enclosing namespace scope, the block 4255 // scope declaration declares that same entity and receives the 4256 // linkage of the previous declaration. 4257 DeclContext *OuterContext = DC->getRedeclContext(); 4258 if (!OuterContext->isFunctionOrMethod()) 4259 // This rule only applies to block-scope declarations. 4260 return false; 4261 4262 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4263 if (PrevOuterContext->isRecord()) 4264 // We found a member function: ignore it. 4265 return false; 4266 4267 // Find the innermost enclosing namespace for the new and 4268 // previous declarations. 4269 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4270 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4271 4272 // The previous declaration is in a different namespace, so it 4273 // isn't the same function. 4274 if (!OuterContext->Equals(PrevOuterContext)) 4275 return false; 4276 } 4277 4278 return true; 4279} 4280 4281static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4282 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4283 if (!SS.isSet()) return; 4284 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4285} 4286 4287bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4288 QualType type = decl->getType(); 4289 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4290 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4291 // Various kinds of declaration aren't allowed to be __autoreleasing. 4292 unsigned kind = -1U; 4293 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4294 if (var->hasAttr<BlocksAttr>()) 4295 kind = 0; // __block 4296 else if (!var->hasLocalStorage()) 4297 kind = 1; // global 4298 } else if (isa<ObjCIvarDecl>(decl)) { 4299 kind = 3; // ivar 4300 } else if (isa<FieldDecl>(decl)) { 4301 kind = 2; // field 4302 } 4303 4304 if (kind != -1U) { 4305 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4306 << kind; 4307 } 4308 } else if (lifetime == Qualifiers::OCL_None) { 4309 // Try to infer lifetime. 4310 if (!type->isObjCLifetimeType()) 4311 return false; 4312 4313 lifetime = type->getObjCARCImplicitLifetime(); 4314 type = Context.getLifetimeQualifiedType(type, lifetime); 4315 decl->setType(type); 4316 } 4317 4318 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4319 // Thread-local variables cannot have lifetime. 4320 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4321 var->isThreadSpecified()) { 4322 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4323 << var->getType(); 4324 return true; 4325 } 4326 } 4327 4328 return false; 4329} 4330 4331static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4332 // 'weak' only applies to declarations with external linkage. 4333 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4334 if (ND.getLinkage() != ExternalLinkage) { 4335 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4336 ND.dropAttr<WeakAttr>(); 4337 } 4338 } 4339 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4340 if (ND.getLinkage() == ExternalLinkage) { 4341 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4342 ND.dropAttr<WeakRefAttr>(); 4343 } 4344 } 4345} 4346 4347NamedDecl* 4348Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4349 TypeSourceInfo *TInfo, LookupResult &Previous, 4350 MultiTemplateParamsArg TemplateParamLists) { 4351 QualType R = TInfo->getType(); 4352 DeclarationName Name = GetNameForDeclarator(D).getName(); 4353 4354 // Check that there are no default arguments (C++ only). 4355 if (getLangOpts().CPlusPlus) 4356 CheckExtraCXXDefaultArguments(D); 4357 4358 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4359 assert(SCSpec != DeclSpec::SCS_typedef && 4360 "Parser allowed 'typedef' as storage class VarDecl."); 4361 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4362 if (SCSpec == DeclSpec::SCS_mutable) { 4363 // mutable can only appear on non-static class members, so it's always 4364 // an error here 4365 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4366 D.setInvalidType(); 4367 SC = SC_None; 4368 } 4369 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4370 VarDecl::StorageClass SCAsWritten 4371 = StorageClassSpecToVarDeclStorageClass(SCSpec); 4372 4373 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4374 if (!II) { 4375 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4376 << Name; 4377 return 0; 4378 } 4379 4380 DiagnoseFunctionSpecifiers(D); 4381 4382 if (!DC->isRecord() && S->getFnParent() == 0) { 4383 // C99 6.9p2: The storage-class specifiers auto and register shall not 4384 // appear in the declaration specifiers in an external declaration. 4385 if (SC == SC_Auto || SC == SC_Register) { 4386 4387 // If this is a register variable with an asm label specified, then this 4388 // is a GNU extension. 4389 if (SC == SC_Register && D.getAsmLabel()) 4390 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4391 else 4392 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4393 D.setInvalidType(); 4394 } 4395 } 4396 4397 if (getLangOpts().OpenCL) { 4398 // Set up the special work-group-local storage class for variables in the 4399 // OpenCL __local address space. 4400 if (R.getAddressSpace() == LangAS::opencl_local) { 4401 SC = SC_OpenCLWorkGroupLocal; 4402 SCAsWritten = SC_OpenCLWorkGroupLocal; 4403 } 4404 } 4405 4406 bool isExplicitSpecialization = false; 4407 VarDecl *NewVD; 4408 if (!getLangOpts().CPlusPlus) { 4409 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4410 D.getIdentifierLoc(), II, 4411 R, TInfo, SC, SCAsWritten); 4412 4413 if (D.isInvalidType()) 4414 NewVD->setInvalidDecl(); 4415 } else { 4416 if (DC->isRecord() && !CurContext->isRecord()) { 4417 // This is an out-of-line definition of a static data member. 4418 if (SC == SC_Static) { 4419 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4420 diag::err_static_out_of_line) 4421 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4422 } else if (SC == SC_None) 4423 SC = SC_Static; 4424 } 4425 if (SC == SC_Static && CurContext->isRecord()) { 4426 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4427 if (RD->isLocalClass()) 4428 Diag(D.getIdentifierLoc(), 4429 diag::err_static_data_member_not_allowed_in_local_class) 4430 << Name << RD->getDeclName(); 4431 4432 // C++98 [class.union]p1: If a union contains a static data member, 4433 // the program is ill-formed. C++11 drops this restriction. 4434 if (RD->isUnion()) 4435 Diag(D.getIdentifierLoc(), 4436 getLangOpts().CPlusPlus11 4437 ? diag::warn_cxx98_compat_static_data_member_in_union 4438 : diag::ext_static_data_member_in_union) << Name; 4439 // We conservatively disallow static data members in anonymous structs. 4440 else if (!RD->getDeclName()) 4441 Diag(D.getIdentifierLoc(), 4442 diag::err_static_data_member_not_allowed_in_anon_struct) 4443 << Name << RD->isUnion(); 4444 } 4445 } 4446 4447 // Match up the template parameter lists with the scope specifier, then 4448 // determine whether we have a template or a template specialization. 4449 isExplicitSpecialization = false; 4450 bool Invalid = false; 4451 if (TemplateParameterList *TemplateParams 4452 = MatchTemplateParametersToScopeSpecifier( 4453 D.getDeclSpec().getLocStart(), 4454 D.getIdentifierLoc(), 4455 D.getCXXScopeSpec(), 4456 TemplateParamLists.data(), 4457 TemplateParamLists.size(), 4458 /*never a friend*/ false, 4459 isExplicitSpecialization, 4460 Invalid)) { 4461 if (TemplateParams->size() > 0) { 4462 // There is no such thing as a variable template. 4463 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4464 << II 4465 << SourceRange(TemplateParams->getTemplateLoc(), 4466 TemplateParams->getRAngleLoc()); 4467 return 0; 4468 } else { 4469 // There is an extraneous 'template<>' for this variable. Complain 4470 // about it, but allow the declaration of the variable. 4471 Diag(TemplateParams->getTemplateLoc(), 4472 diag::err_template_variable_noparams) 4473 << II 4474 << SourceRange(TemplateParams->getTemplateLoc(), 4475 TemplateParams->getRAngleLoc()); 4476 } 4477 } 4478 4479 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4480 D.getIdentifierLoc(), II, 4481 R, TInfo, SC, SCAsWritten); 4482 4483 // If this decl has an auto type in need of deduction, make a note of the 4484 // Decl so we can diagnose uses of it in its own initializer. 4485 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4486 R->getContainedAutoType()) 4487 ParsingInitForAutoVars.insert(NewVD); 4488 4489 if (D.isInvalidType() || Invalid) 4490 NewVD->setInvalidDecl(); 4491 4492 SetNestedNameSpecifier(NewVD, D); 4493 4494 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4495 NewVD->setTemplateParameterListsInfo(Context, 4496 TemplateParamLists.size(), 4497 TemplateParamLists.data()); 4498 } 4499 4500 if (D.getDeclSpec().isConstexprSpecified()) 4501 NewVD->setConstexpr(true); 4502 } 4503 4504 // Set the lexical context. If the declarator has a C++ scope specifier, the 4505 // lexical context will be different from the semantic context. 4506 NewVD->setLexicalDeclContext(CurContext); 4507 4508 if (D.getDeclSpec().isThreadSpecified()) { 4509 if (NewVD->hasLocalStorage()) 4510 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4511 else if (!Context.getTargetInfo().isTLSSupported()) 4512 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4513 else 4514 NewVD->setThreadSpecified(true); 4515 } 4516 4517 if (D.getDeclSpec().isModulePrivateSpecified()) { 4518 if (isExplicitSpecialization) 4519 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4520 << 2 4521 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4522 else if (NewVD->hasLocalStorage()) 4523 Diag(NewVD->getLocation(), diag::err_module_private_local) 4524 << 0 << NewVD->getDeclName() 4525 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4526 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4527 else 4528 NewVD->setModulePrivate(); 4529 } 4530 4531 // Handle attributes prior to checking for duplicates in MergeVarDecl 4532 ProcessDeclAttributes(S, NewVD, D); 4533 4534 if (getLangOpts().CUDA) { 4535 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 4536 // storage [duration]." 4537 if (SC == SC_None && S->getFnParent() != 0 && 4538 (NewVD->hasAttr<CUDASharedAttr>() || 4539 NewVD->hasAttr<CUDAConstantAttr>())) { 4540 NewVD->setStorageClass(SC_Static); 4541 NewVD->setStorageClassAsWritten(SC_Static); 4542 } 4543 } 4544 4545 // In auto-retain/release, infer strong retension for variables of 4546 // retainable type. 4547 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4548 NewVD->setInvalidDecl(); 4549 4550 // Handle GNU asm-label extension (encoded as an attribute). 4551 if (Expr *E = (Expr*)D.getAsmLabel()) { 4552 // The parser guarantees this is a string. 4553 StringLiteral *SE = cast<StringLiteral>(E); 4554 StringRef Label = SE->getString(); 4555 if (S->getFnParent() != 0) { 4556 switch (SC) { 4557 case SC_None: 4558 case SC_Auto: 4559 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4560 break; 4561 case SC_Register: 4562 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4563 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4564 break; 4565 case SC_Static: 4566 case SC_Extern: 4567 case SC_PrivateExtern: 4568 case SC_OpenCLWorkGroupLocal: 4569 break; 4570 } 4571 } 4572 4573 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4574 Context, Label)); 4575 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4576 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 4577 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 4578 if (I != ExtnameUndeclaredIdentifiers.end()) { 4579 NewVD->addAttr(I->second); 4580 ExtnameUndeclaredIdentifiers.erase(I); 4581 } 4582 } 4583 4584 // Diagnose shadowed variables before filtering for scope. 4585 if (!D.getCXXScopeSpec().isSet()) 4586 CheckShadow(S, NewVD, Previous); 4587 4588 // Don't consider existing declarations that are in a different 4589 // scope and are out-of-semantic-context declarations (if the new 4590 // declaration has linkage). 4591 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 4592 isExplicitSpecialization); 4593 4594 if (!getLangOpts().CPlusPlus) { 4595 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4596 } else { 4597 // Merge the decl with the existing one if appropriate. 4598 if (!Previous.empty()) { 4599 if (Previous.isSingleResult() && 4600 isa<FieldDecl>(Previous.getFoundDecl()) && 4601 D.getCXXScopeSpec().isSet()) { 4602 // The user tried to define a non-static data member 4603 // out-of-line (C++ [dcl.meaning]p1). 4604 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4605 << D.getCXXScopeSpec().getRange(); 4606 Previous.clear(); 4607 NewVD->setInvalidDecl(); 4608 } 4609 } else if (D.getCXXScopeSpec().isSet()) { 4610 // No previous declaration in the qualifying scope. 4611 Diag(D.getIdentifierLoc(), diag::err_no_member) 4612 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4613 << D.getCXXScopeSpec().getRange(); 4614 NewVD->setInvalidDecl(); 4615 } 4616 4617 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4618 4619 // This is an explicit specialization of a static data member. Check it. 4620 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4621 CheckMemberSpecialization(NewVD, Previous)) 4622 NewVD->setInvalidDecl(); 4623 } 4624 4625 checkAttributesAfterMerging(*this, *NewVD); 4626 4627 // If this is a locally-scoped extern C variable, update the map of 4628 // such variables. 4629 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4630 !NewVD->isInvalidDecl()) 4631 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4632 4633 // If there's a #pragma GCC visibility in scope, and this isn't a class 4634 // member, set the visibility of this variable. 4635 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 4636 AddPushedVisibilityAttribute(NewVD); 4637 4638 return NewVD; 4639} 4640 4641/// \brief Diagnose variable or built-in function shadowing. Implements 4642/// -Wshadow. 4643/// 4644/// This method is called whenever a VarDecl is added to a "useful" 4645/// scope. 4646/// 4647/// \param S the scope in which the shadowing name is being declared 4648/// \param R the lookup of the name 4649/// 4650void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4651 // Return if warning is ignored. 4652 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4653 DiagnosticsEngine::Ignored) 4654 return; 4655 4656 // Don't diagnose declarations at file scope. 4657 if (D->hasGlobalStorage()) 4658 return; 4659 4660 DeclContext *NewDC = D->getDeclContext(); 4661 4662 // Only diagnose if we're shadowing an unambiguous field or variable. 4663 if (R.getResultKind() != LookupResult::Found) 4664 return; 4665 4666 NamedDecl* ShadowedDecl = R.getFoundDecl(); 4667 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 4668 return; 4669 4670 // Fields are not shadowed by variables in C++ static methods. 4671 if (isa<FieldDecl>(ShadowedDecl)) 4672 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 4673 if (MD->isStatic()) 4674 return; 4675 4676 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 4677 if (shadowedVar->isExternC()) { 4678 // For shadowing external vars, make sure that we point to the global 4679 // declaration, not a locally scoped extern declaration. 4680 for (VarDecl::redecl_iterator 4681 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 4682 I != E; ++I) 4683 if (I->isFileVarDecl()) { 4684 ShadowedDecl = *I; 4685 break; 4686 } 4687 } 4688 4689 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 4690 4691 // Only warn about certain kinds of shadowing for class members. 4692 if (NewDC && NewDC->isRecord()) { 4693 // In particular, don't warn about shadowing non-class members. 4694 if (!OldDC->isRecord()) 4695 return; 4696 4697 // TODO: should we warn about static data members shadowing 4698 // static data members from base classes? 4699 4700 // TODO: don't diagnose for inaccessible shadowed members. 4701 // This is hard to do perfectly because we might friend the 4702 // shadowing context, but that's just a false negative. 4703 } 4704 4705 // Determine what kind of declaration we're shadowing. 4706 unsigned Kind; 4707 if (isa<RecordDecl>(OldDC)) { 4708 if (isa<FieldDecl>(ShadowedDecl)) 4709 Kind = 3; // field 4710 else 4711 Kind = 2; // static data member 4712 } else if (OldDC->isFileContext()) 4713 Kind = 1; // global 4714 else 4715 Kind = 0; // local 4716 4717 DeclarationName Name = R.getLookupName(); 4718 4719 // Emit warning and note. 4720 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 4721 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 4722} 4723 4724/// \brief Check -Wshadow without the advantage of a previous lookup. 4725void Sema::CheckShadow(Scope *S, VarDecl *D) { 4726 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 4727 DiagnosticsEngine::Ignored) 4728 return; 4729 4730 LookupResult R(*this, D->getDeclName(), D->getLocation(), 4731 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 4732 LookupName(R, S); 4733 CheckShadow(S, D, R); 4734} 4735 4736template<typename T> 4737static bool mayConflictWithNonVisibleExternC(const T *ND) { 4738 VarDecl::StorageClass SC = ND->getStorageClass(); 4739 if (ND->hasCLanguageLinkage() && (SC == SC_Extern || SC == SC_PrivateExtern)) 4740 return true; 4741 return ND->getDeclContext()->isTranslationUnit(); 4742} 4743 4744/// \brief Perform semantic checking on a newly-created variable 4745/// declaration. 4746/// 4747/// This routine performs all of the type-checking required for a 4748/// variable declaration once it has been built. It is used both to 4749/// check variables after they have been parsed and their declarators 4750/// have been translated into a declaration, and to check variables 4751/// that have been instantiated from a template. 4752/// 4753/// Sets NewVD->isInvalidDecl() if an error was encountered. 4754/// 4755/// Returns true if the variable declaration is a redeclaration. 4756bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 4757 LookupResult &Previous) { 4758 // If the decl is already known invalid, don't check it. 4759 if (NewVD->isInvalidDecl()) 4760 return false; 4761 4762 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 4763 QualType T = TInfo->getType(); 4764 4765 if (T->isObjCObjectType()) { 4766 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 4767 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 4768 T = Context.getObjCObjectPointerType(T); 4769 NewVD->setType(T); 4770 } 4771 4772 // Emit an error if an address space was applied to decl with local storage. 4773 // This includes arrays of objects with address space qualifiers, but not 4774 // automatic variables that point to other address spaces. 4775 // ISO/IEC TR 18037 S5.1.2 4776 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 4777 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 4778 NewVD->setInvalidDecl(); 4779 return false; 4780 } 4781 4782 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 4783 // scope. 4784 if ((getLangOpts().OpenCLVersion >= 120) 4785 && NewVD->isStaticLocal()) { 4786 Diag(NewVD->getLocation(), diag::err_static_function_scope); 4787 NewVD->setInvalidDecl(); 4788 return false; 4789 } 4790 4791 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 4792 && !NewVD->hasAttr<BlocksAttr>()) { 4793 if (getLangOpts().getGC() != LangOptions::NonGC) 4794 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 4795 else { 4796 assert(!getLangOpts().ObjCAutoRefCount); 4797 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 4798 } 4799 } 4800 4801 bool isVM = T->isVariablyModifiedType(); 4802 if (isVM || NewVD->hasAttr<CleanupAttr>() || 4803 NewVD->hasAttr<BlocksAttr>()) 4804 getCurFunction()->setHasBranchProtectedScope(); 4805 4806 if ((isVM && NewVD->hasLinkage()) || 4807 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 4808 bool SizeIsNegative; 4809 llvm::APSInt Oversized; 4810 TypeSourceInfo *FixedTInfo = 4811 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4812 SizeIsNegative, Oversized); 4813 if (FixedTInfo == 0 && T->isVariableArrayType()) { 4814 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 4815 // FIXME: This won't give the correct result for 4816 // int a[10][n]; 4817 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 4818 4819 if (NewVD->isFileVarDecl()) 4820 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 4821 << SizeRange; 4822 else if (NewVD->getStorageClass() == SC_Static) 4823 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 4824 << SizeRange; 4825 else 4826 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 4827 << SizeRange; 4828 NewVD->setInvalidDecl(); 4829 return false; 4830 } 4831 4832 if (FixedTInfo == 0) { 4833 if (NewVD->isFileVarDecl()) 4834 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 4835 else 4836 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 4837 NewVD->setInvalidDecl(); 4838 return false; 4839 } 4840 4841 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 4842 NewVD->setType(FixedTInfo->getType()); 4843 NewVD->setTypeSourceInfo(FixedTInfo); 4844 } 4845 4846 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewVD)) { 4847 // Since we did not find anything by this name, look for a non-visible 4848 // extern "C" declaration with the same name. 4849 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4850 = findLocallyScopedExternCDecl(NewVD->getDeclName()); 4851 if (Pos != LocallyScopedExternCDecls.end()) 4852 Previous.addDecl(Pos->second); 4853 } 4854 4855 // Filter out any non-conflicting previous declarations. 4856 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 4857 4858 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 4859 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 4860 << T; 4861 NewVD->setInvalidDecl(); 4862 return false; 4863 } 4864 4865 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 4866 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 4867 NewVD->setInvalidDecl(); 4868 return false; 4869 } 4870 4871 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 4872 Diag(NewVD->getLocation(), diag::err_block_on_vm); 4873 NewVD->setInvalidDecl(); 4874 return false; 4875 } 4876 4877 if (NewVD->isConstexpr() && !T->isDependentType() && 4878 RequireLiteralType(NewVD->getLocation(), T, 4879 diag::err_constexpr_var_non_literal)) { 4880 NewVD->setInvalidDecl(); 4881 return false; 4882 } 4883 4884 if (!Previous.empty()) { 4885 MergeVarDecl(NewVD, Previous); 4886 return true; 4887 } 4888 return false; 4889} 4890 4891/// \brief Data used with FindOverriddenMethod 4892struct FindOverriddenMethodData { 4893 Sema *S; 4894 CXXMethodDecl *Method; 4895}; 4896 4897/// \brief Member lookup function that determines whether a given C++ 4898/// method overrides a method in a base class, to be used with 4899/// CXXRecordDecl::lookupInBases(). 4900static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 4901 CXXBasePath &Path, 4902 void *UserData) { 4903 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4904 4905 FindOverriddenMethodData *Data 4906 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 4907 4908 DeclarationName Name = Data->Method->getDeclName(); 4909 4910 // FIXME: Do we care about other names here too? 4911 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 4912 // We really want to find the base class destructor here. 4913 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 4914 CanQualType CT = Data->S->Context.getCanonicalType(T); 4915 4916 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 4917 } 4918 4919 for (Path.Decls = BaseRecord->lookup(Name); 4920 !Path.Decls.empty(); 4921 Path.Decls = Path.Decls.slice(1)) { 4922 NamedDecl *D = Path.Decls.front(); 4923 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4924 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 4925 return true; 4926 } 4927 } 4928 4929 return false; 4930} 4931 4932namespace { 4933 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 4934} 4935/// \brief Report an error regarding overriding, along with any relevant 4936/// overriden methods. 4937/// 4938/// \param DiagID the primary error to report. 4939/// \param MD the overriding method. 4940/// \param OEK which overrides to include as notes. 4941static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 4942 OverrideErrorKind OEK = OEK_All) { 4943 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 4944 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4945 E = MD->end_overridden_methods(); 4946 I != E; ++I) { 4947 // This check (& the OEK parameter) could be replaced by a predicate, but 4948 // without lambdas that would be overkill. This is still nicer than writing 4949 // out the diag loop 3 times. 4950 if ((OEK == OEK_All) || 4951 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 4952 (OEK == OEK_Deleted && (*I)->isDeleted())) 4953 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 4954 } 4955} 4956 4957/// AddOverriddenMethods - See if a method overrides any in the base classes, 4958/// and if so, check that it's a valid override and remember it. 4959bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4960 // Look for virtual methods in base classes that this method might override. 4961 CXXBasePaths Paths; 4962 FindOverriddenMethodData Data; 4963 Data.Method = MD; 4964 Data.S = this; 4965 bool hasDeletedOverridenMethods = false; 4966 bool hasNonDeletedOverridenMethods = false; 4967 bool AddedAny = false; 4968 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 4969 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 4970 E = Paths.found_decls_end(); I != E; ++I) { 4971 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 4972 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 4973 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 4974 !CheckOverridingFunctionAttributes(MD, OldMD) && 4975 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 4976 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 4977 hasDeletedOverridenMethods |= OldMD->isDeleted(); 4978 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 4979 AddedAny = true; 4980 } 4981 } 4982 } 4983 } 4984 4985 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 4986 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 4987 } 4988 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 4989 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 4990 } 4991 4992 return AddedAny; 4993} 4994 4995namespace { 4996 // Struct for holding all of the extra arguments needed by 4997 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 4998 struct ActOnFDArgs { 4999 Scope *S; 5000 Declarator &D; 5001 MultiTemplateParamsArg TemplateParamLists; 5002 bool AddToScope; 5003 }; 5004} 5005 5006namespace { 5007 5008// Callback to only accept typo corrections that have a non-zero edit distance. 5009// Also only accept corrections that have the same parent decl. 5010class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5011 public: 5012 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5013 CXXRecordDecl *Parent) 5014 : Context(Context), OriginalFD(TypoFD), 5015 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5016 5017 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5018 if (candidate.getEditDistance() == 0) 5019 return false; 5020 5021 SmallVector<unsigned, 1> MismatchedParams; 5022 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5023 CDeclEnd = candidate.end(); 5024 CDecl != CDeclEnd; ++CDecl) { 5025 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5026 5027 if (FD && !FD->hasBody() && 5028 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 5029 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5030 CXXRecordDecl *Parent = MD->getParent(); 5031 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 5032 return true; 5033 } else if (!ExpectedParent) { 5034 return true; 5035 } 5036 } 5037 } 5038 5039 return false; 5040 } 5041 5042 private: 5043 ASTContext &Context; 5044 FunctionDecl *OriginalFD; 5045 CXXRecordDecl *ExpectedParent; 5046}; 5047 5048} 5049 5050/// \brief Generate diagnostics for an invalid function redeclaration. 5051/// 5052/// This routine handles generating the diagnostic messages for an invalid 5053/// function redeclaration, including finding possible similar declarations 5054/// or performing typo correction if there are no previous declarations with 5055/// the same name. 5056/// 5057/// Returns a NamedDecl iff typo correction was performed and substituting in 5058/// the new declaration name does not cause new errors. 5059static NamedDecl* DiagnoseInvalidRedeclaration( 5060 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 5061 ActOnFDArgs &ExtraArgs) { 5062 NamedDecl *Result = NULL; 5063 DeclarationName Name = NewFD->getDeclName(); 5064 DeclContext *NewDC = NewFD->getDeclContext(); 5065 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 5066 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5067 SmallVector<unsigned, 1> MismatchedParams; 5068 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 5069 TypoCorrection Correction; 5070 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 5071 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 5072 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 5073 : diag::err_member_def_does_not_match; 5074 5075 NewFD->setInvalidDecl(); 5076 SemaRef.LookupQualifiedName(Prev, NewDC); 5077 assert(!Prev.isAmbiguous() && 5078 "Cannot have an ambiguity in previous-declaration lookup"); 5079 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 5080 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 5081 MD ? MD->getParent() : 0); 5082 if (!Prev.empty()) { 5083 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 5084 Func != FuncEnd; ++Func) { 5085 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 5086 if (FD && 5087 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5088 // Add 1 to the index so that 0 can mean the mismatch didn't 5089 // involve a parameter 5090 unsigned ParamNum = 5091 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 5092 NearMatches.push_back(std::make_pair(FD, ParamNum)); 5093 } 5094 } 5095 // If the qualified name lookup yielded nothing, try typo correction 5096 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 5097 Prev.getLookupKind(), 0, 0, 5098 Validator, NewDC))) { 5099 // Trap errors. 5100 Sema::SFINAETrap Trap(SemaRef); 5101 5102 // Set up everything for the call to ActOnFunctionDeclarator 5103 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 5104 ExtraArgs.D.getIdentifierLoc()); 5105 Previous.clear(); 5106 Previous.setLookupName(Correction.getCorrection()); 5107 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 5108 CDeclEnd = Correction.end(); 5109 CDecl != CDeclEnd; ++CDecl) { 5110 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5111 if (FD && !FD->hasBody() && 5112 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5113 Previous.addDecl(FD); 5114 } 5115 } 5116 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 5117 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 5118 // pieces need to verify the typo-corrected C++ declaraction and hopefully 5119 // eliminate the need for the parameter pack ExtraArgs. 5120 Result = SemaRef.ActOnFunctionDeclarator( 5121 ExtraArgs.S, ExtraArgs.D, 5122 Correction.getCorrectionDecl()->getDeclContext(), 5123 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 5124 ExtraArgs.AddToScope); 5125 if (Trap.hasErrorOccurred()) { 5126 // Pretend the typo correction never occurred 5127 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 5128 ExtraArgs.D.getIdentifierLoc()); 5129 ExtraArgs.D.setRedeclaration(wasRedeclaration); 5130 Previous.clear(); 5131 Previous.setLookupName(Name); 5132 Result = NULL; 5133 } else { 5134 for (LookupResult::iterator Func = Previous.begin(), 5135 FuncEnd = Previous.end(); 5136 Func != FuncEnd; ++Func) { 5137 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 5138 NearMatches.push_back(std::make_pair(FD, 0)); 5139 } 5140 } 5141 if (NearMatches.empty()) { 5142 // Ignore the correction if it didn't yield any close FunctionDecl matches 5143 Correction = TypoCorrection(); 5144 } else { 5145 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 5146 : diag::err_member_def_does_not_match_suggest; 5147 } 5148 } 5149 5150 if (Correction) { 5151 // FIXME: use Correction.getCorrectionRange() instead of computing the range 5152 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in 5153 // turn causes the correction to fully qualify the name. If we fix 5154 // CorrectTypo to minimally qualify then this change should be good. 5155 SourceRange FixItLoc(NewFD->getLocation()); 5156 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec(); 5157 if (Correction.getCorrectionSpecifier() && SS.isValid()) 5158 FixItLoc.setBegin(SS.getBeginLoc()); 5159 SemaRef.Diag(NewFD->getLocStart(), DiagMsg) 5160 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 5161 << FixItHint::CreateReplacement( 5162 FixItLoc, Correction.getAsString(SemaRef.getLangOpts())); 5163 } else { 5164 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 5165 << Name << NewDC << NewFD->getLocation(); 5166 } 5167 5168 bool NewFDisConst = false; 5169 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 5170 NewFDisConst = NewMD->isConst(); 5171 5172 for (SmallVector<std::pair<FunctionDecl *, unsigned>, 1>::iterator 5173 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 5174 NearMatch != NearMatchEnd; ++NearMatch) { 5175 FunctionDecl *FD = NearMatch->first; 5176 bool FDisConst = false; 5177 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 5178 FDisConst = MD->isConst(); 5179 5180 if (unsigned Idx = NearMatch->second) { 5181 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 5182 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 5183 if (Loc.isInvalid()) Loc = FD->getLocation(); 5184 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 5185 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 5186 } else if (Correction) { 5187 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 5188 << Correction.getQuoted(SemaRef.getLangOpts()); 5189 } else if (FDisConst != NewFDisConst) { 5190 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 5191 << NewFDisConst << FD->getSourceRange().getEnd(); 5192 } else 5193 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 5194 } 5195 return Result; 5196} 5197 5198static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 5199 Declarator &D) { 5200 switch (D.getDeclSpec().getStorageClassSpec()) { 5201 default: llvm_unreachable("Unknown storage class!"); 5202 case DeclSpec::SCS_auto: 5203 case DeclSpec::SCS_register: 5204 case DeclSpec::SCS_mutable: 5205 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5206 diag::err_typecheck_sclass_func); 5207 D.setInvalidType(); 5208 break; 5209 case DeclSpec::SCS_unspecified: break; 5210 case DeclSpec::SCS_extern: return SC_Extern; 5211 case DeclSpec::SCS_static: { 5212 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 5213 // C99 6.7.1p5: 5214 // The declaration of an identifier for a function that has 5215 // block scope shall have no explicit storage-class specifier 5216 // other than extern 5217 // See also (C++ [dcl.stc]p4). 5218 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5219 diag::err_static_block_func); 5220 break; 5221 } else 5222 return SC_Static; 5223 } 5224 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5225 } 5226 5227 // No explicit storage class has already been returned 5228 return SC_None; 5229} 5230 5231static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 5232 DeclContext *DC, QualType &R, 5233 TypeSourceInfo *TInfo, 5234 FunctionDecl::StorageClass SC, 5235 bool &IsVirtualOkay) { 5236 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 5237 DeclarationName Name = NameInfo.getName(); 5238 5239 FunctionDecl *NewFD = 0; 5240 bool isInline = D.getDeclSpec().isInlineSpecified(); 5241 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 5242 FunctionDecl::StorageClass SCAsWritten 5243 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 5244 5245 if (!SemaRef.getLangOpts().CPlusPlus) { 5246 // Determine whether the function was written with a 5247 // prototype. This true when: 5248 // - there is a prototype in the declarator, or 5249 // - the type R of the function is some kind of typedef or other reference 5250 // to a type name (which eventually refers to a function type). 5251 bool HasPrototype = 5252 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 5253 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 5254 5255 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 5256 D.getLocStart(), NameInfo, R, 5257 TInfo, SC, SCAsWritten, isInline, 5258 HasPrototype); 5259 if (D.isInvalidType()) 5260 NewFD->setInvalidDecl(); 5261 5262 // Set the lexical context. 5263 NewFD->setLexicalDeclContext(SemaRef.CurContext); 5264 5265 return NewFD; 5266 } 5267 5268 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5269 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5270 5271 // Check that the return type is not an abstract class type. 5272 // For record types, this is done by the AbstractClassUsageDiagnoser once 5273 // the class has been completely parsed. 5274 if (!DC->isRecord() && 5275 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 5276 R->getAs<FunctionType>()->getResultType(), 5277 diag::err_abstract_type_in_decl, 5278 SemaRef.AbstractReturnType)) 5279 D.setInvalidType(); 5280 5281 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 5282 // This is a C++ constructor declaration. 5283 assert(DC->isRecord() && 5284 "Constructors can only be declared in a member context"); 5285 5286 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 5287 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5288 D.getLocStart(), NameInfo, 5289 R, TInfo, isExplicit, isInline, 5290 /*isImplicitlyDeclared=*/false, 5291 isConstexpr); 5292 5293 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5294 // This is a C++ destructor declaration. 5295 if (DC->isRecord()) { 5296 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 5297 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 5298 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 5299 SemaRef.Context, Record, 5300 D.getLocStart(), 5301 NameInfo, R, TInfo, isInline, 5302 /*isImplicitlyDeclared=*/false); 5303 5304 // If the class is complete, then we now create the implicit exception 5305 // specification. If the class is incomplete or dependent, we can't do 5306 // it yet. 5307 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 5308 Record->getDefinition() && !Record->isBeingDefined() && 5309 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 5310 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 5311 } 5312 5313 IsVirtualOkay = true; 5314 return NewDD; 5315 5316 } else { 5317 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 5318 D.setInvalidType(); 5319 5320 // Create a FunctionDecl to satisfy the function definition parsing 5321 // code path. 5322 return FunctionDecl::Create(SemaRef.Context, DC, 5323 D.getLocStart(), 5324 D.getIdentifierLoc(), Name, R, TInfo, 5325 SC, SCAsWritten, isInline, 5326 /*hasPrototype=*/true, isConstexpr); 5327 } 5328 5329 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 5330 if (!DC->isRecord()) { 5331 SemaRef.Diag(D.getIdentifierLoc(), 5332 diag::err_conv_function_not_member); 5333 return 0; 5334 } 5335 5336 SemaRef.CheckConversionDeclarator(D, R, SC); 5337 IsVirtualOkay = true; 5338 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5339 D.getLocStart(), NameInfo, 5340 R, TInfo, isInline, isExplicit, 5341 isConstexpr, SourceLocation()); 5342 5343 } else if (DC->isRecord()) { 5344 // If the name of the function is the same as the name of the record, 5345 // then this must be an invalid constructor that has a return type. 5346 // (The parser checks for a return type and makes the declarator a 5347 // constructor if it has no return type). 5348 if (Name.getAsIdentifierInfo() && 5349 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 5350 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 5351 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5352 << SourceRange(D.getIdentifierLoc()); 5353 return 0; 5354 } 5355 5356 bool isStatic = SC == SC_Static; 5357 5358 // [class.free]p1: 5359 // Any allocation function for a class T is a static member 5360 // (even if not explicitly declared static). 5361 if (Name.getCXXOverloadedOperator() == OO_New || 5362 Name.getCXXOverloadedOperator() == OO_Array_New) 5363 isStatic = true; 5364 5365 // [class.free]p6 Any deallocation function for a class X is a static member 5366 // (even if not explicitly declared static). 5367 if (Name.getCXXOverloadedOperator() == OO_Delete || 5368 Name.getCXXOverloadedOperator() == OO_Array_Delete) 5369 isStatic = true; 5370 5371 IsVirtualOkay = !isStatic; 5372 5373 // This is a C++ method declaration. 5374 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5375 D.getLocStart(), NameInfo, R, 5376 TInfo, isStatic, SCAsWritten, isInline, 5377 isConstexpr, SourceLocation()); 5378 5379 } else { 5380 // Determine whether the function was written with a 5381 // prototype. This true when: 5382 // - we're in C++ (where every function has a prototype), 5383 return FunctionDecl::Create(SemaRef.Context, DC, 5384 D.getLocStart(), 5385 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 5386 true/*HasPrototype*/, isConstexpr); 5387 } 5388} 5389 5390void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 5391 // In C++, the empty parameter-type-list must be spelled "void"; a 5392 // typedef of void is not permitted. 5393 if (getLangOpts().CPlusPlus && 5394 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5395 bool IsTypeAlias = false; 5396 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5397 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5398 else if (const TemplateSpecializationType *TST = 5399 Param->getType()->getAs<TemplateSpecializationType>()) 5400 IsTypeAlias = TST->isTypeAlias(); 5401 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5402 << IsTypeAlias; 5403 } 5404} 5405 5406NamedDecl* 5407Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5408 TypeSourceInfo *TInfo, LookupResult &Previous, 5409 MultiTemplateParamsArg TemplateParamLists, 5410 bool &AddToScope) { 5411 QualType R = TInfo->getType(); 5412 5413 assert(R.getTypePtr()->isFunctionType()); 5414 5415 // TODO: consider using NameInfo for diagnostic. 5416 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5417 DeclarationName Name = NameInfo.getName(); 5418 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 5419 5420 if (D.getDeclSpec().isThreadSpecified()) 5421 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5422 5423 // Do not allow returning a objc interface by-value. 5424 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 5425 Diag(D.getIdentifierLoc(), 5426 diag::err_object_cannot_be_passed_returned_by_value) << 0 5427 << R->getAs<FunctionType>()->getResultType() 5428 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 5429 5430 QualType T = R->getAs<FunctionType>()->getResultType(); 5431 T = Context.getObjCObjectPointerType(T); 5432 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 5433 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5434 R = Context.getFunctionType(T, FPT->arg_type_begin(), 5435 FPT->getNumArgs(), EPI); 5436 } 5437 else if (isa<FunctionNoProtoType>(R)) 5438 R = Context.getFunctionNoProtoType(T); 5439 } 5440 5441 bool isFriend = false; 5442 FunctionTemplateDecl *FunctionTemplate = 0; 5443 bool isExplicitSpecialization = false; 5444 bool isFunctionTemplateSpecialization = false; 5445 5446 bool isDependentClassScopeExplicitSpecialization = false; 5447 bool HasExplicitTemplateArgs = false; 5448 TemplateArgumentListInfo TemplateArgs; 5449 5450 bool isVirtualOkay = false; 5451 5452 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 5453 isVirtualOkay); 5454 if (!NewFD) return 0; 5455 5456 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 5457 NewFD->setTopLevelDeclInObjCContainer(); 5458 5459 if (getLangOpts().CPlusPlus) { 5460 bool isInline = D.getDeclSpec().isInlineSpecified(); 5461 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5462 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5463 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5464 isFriend = D.getDeclSpec().isFriendSpecified(); 5465 if (isFriend && !isInline && D.isFunctionDefinition()) { 5466 // C++ [class.friend]p5 5467 // A function can be defined in a friend declaration of a 5468 // class . . . . Such a function is implicitly inline. 5469 NewFD->setImplicitlyInline(); 5470 } 5471 5472 // If this is a method defined in an __interface, and is not a constructor 5473 // or an overloaded operator, then set the pure flag (isVirtual will already 5474 // return true). 5475 if (const CXXRecordDecl *Parent = 5476 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 5477 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 5478 NewFD->setPure(true); 5479 } 5480 5481 SetNestedNameSpecifier(NewFD, D); 5482 isExplicitSpecialization = false; 5483 isFunctionTemplateSpecialization = false; 5484 if (D.isInvalidType()) 5485 NewFD->setInvalidDecl(); 5486 5487 // Set the lexical context. If the declarator has a C++ 5488 // scope specifier, or is the object of a friend declaration, the 5489 // lexical context will be different from the semantic context. 5490 NewFD->setLexicalDeclContext(CurContext); 5491 5492 // Match up the template parameter lists with the scope specifier, then 5493 // determine whether we have a template or a template specialization. 5494 bool Invalid = false; 5495 if (TemplateParameterList *TemplateParams 5496 = MatchTemplateParametersToScopeSpecifier( 5497 D.getDeclSpec().getLocStart(), 5498 D.getIdentifierLoc(), 5499 D.getCXXScopeSpec(), 5500 TemplateParamLists.data(), 5501 TemplateParamLists.size(), 5502 isFriend, 5503 isExplicitSpecialization, 5504 Invalid)) { 5505 if (TemplateParams->size() > 0) { 5506 // This is a function template 5507 5508 // Check that we can declare a template here. 5509 if (CheckTemplateDeclScope(S, TemplateParams)) 5510 return 0; 5511 5512 // A destructor cannot be a template. 5513 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5514 Diag(NewFD->getLocation(), diag::err_destructor_template); 5515 return 0; 5516 } 5517 5518 // If we're adding a template to a dependent context, we may need to 5519 // rebuilding some of the types used within the template parameter list, 5520 // now that we know what the current instantiation is. 5521 if (DC->isDependentContext()) { 5522 ContextRAII SavedContext(*this, DC); 5523 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 5524 Invalid = true; 5525 } 5526 5527 5528 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 5529 NewFD->getLocation(), 5530 Name, TemplateParams, 5531 NewFD); 5532 FunctionTemplate->setLexicalDeclContext(CurContext); 5533 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 5534 5535 // For source fidelity, store the other template param lists. 5536 if (TemplateParamLists.size() > 1) { 5537 NewFD->setTemplateParameterListsInfo(Context, 5538 TemplateParamLists.size() - 1, 5539 TemplateParamLists.data()); 5540 } 5541 } else { 5542 // This is a function template specialization. 5543 isFunctionTemplateSpecialization = true; 5544 // For source fidelity, store all the template param lists. 5545 NewFD->setTemplateParameterListsInfo(Context, 5546 TemplateParamLists.size(), 5547 TemplateParamLists.data()); 5548 5549 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 5550 if (isFriend) { 5551 // We want to remove the "template<>", found here. 5552 SourceRange RemoveRange = TemplateParams->getSourceRange(); 5553 5554 // If we remove the template<> and the name is not a 5555 // template-id, we're actually silently creating a problem: 5556 // the friend declaration will refer to an untemplated decl, 5557 // and clearly the user wants a template specialization. So 5558 // we need to insert '<>' after the name. 5559 SourceLocation InsertLoc; 5560 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5561 InsertLoc = D.getName().getSourceRange().getEnd(); 5562 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 5563 } 5564 5565 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 5566 << Name << RemoveRange 5567 << FixItHint::CreateRemoval(RemoveRange) 5568 << FixItHint::CreateInsertion(InsertLoc, "<>"); 5569 } 5570 } 5571 } 5572 else { 5573 // All template param lists were matched against the scope specifier: 5574 // this is NOT (an explicit specialization of) a template. 5575 if (TemplateParamLists.size() > 0) 5576 // For source fidelity, store all the template param lists. 5577 NewFD->setTemplateParameterListsInfo(Context, 5578 TemplateParamLists.size(), 5579 TemplateParamLists.data()); 5580 } 5581 5582 if (Invalid) { 5583 NewFD->setInvalidDecl(); 5584 if (FunctionTemplate) 5585 FunctionTemplate->setInvalidDecl(); 5586 } 5587 5588 // C++ [dcl.fct.spec]p5: 5589 // The virtual specifier shall only be used in declarations of 5590 // nonstatic class member functions that appear within a 5591 // member-specification of a class declaration; see 10.3. 5592 // 5593 if (isVirtual && !NewFD->isInvalidDecl()) { 5594 if (!isVirtualOkay) { 5595 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5596 diag::err_virtual_non_function); 5597 } else if (!CurContext->isRecord()) { 5598 // 'virtual' was specified outside of the class. 5599 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5600 diag::err_virtual_out_of_class) 5601 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5602 } else if (NewFD->getDescribedFunctionTemplate()) { 5603 // C++ [temp.mem]p3: 5604 // A member function template shall not be virtual. 5605 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5606 diag::err_virtual_member_function_template) 5607 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5608 } else { 5609 // Okay: Add virtual to the method. 5610 NewFD->setVirtualAsWritten(true); 5611 } 5612 } 5613 5614 // C++ [dcl.fct.spec]p3: 5615 // The inline specifier shall not appear on a block scope function 5616 // declaration. 5617 if (isInline && !NewFD->isInvalidDecl()) { 5618 if (CurContext->isFunctionOrMethod()) { 5619 // 'inline' is not allowed on block scope function declaration. 5620 Diag(D.getDeclSpec().getInlineSpecLoc(), 5621 diag::err_inline_declaration_block_scope) << Name 5622 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5623 } 5624 } 5625 5626 // C++ [dcl.fct.spec]p6: 5627 // The explicit specifier shall be used only in the declaration of a 5628 // constructor or conversion function within its class definition; 5629 // see 12.3.1 and 12.3.2. 5630 if (isExplicit && !NewFD->isInvalidDecl()) { 5631 if (!CurContext->isRecord()) { 5632 // 'explicit' was specified outside of the class. 5633 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5634 diag::err_explicit_out_of_class) 5635 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5636 } else if (!isa<CXXConstructorDecl>(NewFD) && 5637 !isa<CXXConversionDecl>(NewFD)) { 5638 // 'explicit' was specified on a function that wasn't a constructor 5639 // or conversion function. 5640 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5641 diag::err_explicit_non_ctor_or_conv_function) 5642 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5643 } 5644 } 5645 5646 if (isConstexpr) { 5647 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 5648 // are implicitly inline. 5649 NewFD->setImplicitlyInline(); 5650 5651 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 5652 // be either constructors or to return a literal type. Therefore, 5653 // destructors cannot be declared constexpr. 5654 if (isa<CXXDestructorDecl>(NewFD)) 5655 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 5656 } 5657 5658 // If __module_private__ was specified, mark the function accordingly. 5659 if (D.getDeclSpec().isModulePrivateSpecified()) { 5660 if (isFunctionTemplateSpecialization) { 5661 SourceLocation ModulePrivateLoc 5662 = D.getDeclSpec().getModulePrivateSpecLoc(); 5663 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 5664 << 0 5665 << FixItHint::CreateRemoval(ModulePrivateLoc); 5666 } else { 5667 NewFD->setModulePrivate(); 5668 if (FunctionTemplate) 5669 FunctionTemplate->setModulePrivate(); 5670 } 5671 } 5672 5673 if (isFriend) { 5674 // For now, claim that the objects have no previous declaration. 5675 if (FunctionTemplate) { 5676 FunctionTemplate->setObjectOfFriendDecl(false); 5677 FunctionTemplate->setAccess(AS_public); 5678 } 5679 NewFD->setObjectOfFriendDecl(false); 5680 NewFD->setAccess(AS_public); 5681 } 5682 5683 // If a function is defined as defaulted or deleted, mark it as such now. 5684 switch (D.getFunctionDefinitionKind()) { 5685 case FDK_Declaration: 5686 case FDK_Definition: 5687 break; 5688 5689 case FDK_Defaulted: 5690 NewFD->setDefaulted(); 5691 break; 5692 5693 case FDK_Deleted: 5694 NewFD->setDeletedAsWritten(); 5695 break; 5696 } 5697 5698 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 5699 D.isFunctionDefinition()) { 5700 // C++ [class.mfct]p2: 5701 // A member function may be defined (8.4) in its class definition, in 5702 // which case it is an inline member function (7.1.2) 5703 NewFD->setImplicitlyInline(); 5704 } 5705 5706 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 5707 !CurContext->isRecord()) { 5708 // C++ [class.static]p1: 5709 // A data or function member of a class may be declared static 5710 // in a class definition, in which case it is a static member of 5711 // the class. 5712 5713 // Complain about the 'static' specifier if it's on an out-of-line 5714 // member function definition. 5715 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5716 diag::err_static_out_of_line) 5717 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5718 } 5719 5720 // C++11 [except.spec]p15: 5721 // A deallocation function with no exception-specification is treated 5722 // as if it were specified with noexcept(true). 5723 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 5724 if ((Name.getCXXOverloadedOperator() == OO_Delete || 5725 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 5726 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 5727 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5728 EPI.ExceptionSpecType = EST_BasicNoexcept; 5729 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 5730 FPT->arg_type_begin(), 5731 FPT->getNumArgs(), EPI)); 5732 } 5733 } 5734 5735 // Filter out previous declarations that don't match the scope. 5736 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 5737 isExplicitSpecialization || 5738 isFunctionTemplateSpecialization); 5739 5740 // Handle GNU asm-label extension (encoded as an attribute). 5741 if (Expr *E = (Expr*) D.getAsmLabel()) { 5742 // The parser guarantees this is a string. 5743 StringLiteral *SE = cast<StringLiteral>(E); 5744 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 5745 SE->getString())); 5746 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5747 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5748 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 5749 if (I != ExtnameUndeclaredIdentifiers.end()) { 5750 NewFD->addAttr(I->second); 5751 ExtnameUndeclaredIdentifiers.erase(I); 5752 } 5753 } 5754 5755 // Copy the parameter declarations from the declarator D to the function 5756 // declaration NewFD, if they are available. First scavenge them into Params. 5757 SmallVector<ParmVarDecl*, 16> Params; 5758 if (D.isFunctionDeclarator()) { 5759 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5760 5761 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 5762 // function that takes no arguments, not a function that takes a 5763 // single void argument. 5764 // We let through "const void" here because Sema::GetTypeForDeclarator 5765 // already checks for that case. 5766 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5767 FTI.ArgInfo[0].Param && 5768 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 5769 // Empty arg list, don't push any params. 5770 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 5771 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 5772 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 5773 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 5774 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 5775 Param->setDeclContext(NewFD); 5776 Params.push_back(Param); 5777 5778 if (Param->isInvalidDecl()) 5779 NewFD->setInvalidDecl(); 5780 } 5781 } 5782 5783 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 5784 // When we're declaring a function with a typedef, typeof, etc as in the 5785 // following example, we'll need to synthesize (unnamed) 5786 // parameters for use in the declaration. 5787 // 5788 // @code 5789 // typedef void fn(int); 5790 // fn f; 5791 // @endcode 5792 5793 // Synthesize a parameter for each argument type. 5794 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 5795 AE = FT->arg_type_end(); AI != AE; ++AI) { 5796 ParmVarDecl *Param = 5797 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 5798 Param->setScopeInfo(0, Params.size()); 5799 Params.push_back(Param); 5800 } 5801 } else { 5802 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 5803 "Should not need args for typedef of non-prototype fn"); 5804 } 5805 5806 // Finally, we know we have the right number of parameters, install them. 5807 NewFD->setParams(Params); 5808 5809 // Find all anonymous symbols defined during the declaration of this function 5810 // and add to NewFD. This lets us track decls such 'enum Y' in: 5811 // 5812 // void f(enum Y {AA} x) {} 5813 // 5814 // which would otherwise incorrectly end up in the translation unit scope. 5815 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 5816 DeclsInPrototypeScope.clear(); 5817 5818 // Process the non-inheritable attributes on this declaration. 5819 ProcessDeclAttributes(S, NewFD, D, 5820 /*NonInheritable=*/true, /*Inheritable=*/false); 5821 5822 // Functions returning a variably modified type violate C99 6.7.5.2p2 5823 // because all functions have linkage. 5824 if (!NewFD->isInvalidDecl() && 5825 NewFD->getResultType()->isVariablyModifiedType()) { 5826 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 5827 NewFD->setInvalidDecl(); 5828 } 5829 5830 // Handle attributes. 5831 ProcessDeclAttributes(S, NewFD, D, 5832 /*NonInheritable=*/false, /*Inheritable=*/true); 5833 5834 QualType RetType = NewFD->getResultType(); 5835 const CXXRecordDecl *Ret = RetType->isRecordType() ? 5836 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 5837 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 5838 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 5839 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 5840 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) { 5841 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 5842 Context)); 5843 } 5844 } 5845 5846 if (!getLangOpts().CPlusPlus) { 5847 // Perform semantic checking on the function declaration. 5848 bool isExplicitSpecialization=false; 5849 if (!NewFD->isInvalidDecl()) { 5850 if (NewFD->isMain()) 5851 CheckMain(NewFD, D.getDeclSpec()); 5852 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5853 isExplicitSpecialization)); 5854 } 5855 // Make graceful recovery from an invalid redeclaration. 5856 else if (!Previous.empty()) 5857 D.setRedeclaration(true); 5858 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5859 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5860 "previous declaration set still overloaded"); 5861 } else { 5862 // If the declarator is a template-id, translate the parser's template 5863 // argument list into our AST format. 5864 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5865 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5866 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5867 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5868 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 5869 TemplateId->NumArgs); 5870 translateTemplateArguments(TemplateArgsPtr, 5871 TemplateArgs); 5872 5873 HasExplicitTemplateArgs = true; 5874 5875 if (NewFD->isInvalidDecl()) { 5876 HasExplicitTemplateArgs = false; 5877 } else if (FunctionTemplate) { 5878 // Function template with explicit template arguments. 5879 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 5880 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 5881 5882 HasExplicitTemplateArgs = false; 5883 } else if (!isFunctionTemplateSpecialization && 5884 !D.getDeclSpec().isFriendSpecified()) { 5885 // We have encountered something that the user meant to be a 5886 // specialization (because it has explicitly-specified template 5887 // arguments) but that was not introduced with a "template<>" (or had 5888 // too few of them). 5889 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 5890 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 5891 << FixItHint::CreateInsertion( 5892 D.getDeclSpec().getLocStart(), 5893 "template<> "); 5894 isFunctionTemplateSpecialization = true; 5895 } else { 5896 // "friend void foo<>(int);" is an implicit specialization decl. 5897 isFunctionTemplateSpecialization = true; 5898 } 5899 } else if (isFriend && isFunctionTemplateSpecialization) { 5900 // This combination is only possible in a recovery case; the user 5901 // wrote something like: 5902 // template <> friend void foo(int); 5903 // which we're recovering from as if the user had written: 5904 // friend void foo<>(int); 5905 // Go ahead and fake up a template id. 5906 HasExplicitTemplateArgs = true; 5907 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 5908 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 5909 } 5910 5911 // If it's a friend (and only if it's a friend), it's possible 5912 // that either the specialized function type or the specialized 5913 // template is dependent, and therefore matching will fail. In 5914 // this case, don't check the specialization yet. 5915 bool InstantiationDependent = false; 5916 if (isFunctionTemplateSpecialization && isFriend && 5917 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 5918 TemplateSpecializationType::anyDependentTemplateArguments( 5919 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 5920 InstantiationDependent))) { 5921 assert(HasExplicitTemplateArgs && 5922 "friend function specialization without template args"); 5923 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 5924 Previous)) 5925 NewFD->setInvalidDecl(); 5926 } else if (isFunctionTemplateSpecialization) { 5927 if (CurContext->isDependentContext() && CurContext->isRecord() 5928 && !isFriend) { 5929 isDependentClassScopeExplicitSpecialization = true; 5930 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 5931 diag::ext_function_specialization_in_class : 5932 diag::err_function_specialization_in_class) 5933 << NewFD->getDeclName(); 5934 } else if (CheckFunctionTemplateSpecialization(NewFD, 5935 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5936 Previous)) 5937 NewFD->setInvalidDecl(); 5938 5939 // C++ [dcl.stc]p1: 5940 // A storage-class-specifier shall not be specified in an explicit 5941 // specialization (14.7.3) 5942 if (SC != SC_None) { 5943 if (SC != NewFD->getStorageClass()) 5944 Diag(NewFD->getLocation(), 5945 diag::err_explicit_specialization_inconsistent_storage_class) 5946 << SC 5947 << FixItHint::CreateRemoval( 5948 D.getDeclSpec().getStorageClassSpecLoc()); 5949 5950 else 5951 Diag(NewFD->getLocation(), 5952 diag::ext_explicit_specialization_storage_class) 5953 << FixItHint::CreateRemoval( 5954 D.getDeclSpec().getStorageClassSpecLoc()); 5955 } 5956 5957 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 5958 if (CheckMemberSpecialization(NewFD, Previous)) 5959 NewFD->setInvalidDecl(); 5960 } 5961 5962 // Perform semantic checking on the function declaration. 5963 if (!isDependentClassScopeExplicitSpecialization) { 5964 if (NewFD->isInvalidDecl()) { 5965 // If this is a class member, mark the class invalid immediately. 5966 // This avoids some consistency errors later. 5967 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 5968 methodDecl->getParent()->setInvalidDecl(); 5969 } else { 5970 if (NewFD->isMain()) 5971 CheckMain(NewFD, D.getDeclSpec()); 5972 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 5973 isExplicitSpecialization)); 5974 } 5975 } 5976 5977 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 5978 Previous.getResultKind() != LookupResult::FoundOverloaded) && 5979 "previous declaration set still overloaded"); 5980 5981 NamedDecl *PrincipalDecl = (FunctionTemplate 5982 ? cast<NamedDecl>(FunctionTemplate) 5983 : NewFD); 5984 5985 if (isFriend && D.isRedeclaration()) { 5986 AccessSpecifier Access = AS_public; 5987 if (!NewFD->isInvalidDecl()) 5988 Access = NewFD->getPreviousDecl()->getAccess(); 5989 5990 NewFD->setAccess(Access); 5991 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 5992 5993 PrincipalDecl->setObjectOfFriendDecl(true); 5994 } 5995 5996 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 5997 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5998 PrincipalDecl->setNonMemberOperator(); 5999 6000 // If we have a function template, check the template parameter 6001 // list. This will check and merge default template arguments. 6002 if (FunctionTemplate) { 6003 FunctionTemplateDecl *PrevTemplate = 6004 FunctionTemplate->getPreviousDecl(); 6005 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 6006 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 6007 D.getDeclSpec().isFriendSpecified() 6008 ? (D.isFunctionDefinition() 6009 ? TPC_FriendFunctionTemplateDefinition 6010 : TPC_FriendFunctionTemplate) 6011 : (D.getCXXScopeSpec().isSet() && 6012 DC && DC->isRecord() && 6013 DC->isDependentContext()) 6014 ? TPC_ClassTemplateMember 6015 : TPC_FunctionTemplate); 6016 } 6017 6018 if (NewFD->isInvalidDecl()) { 6019 // Ignore all the rest of this. 6020 } else if (!D.isRedeclaration()) { 6021 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 6022 AddToScope }; 6023 // Fake up an access specifier if it's supposed to be a class member. 6024 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 6025 NewFD->setAccess(AS_public); 6026 6027 // Qualified decls generally require a previous declaration. 6028 if (D.getCXXScopeSpec().isSet()) { 6029 // ...with the major exception of templated-scope or 6030 // dependent-scope friend declarations. 6031 6032 // TODO: we currently also suppress this check in dependent 6033 // contexts because (1) the parameter depth will be off when 6034 // matching friend templates and (2) we might actually be 6035 // selecting a friend based on a dependent factor. But there 6036 // are situations where these conditions don't apply and we 6037 // can actually do this check immediately. 6038 if (isFriend && 6039 (TemplateParamLists.size() || 6040 D.getCXXScopeSpec().getScopeRep()->isDependent() || 6041 CurContext->isDependentContext())) { 6042 // ignore these 6043 } else { 6044 // The user tried to provide an out-of-line definition for a 6045 // function that is a member of a class or namespace, but there 6046 // was no such member function declared (C++ [class.mfct]p2, 6047 // C++ [namespace.memdef]p2). For example: 6048 // 6049 // class X { 6050 // void f() const; 6051 // }; 6052 // 6053 // void X::f() { } // ill-formed 6054 // 6055 // Complain about this problem, and attempt to suggest close 6056 // matches (e.g., those that differ only in cv-qualifiers and 6057 // whether the parameter types are references). 6058 6059 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6060 NewFD, 6061 ExtraArgs)) { 6062 AddToScope = ExtraArgs.AddToScope; 6063 return Result; 6064 } 6065 } 6066 6067 // Unqualified local friend declarations are required to resolve 6068 // to something. 6069 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 6070 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6071 NewFD, 6072 ExtraArgs)) { 6073 AddToScope = ExtraArgs.AddToScope; 6074 return Result; 6075 } 6076 } 6077 6078 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 6079 !isFriend && !isFunctionTemplateSpecialization && 6080 !isExplicitSpecialization) { 6081 // An out-of-line member function declaration must also be a 6082 // definition (C++ [dcl.meaning]p1). 6083 // Note that this is not the case for explicit specializations of 6084 // function templates or member functions of class templates, per 6085 // C++ [temp.expl.spec]p2. We also allow these declarations as an 6086 // extension for compatibility with old SWIG code which likes to 6087 // generate them. 6088 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 6089 << D.getCXXScopeSpec().getRange(); 6090 } 6091 } 6092 6093 checkAttributesAfterMerging(*this, *NewFD); 6094 6095 AddKnownFunctionAttributes(NewFD); 6096 6097 if (NewFD->hasAttr<OverloadableAttr>() && 6098 !NewFD->getType()->getAs<FunctionProtoType>()) { 6099 Diag(NewFD->getLocation(), 6100 diag::err_attribute_overloadable_no_prototype) 6101 << NewFD; 6102 6103 // Turn this into a variadic function with no parameters. 6104 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 6105 FunctionProtoType::ExtProtoInfo EPI; 6106 EPI.Variadic = true; 6107 EPI.ExtInfo = FT->getExtInfo(); 6108 6109 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 6110 NewFD->setType(R); 6111 } 6112 6113 // If there's a #pragma GCC visibility in scope, and this isn't a class 6114 // member, set the visibility of this function. 6115 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 6116 AddPushedVisibilityAttribute(NewFD); 6117 6118 // If there's a #pragma clang arc_cf_code_audited in scope, consider 6119 // marking the function. 6120 AddCFAuditedAttribute(NewFD); 6121 6122 // If this is a locally-scoped extern C function, update the 6123 // map of such names. 6124 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 6125 && !NewFD->isInvalidDecl()) 6126 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 6127 6128 // Set this FunctionDecl's range up to the right paren. 6129 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 6130 6131 if (getLangOpts().CPlusPlus) { 6132 if (FunctionTemplate) { 6133 if (NewFD->isInvalidDecl()) 6134 FunctionTemplate->setInvalidDecl(); 6135 return FunctionTemplate; 6136 } 6137 } 6138 6139 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 6140 if ((getLangOpts().OpenCLVersion >= 120) 6141 && NewFD->hasAttr<OpenCLKernelAttr>() 6142 && (SC == SC_Static)) { 6143 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 6144 D.setInvalidType(); 6145 } 6146 6147 MarkUnusedFileScopedDecl(NewFD); 6148 6149 if (getLangOpts().CUDA) 6150 if (IdentifierInfo *II = NewFD->getIdentifier()) 6151 if (!NewFD->isInvalidDecl() && 6152 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6153 if (II->isStr("cudaConfigureCall")) { 6154 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 6155 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 6156 6157 Context.setcudaConfigureCallDecl(NewFD); 6158 } 6159 } 6160 6161 // Here we have an function template explicit specialization at class scope. 6162 // The actually specialization will be postponed to template instatiation 6163 // time via the ClassScopeFunctionSpecializationDecl node. 6164 if (isDependentClassScopeExplicitSpecialization) { 6165 ClassScopeFunctionSpecializationDecl *NewSpec = 6166 ClassScopeFunctionSpecializationDecl::Create( 6167 Context, CurContext, SourceLocation(), 6168 cast<CXXMethodDecl>(NewFD), 6169 HasExplicitTemplateArgs, TemplateArgs); 6170 CurContext->addDecl(NewSpec); 6171 AddToScope = false; 6172 } 6173 6174 return NewFD; 6175} 6176 6177/// \brief Perform semantic checking of a new function declaration. 6178/// 6179/// Performs semantic analysis of the new function declaration 6180/// NewFD. This routine performs all semantic checking that does not 6181/// require the actual declarator involved in the declaration, and is 6182/// used both for the declaration of functions as they are parsed 6183/// (called via ActOnDeclarator) and for the declaration of functions 6184/// that have been instantiated via C++ template instantiation (called 6185/// via InstantiateDecl). 6186/// 6187/// \param IsExplicitSpecialization whether this new function declaration is 6188/// an explicit specialization of the previous declaration. 6189/// 6190/// This sets NewFD->isInvalidDecl() to true if there was an error. 6191/// 6192/// \returns true if the function declaration is a redeclaration. 6193bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 6194 LookupResult &Previous, 6195 bool IsExplicitSpecialization) { 6196 assert(!NewFD->getResultType()->isVariablyModifiedType() 6197 && "Variably modified return types are not handled here"); 6198 6199 // Check for a previous declaration of this name. 6200 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewFD)) { 6201 // Since we did not find anything by this name, look for a non-visible 6202 // extern "C" declaration with the same name. 6203 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6204 = findLocallyScopedExternCDecl(NewFD->getDeclName()); 6205 if (Pos != LocallyScopedExternCDecls.end()) 6206 Previous.addDecl(Pos->second); 6207 } 6208 6209 // Filter out any non-conflicting previous declarations. 6210 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 6211 6212 bool Redeclaration = false; 6213 NamedDecl *OldDecl = 0; 6214 6215 // Merge or overload the declaration with an existing declaration of 6216 // the same name, if appropriate. 6217 if (!Previous.empty()) { 6218 // Determine whether NewFD is an overload of PrevDecl or 6219 // a declaration that requires merging. If it's an overload, 6220 // there's no more work to do here; we'll just add the new 6221 // function to the scope. 6222 if (!AllowOverloadingOfFunction(Previous, Context)) { 6223 Redeclaration = true; 6224 OldDecl = Previous.getFoundDecl(); 6225 } else { 6226 switch (CheckOverload(S, NewFD, Previous, OldDecl, 6227 /*NewIsUsingDecl*/ false)) { 6228 case Ovl_Match: 6229 Redeclaration = true; 6230 break; 6231 6232 case Ovl_NonFunction: 6233 Redeclaration = true; 6234 break; 6235 6236 case Ovl_Overload: 6237 Redeclaration = false; 6238 break; 6239 } 6240 6241 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 6242 // If a function name is overloadable in C, then every function 6243 // with that name must be marked "overloadable". 6244 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 6245 << Redeclaration << NewFD; 6246 NamedDecl *OverloadedDecl = 0; 6247 if (Redeclaration) 6248 OverloadedDecl = OldDecl; 6249 else if (!Previous.empty()) 6250 OverloadedDecl = Previous.getRepresentativeDecl(); 6251 if (OverloadedDecl) 6252 Diag(OverloadedDecl->getLocation(), 6253 diag::note_attribute_overloadable_prev_overload); 6254 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 6255 Context)); 6256 } 6257 } 6258 } 6259 6260 // C++11 [dcl.constexpr]p8: 6261 // A constexpr specifier for a non-static member function that is not 6262 // a constructor declares that member function to be const. 6263 // 6264 // This needs to be delayed until we know whether this is an out-of-line 6265 // definition of a static member function. 6266 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6267 if (MD && MD->isConstexpr() && !MD->isStatic() && 6268 !isa<CXXConstructorDecl>(MD) && 6269 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 6270 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 6271 if (FunctionTemplateDecl *OldTD = 6272 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 6273 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 6274 if (!OldMD || !OldMD->isStatic()) { 6275 const FunctionProtoType *FPT = 6276 MD->getType()->castAs<FunctionProtoType>(); 6277 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6278 EPI.TypeQuals |= Qualifiers::Const; 6279 MD->setType(Context.getFunctionType(FPT->getResultType(), 6280 FPT->arg_type_begin(), 6281 FPT->getNumArgs(), EPI)); 6282 } 6283 } 6284 6285 if (Redeclaration) { 6286 // NewFD and OldDecl represent declarations that need to be 6287 // merged. 6288 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 6289 NewFD->setInvalidDecl(); 6290 return Redeclaration; 6291 } 6292 6293 Previous.clear(); 6294 Previous.addDecl(OldDecl); 6295 6296 if (FunctionTemplateDecl *OldTemplateDecl 6297 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 6298 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 6299 FunctionTemplateDecl *NewTemplateDecl 6300 = NewFD->getDescribedFunctionTemplate(); 6301 assert(NewTemplateDecl && "Template/non-template mismatch"); 6302 if (CXXMethodDecl *Method 6303 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 6304 Method->setAccess(OldTemplateDecl->getAccess()); 6305 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 6306 } 6307 6308 // If this is an explicit specialization of a member that is a function 6309 // template, mark it as a member specialization. 6310 if (IsExplicitSpecialization && 6311 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 6312 NewTemplateDecl->setMemberSpecialization(); 6313 assert(OldTemplateDecl->isMemberSpecialization()); 6314 } 6315 6316 } else { 6317 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 6318 NewFD->setAccess(OldDecl->getAccess()); 6319 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 6320 } 6321 } 6322 6323 // Semantic checking for this function declaration (in isolation). 6324 if (getLangOpts().CPlusPlus) { 6325 // C++-specific checks. 6326 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 6327 CheckConstructor(Constructor); 6328 } else if (CXXDestructorDecl *Destructor = 6329 dyn_cast<CXXDestructorDecl>(NewFD)) { 6330 CXXRecordDecl *Record = Destructor->getParent(); 6331 QualType ClassType = Context.getTypeDeclType(Record); 6332 6333 // FIXME: Shouldn't we be able to perform this check even when the class 6334 // type is dependent? Both gcc and edg can handle that. 6335 if (!ClassType->isDependentType()) { 6336 DeclarationName Name 6337 = Context.DeclarationNames.getCXXDestructorName( 6338 Context.getCanonicalType(ClassType)); 6339 if (NewFD->getDeclName() != Name) { 6340 Diag(NewFD->getLocation(), diag::err_destructor_name); 6341 NewFD->setInvalidDecl(); 6342 return Redeclaration; 6343 } 6344 } 6345 } else if (CXXConversionDecl *Conversion 6346 = dyn_cast<CXXConversionDecl>(NewFD)) { 6347 ActOnConversionDeclarator(Conversion); 6348 } 6349 6350 // Find any virtual functions that this function overrides. 6351 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 6352 if (!Method->isFunctionTemplateSpecialization() && 6353 !Method->getDescribedFunctionTemplate() && 6354 Method->isCanonicalDecl()) { 6355 if (AddOverriddenMethods(Method->getParent(), Method)) { 6356 // If the function was marked as "static", we have a problem. 6357 if (NewFD->getStorageClass() == SC_Static) { 6358 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 6359 } 6360 } 6361 } 6362 6363 if (Method->isStatic()) 6364 checkThisInStaticMemberFunctionType(Method); 6365 } 6366 6367 // Extra checking for C++ overloaded operators (C++ [over.oper]). 6368 if (NewFD->isOverloadedOperator() && 6369 CheckOverloadedOperatorDeclaration(NewFD)) { 6370 NewFD->setInvalidDecl(); 6371 return Redeclaration; 6372 } 6373 6374 // Extra checking for C++0x literal operators (C++0x [over.literal]). 6375 if (NewFD->getLiteralIdentifier() && 6376 CheckLiteralOperatorDeclaration(NewFD)) { 6377 NewFD->setInvalidDecl(); 6378 return Redeclaration; 6379 } 6380 6381 // In C++, check default arguments now that we have merged decls. Unless 6382 // the lexical context is the class, because in this case this is done 6383 // during delayed parsing anyway. 6384 if (!CurContext->isRecord()) 6385 CheckCXXDefaultArguments(NewFD); 6386 6387 // If this function declares a builtin function, check the type of this 6388 // declaration against the expected type for the builtin. 6389 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 6390 ASTContext::GetBuiltinTypeError Error; 6391 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 6392 QualType T = Context.GetBuiltinType(BuiltinID, Error); 6393 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 6394 // The type of this function differs from the type of the builtin, 6395 // so forget about the builtin entirely. 6396 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 6397 } 6398 } 6399 6400 // If this function is declared as being extern "C", then check to see if 6401 // the function returns a UDT (class, struct, or union type) that is not C 6402 // compatible, and if it does, warn the user. 6403 if (NewFD->hasCLanguageLinkage()) { 6404 QualType R = NewFD->getResultType(); 6405 if (R->isIncompleteType() && !R->isVoidType()) 6406 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 6407 << NewFD << R; 6408 else if (!R.isPODType(Context) && !R->isVoidType() && 6409 !R->isObjCObjectPointerType()) 6410 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 6411 } 6412 } 6413 return Redeclaration; 6414} 6415 6416static SourceRange getResultSourceRange(const FunctionDecl *FD) { 6417 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6418 if (!TSI) 6419 return SourceRange(); 6420 6421 TypeLoc TL = TSI->getTypeLoc(); 6422 FunctionTypeLoc *FunctionTL = dyn_cast<FunctionTypeLoc>(&TL); 6423 if (!FunctionTL) 6424 return SourceRange(); 6425 6426 TypeLoc ResultTL = FunctionTL->getResultLoc(); 6427 if (isa<BuiltinTypeLoc>(ResultTL.getUnqualifiedLoc())) 6428 return ResultTL.getSourceRange(); 6429 6430 return SourceRange(); 6431} 6432 6433void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 6434 // C++11 [basic.start.main]p3: A program that declares main to be inline, 6435 // static or constexpr is ill-formed. 6436 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 6437 // appear in a declaration of main. 6438 // static main is not an error under C99, but we should warn about it. 6439 // We accept _Noreturn main as an extension. 6440 if (FD->getStorageClass() == SC_Static) 6441 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 6442 ? diag::err_static_main : diag::warn_static_main) 6443 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 6444 if (FD->isInlineSpecified()) 6445 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 6446 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 6447 if (DS.isNoreturnSpecified()) 6448 Diag(DS.getNoreturnSpecLoc(), diag::ext_noreturn_main); 6449 if (FD->isConstexpr()) { 6450 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 6451 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 6452 FD->setConstexpr(false); 6453 } 6454 6455 QualType T = FD->getType(); 6456 assert(T->isFunctionType() && "function decl is not of function type"); 6457 const FunctionType* FT = T->castAs<FunctionType>(); 6458 6459 // All the standards say that main() should should return 'int'. 6460 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 6461 // In C and C++, main magically returns 0 if you fall off the end; 6462 // set the flag which tells us that. 6463 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6464 FD->setHasImplicitReturnZero(true); 6465 6466 // In C with GNU extensions we allow main() to have non-integer return 6467 // type, but we should warn about the extension, and we disable the 6468 // implicit-return-zero rule. 6469 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 6470 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 6471 6472 SourceRange ResultRange = getResultSourceRange(FD); 6473 if (ResultRange.isValid()) 6474 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 6475 << FixItHint::CreateReplacement(ResultRange, "int"); 6476 6477 // Otherwise, this is just a flat-out error. 6478 } else { 6479 SourceRange ResultRange = getResultSourceRange(FD); 6480 if (ResultRange.isValid()) 6481 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 6482 << FixItHint::CreateReplacement(ResultRange, "int"); 6483 else 6484 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 6485 6486 FD->setInvalidDecl(true); 6487 } 6488 6489 // Treat protoless main() as nullary. 6490 if (isa<FunctionNoProtoType>(FT)) return; 6491 6492 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 6493 unsigned nparams = FTP->getNumArgs(); 6494 assert(FD->getNumParams() == nparams); 6495 6496 bool HasExtraParameters = (nparams > 3); 6497 6498 // Darwin passes an undocumented fourth argument of type char**. If 6499 // other platforms start sprouting these, the logic below will start 6500 // getting shifty. 6501 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 6502 HasExtraParameters = false; 6503 6504 if (HasExtraParameters) { 6505 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 6506 FD->setInvalidDecl(true); 6507 nparams = 3; 6508 } 6509 6510 // FIXME: a lot of the following diagnostics would be improved 6511 // if we had some location information about types. 6512 6513 QualType CharPP = 6514 Context.getPointerType(Context.getPointerType(Context.CharTy)); 6515 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 6516 6517 for (unsigned i = 0; i < nparams; ++i) { 6518 QualType AT = FTP->getArgType(i); 6519 6520 bool mismatch = true; 6521 6522 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 6523 mismatch = false; 6524 else if (Expected[i] == CharPP) { 6525 // As an extension, the following forms are okay: 6526 // char const ** 6527 // char const * const * 6528 // char * const * 6529 6530 QualifierCollector qs; 6531 const PointerType* PT; 6532 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 6533 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 6534 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 6535 qs.removeConst(); 6536 mismatch = !qs.empty(); 6537 } 6538 } 6539 6540 if (mismatch) { 6541 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 6542 // TODO: suggest replacing given type with expected type 6543 FD->setInvalidDecl(true); 6544 } 6545 } 6546 6547 if (nparams == 1 && !FD->isInvalidDecl()) { 6548 Diag(FD->getLocation(), diag::warn_main_one_arg); 6549 } 6550 6551 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 6552 Diag(FD->getLocation(), diag::err_main_template_decl); 6553 FD->setInvalidDecl(); 6554 } 6555} 6556 6557bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 6558 // FIXME: Need strict checking. In C89, we need to check for 6559 // any assignment, increment, decrement, function-calls, or 6560 // commas outside of a sizeof. In C99, it's the same list, 6561 // except that the aforementioned are allowed in unevaluated 6562 // expressions. Everything else falls under the 6563 // "may accept other forms of constant expressions" exception. 6564 // (We never end up here for C++, so the constant expression 6565 // rules there don't matter.) 6566 if (Init->isConstantInitializer(Context, false)) 6567 return false; 6568 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 6569 << Init->getSourceRange(); 6570 return true; 6571} 6572 6573namespace { 6574 // Visits an initialization expression to see if OrigDecl is evaluated in 6575 // its own initialization and throws a warning if it does. 6576 class SelfReferenceChecker 6577 : public EvaluatedExprVisitor<SelfReferenceChecker> { 6578 Sema &S; 6579 Decl *OrigDecl; 6580 bool isRecordType; 6581 bool isPODType; 6582 bool isReferenceType; 6583 6584 public: 6585 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 6586 6587 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 6588 S(S), OrigDecl(OrigDecl) { 6589 isPODType = false; 6590 isRecordType = false; 6591 isReferenceType = false; 6592 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 6593 isPODType = VD->getType().isPODType(S.Context); 6594 isRecordType = VD->getType()->isRecordType(); 6595 isReferenceType = VD->getType()->isReferenceType(); 6596 } 6597 } 6598 6599 // For most expressions, the cast is directly above the DeclRefExpr. 6600 // For conditional operators, the cast can be outside the conditional 6601 // operator if both expressions are DeclRefExpr's. 6602 void HandleValue(Expr *E) { 6603 if (isReferenceType) 6604 return; 6605 E = E->IgnoreParenImpCasts(); 6606 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 6607 HandleDeclRefExpr(DRE); 6608 return; 6609 } 6610 6611 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 6612 HandleValue(CO->getTrueExpr()); 6613 HandleValue(CO->getFalseExpr()); 6614 return; 6615 } 6616 6617 if (isa<MemberExpr>(E)) { 6618 Expr *Base = E->IgnoreParenImpCasts(); 6619 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 6620 // Check for static member variables and don't warn on them. 6621 if (!isa<FieldDecl>(ME->getMemberDecl())) 6622 return; 6623 Base = ME->getBase()->IgnoreParenImpCasts(); 6624 } 6625 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 6626 HandleDeclRefExpr(DRE); 6627 return; 6628 } 6629 } 6630 6631 // Reference types are handled here since all uses of references are 6632 // bad, not just r-value uses. 6633 void VisitDeclRefExpr(DeclRefExpr *E) { 6634 if (isReferenceType) 6635 HandleDeclRefExpr(E); 6636 } 6637 6638 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 6639 if (E->getCastKind() == CK_LValueToRValue || 6640 (isRecordType && E->getCastKind() == CK_NoOp)) 6641 HandleValue(E->getSubExpr()); 6642 6643 Inherited::VisitImplicitCastExpr(E); 6644 } 6645 6646 void VisitMemberExpr(MemberExpr *E) { 6647 // Don't warn on arrays since they can be treated as pointers. 6648 if (E->getType()->canDecayToPointerType()) return; 6649 6650 // Warn when a non-static method call is followed by non-static member 6651 // field accesses, which is followed by a DeclRefExpr. 6652 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 6653 bool Warn = (MD && !MD->isStatic()); 6654 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 6655 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 6656 if (!isa<FieldDecl>(ME->getMemberDecl())) 6657 Warn = false; 6658 Base = ME->getBase()->IgnoreParenImpCasts(); 6659 } 6660 6661 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 6662 if (Warn) 6663 HandleDeclRefExpr(DRE); 6664 return; 6665 } 6666 6667 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 6668 // Visit that expression. 6669 Visit(Base); 6670 } 6671 6672 void VisitUnaryOperator(UnaryOperator *E) { 6673 // For POD record types, addresses of its own members are well-defined. 6674 if (E->getOpcode() == UO_AddrOf && isRecordType && 6675 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 6676 if (!isPODType) 6677 HandleValue(E->getSubExpr()); 6678 return; 6679 } 6680 Inherited::VisitUnaryOperator(E); 6681 } 6682 6683 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 6684 6685 void HandleDeclRefExpr(DeclRefExpr *DRE) { 6686 Decl* ReferenceDecl = DRE->getDecl(); 6687 if (OrigDecl != ReferenceDecl) return; 6688 unsigned diag = isReferenceType 6689 ? diag::warn_uninit_self_reference_in_reference_init 6690 : diag::warn_uninit_self_reference_in_init; 6691 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 6692 S.PDiag(diag) 6693 << DRE->getNameInfo().getName() 6694 << OrigDecl->getLocation() 6695 << DRE->getSourceRange()); 6696 } 6697 }; 6698 6699 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 6700 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 6701 bool DirectInit) { 6702 // Parameters arguments are occassionially constructed with itself, 6703 // for instance, in recursive functions. Skip them. 6704 if (isa<ParmVarDecl>(OrigDecl)) 6705 return; 6706 6707 E = E->IgnoreParens(); 6708 6709 // Skip checking T a = a where T is not a record or reference type. 6710 // Doing so is a way to silence uninitialized warnings. 6711 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 6712 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 6713 if (ICE->getCastKind() == CK_LValueToRValue) 6714 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 6715 if (DRE->getDecl() == OrigDecl) 6716 return; 6717 6718 SelfReferenceChecker(S, OrigDecl).Visit(E); 6719 } 6720} 6721 6722/// AddInitializerToDecl - Adds the initializer Init to the 6723/// declaration dcl. If DirectInit is true, this is C++ direct 6724/// initialization rather than copy initialization. 6725void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 6726 bool DirectInit, bool TypeMayContainAuto) { 6727 // If there is no declaration, there was an error parsing it. Just ignore 6728 // the initializer. 6729 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 6730 return; 6731 6732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 6733 // With declarators parsed the way they are, the parser cannot 6734 // distinguish between a normal initializer and a pure-specifier. 6735 // Thus this grotesque test. 6736 IntegerLiteral *IL; 6737 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 6738 Context.getCanonicalType(IL->getType()) == Context.IntTy) 6739 CheckPureMethod(Method, Init->getSourceRange()); 6740 else { 6741 Diag(Method->getLocation(), diag::err_member_function_initialization) 6742 << Method->getDeclName() << Init->getSourceRange(); 6743 Method->setInvalidDecl(); 6744 } 6745 return; 6746 } 6747 6748 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 6749 if (!VDecl) { 6750 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 6751 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 6752 RealDecl->setInvalidDecl(); 6753 return; 6754 } 6755 6756 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 6757 6758 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 6759 AutoType *Auto = 0; 6760 if (TypeMayContainAuto && 6761 (Auto = VDecl->getType()->getContainedAutoType()) && 6762 !Auto->isDeduced()) { 6763 Expr *DeduceInit = Init; 6764 // Initializer could be a C++ direct-initializer. Deduction only works if it 6765 // contains exactly one expression. 6766 if (CXXDirectInit) { 6767 if (CXXDirectInit->getNumExprs() == 0) { 6768 // It isn't possible to write this directly, but it is possible to 6769 // end up in this situation with "auto x(some_pack...);" 6770 Diag(CXXDirectInit->getLocStart(), 6771 diag::err_auto_var_init_no_expression) 6772 << VDecl->getDeclName() << VDecl->getType() 6773 << VDecl->getSourceRange(); 6774 RealDecl->setInvalidDecl(); 6775 return; 6776 } else if (CXXDirectInit->getNumExprs() > 1) { 6777 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 6778 diag::err_auto_var_init_multiple_expressions) 6779 << VDecl->getDeclName() << VDecl->getType() 6780 << VDecl->getSourceRange(); 6781 RealDecl->setInvalidDecl(); 6782 return; 6783 } else { 6784 DeduceInit = CXXDirectInit->getExpr(0); 6785 } 6786 } 6787 TypeSourceInfo *DeducedType = 0; 6788 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 6789 DAR_Failed) 6790 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 6791 if (!DeducedType) { 6792 RealDecl->setInvalidDecl(); 6793 return; 6794 } 6795 VDecl->setTypeSourceInfo(DeducedType); 6796 VDecl->setType(DeducedType->getType()); 6797 VDecl->ClearLinkageCache(); 6798 6799 // In ARC, infer lifetime. 6800 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 6801 VDecl->setInvalidDecl(); 6802 6803 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 6804 // 'id' instead of a specific object type prevents most of our usual checks. 6805 // We only want to warn outside of template instantiations, though: 6806 // inside a template, the 'id' could have come from a parameter. 6807 if (ActiveTemplateInstantiations.empty() && 6808 DeducedType->getType()->isObjCIdType()) { 6809 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); 6810 Diag(Loc, diag::warn_auto_var_is_id) 6811 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 6812 } 6813 6814 // If this is a redeclaration, check that the type we just deduced matches 6815 // the previously declared type. 6816 if (VarDecl *Old = VDecl->getPreviousDecl()) 6817 MergeVarDeclTypes(VDecl, Old); 6818 } 6819 6820 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 6821 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 6822 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 6823 VDecl->setInvalidDecl(); 6824 return; 6825 } 6826 6827 if (!VDecl->getType()->isDependentType()) { 6828 // A definition must end up with a complete type, which means it must be 6829 // complete with the restriction that an array type might be completed by 6830 // the initializer; note that later code assumes this restriction. 6831 QualType BaseDeclType = VDecl->getType(); 6832 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 6833 BaseDeclType = Array->getElementType(); 6834 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 6835 diag::err_typecheck_decl_incomplete_type)) { 6836 RealDecl->setInvalidDecl(); 6837 return; 6838 } 6839 6840 // The variable can not have an abstract class type. 6841 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 6842 diag::err_abstract_type_in_decl, 6843 AbstractVariableType)) 6844 VDecl->setInvalidDecl(); 6845 } 6846 6847 const VarDecl *Def; 6848 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 6849 Diag(VDecl->getLocation(), diag::err_redefinition) 6850 << VDecl->getDeclName(); 6851 Diag(Def->getLocation(), diag::note_previous_definition); 6852 VDecl->setInvalidDecl(); 6853 return; 6854 } 6855 6856 const VarDecl* PrevInit = 0; 6857 if (getLangOpts().CPlusPlus) { 6858 // C++ [class.static.data]p4 6859 // If a static data member is of const integral or const 6860 // enumeration type, its declaration in the class definition can 6861 // specify a constant-initializer which shall be an integral 6862 // constant expression (5.19). In that case, the member can appear 6863 // in integral constant expressions. The member shall still be 6864 // defined in a namespace scope if it is used in the program and the 6865 // namespace scope definition shall not contain an initializer. 6866 // 6867 // We already performed a redefinition check above, but for static 6868 // data members we also need to check whether there was an in-class 6869 // declaration with an initializer. 6870 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6871 Diag(VDecl->getLocation(), diag::err_redefinition) 6872 << VDecl->getDeclName(); 6873 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6874 return; 6875 } 6876 6877 if (VDecl->hasLocalStorage()) 6878 getCurFunction()->setHasBranchProtectedScope(); 6879 6880 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 6881 VDecl->setInvalidDecl(); 6882 return; 6883 } 6884 } 6885 6886 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 6887 // a kernel function cannot be initialized." 6888 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 6889 Diag(VDecl->getLocation(), diag::err_local_cant_init); 6890 VDecl->setInvalidDecl(); 6891 return; 6892 } 6893 6894 // Get the decls type and save a reference for later, since 6895 // CheckInitializerTypes may change it. 6896 QualType DclT = VDecl->getType(), SavT = DclT; 6897 6898 // Top-level message sends default to 'id' when we're in a debugger 6899 // and we are assigning it to a variable of 'id' type. 6900 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType()) 6901 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) { 6902 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 6903 if (Result.isInvalid()) { 6904 VDecl->setInvalidDecl(); 6905 return; 6906 } 6907 Init = Result.take(); 6908 } 6909 6910 // Perform the initialization. 6911 if (!VDecl->isInvalidDecl()) { 6912 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6913 InitializationKind Kind 6914 = DirectInit ? 6915 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 6916 Init->getLocStart(), 6917 Init->getLocEnd()) 6918 : InitializationKind::CreateDirectList( 6919 VDecl->getLocation()) 6920 : InitializationKind::CreateCopy(VDecl->getLocation(), 6921 Init->getLocStart()); 6922 6923 Expr **Args = &Init; 6924 unsigned NumArgs = 1; 6925 if (CXXDirectInit) { 6926 Args = CXXDirectInit->getExprs(); 6927 NumArgs = CXXDirectInit->getNumExprs(); 6928 } 6929 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 6930 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 6931 MultiExprArg(Args, NumArgs), &DclT); 6932 if (Result.isInvalid()) { 6933 VDecl->setInvalidDecl(); 6934 return; 6935 } 6936 6937 Init = Result.takeAs<Expr>(); 6938 } 6939 6940 // Check for self-references within variable initializers. 6941 // Variables declared within a function/method body (except for references) 6942 // are handled by a dataflow analysis. 6943 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 6944 VDecl->getType()->isReferenceType()) { 6945 CheckSelfReference(*this, RealDecl, Init, DirectInit); 6946 } 6947 6948 // If the type changed, it means we had an incomplete type that was 6949 // completed by the initializer. For example: 6950 // int ary[] = { 1, 3, 5 }; 6951 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 6952 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 6953 VDecl->setType(DclT); 6954 6955 if (!VDecl->isInvalidDecl()) { 6956 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 6957 6958 if (VDecl->hasAttr<BlocksAttr>()) 6959 checkRetainCycles(VDecl, Init); 6960 6961 // It is safe to assign a weak reference into a strong variable. 6962 // Although this code can still have problems: 6963 // id x = self.weakProp; 6964 // id y = self.weakProp; 6965 // we do not warn to warn spuriously when 'x' and 'y' are on separate 6966 // paths through the function. This should be revisited if 6967 // -Wrepeated-use-of-weak is made flow-sensitive. 6968 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 6969 DiagnosticsEngine::Level Level = 6970 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 6971 Init->getLocStart()); 6972 if (Level != DiagnosticsEngine::Ignored) 6973 getCurFunction()->markSafeWeakUse(Init); 6974 } 6975 } 6976 6977 // The initialization is usually a full-expression. 6978 // 6979 // FIXME: If this is a braced initialization of an aggregate, it is not 6980 // an expression, and each individual field initializer is a separate 6981 // full-expression. For instance, in: 6982 // 6983 // struct Temp { ~Temp(); }; 6984 // struct S { S(Temp); }; 6985 // struct T { S a, b; } t = { Temp(), Temp() } 6986 // 6987 // we should destroy the first Temp before constructing the second. 6988 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation()); 6989 if (Result.isInvalid()) { 6990 VDecl->setInvalidDecl(); 6991 return; 6992 } 6993 Init = Result.take(); 6994 6995 // Attach the initializer to the decl. 6996 VDecl->setInit(Init); 6997 6998 if (VDecl->isLocalVarDecl()) { 6999 // C99 6.7.8p4: All the expressions in an initializer for an object that has 7000 // static storage duration shall be constant expressions or string literals. 7001 // C++ does not have this restriction. 7002 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 7003 VDecl->getStorageClass() == SC_Static) 7004 CheckForConstantInitializer(Init, DclT); 7005 } else if (VDecl->isStaticDataMember() && 7006 VDecl->getLexicalDeclContext()->isRecord()) { 7007 // This is an in-class initialization for a static data member, e.g., 7008 // 7009 // struct S { 7010 // static const int value = 17; 7011 // }; 7012 7013 // C++ [class.mem]p4: 7014 // A member-declarator can contain a constant-initializer only 7015 // if it declares a static member (9.4) of const integral or 7016 // const enumeration type, see 9.4.2. 7017 // 7018 // C++11 [class.static.data]p3: 7019 // If a non-volatile const static data member is of integral or 7020 // enumeration type, its declaration in the class definition can 7021 // specify a brace-or-equal-initializer in which every initalizer-clause 7022 // that is an assignment-expression is a constant expression. A static 7023 // data member of literal type can be declared in the class definition 7024 // with the constexpr specifier; if so, its declaration shall specify a 7025 // brace-or-equal-initializer in which every initializer-clause that is 7026 // an assignment-expression is a constant expression. 7027 7028 // Do nothing on dependent types. 7029 if (DclT->isDependentType()) { 7030 7031 // Allow any 'static constexpr' members, whether or not they are of literal 7032 // type. We separately check that every constexpr variable is of literal 7033 // type. 7034 } else if (VDecl->isConstexpr()) { 7035 7036 // Require constness. 7037 } else if (!DclT.isConstQualified()) { 7038 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 7039 << Init->getSourceRange(); 7040 VDecl->setInvalidDecl(); 7041 7042 // We allow integer constant expressions in all cases. 7043 } else if (DclT->isIntegralOrEnumerationType()) { 7044 // Check whether the expression is a constant expression. 7045 SourceLocation Loc; 7046 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 7047 // In C++11, a non-constexpr const static data member with an 7048 // in-class initializer cannot be volatile. 7049 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 7050 else if (Init->isValueDependent()) 7051 ; // Nothing to check. 7052 else if (Init->isIntegerConstantExpr(Context, &Loc)) 7053 ; // Ok, it's an ICE! 7054 else if (Init->isEvaluatable(Context)) { 7055 // If we can constant fold the initializer through heroics, accept it, 7056 // but report this as a use of an extension for -pedantic. 7057 Diag(Loc, diag::ext_in_class_initializer_non_constant) 7058 << Init->getSourceRange(); 7059 } else { 7060 // Otherwise, this is some crazy unknown case. Report the issue at the 7061 // location provided by the isIntegerConstantExpr failed check. 7062 Diag(Loc, diag::err_in_class_initializer_non_constant) 7063 << Init->getSourceRange(); 7064 VDecl->setInvalidDecl(); 7065 } 7066 7067 // We allow foldable floating-point constants as an extension. 7068 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 7069 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 7070 << DclT << Init->getSourceRange(); 7071 if (getLangOpts().CPlusPlus11) 7072 Diag(VDecl->getLocation(), 7073 diag::note_in_class_initializer_float_type_constexpr) 7074 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7075 7076 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 7077 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 7078 << Init->getSourceRange(); 7079 VDecl->setInvalidDecl(); 7080 } 7081 7082 // Suggest adding 'constexpr' in C++11 for literal types. 7083 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) { 7084 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 7085 << DclT << Init->getSourceRange() 7086 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7087 VDecl->setConstexpr(true); 7088 7089 } else { 7090 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 7091 << DclT << Init->getSourceRange(); 7092 VDecl->setInvalidDecl(); 7093 } 7094 } else if (VDecl->isFileVarDecl()) { 7095 if (VDecl->getStorageClassAsWritten() == SC_Extern && 7096 (!getLangOpts().CPlusPlus || 7097 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 7098 Diag(VDecl->getLocation(), diag::warn_extern_init); 7099 7100 // C99 6.7.8p4. All file scoped initializers need to be constant. 7101 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 7102 CheckForConstantInitializer(Init, DclT); 7103 } 7104 7105 // We will represent direct-initialization similarly to copy-initialization: 7106 // int x(1); -as-> int x = 1; 7107 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 7108 // 7109 // Clients that want to distinguish between the two forms, can check for 7110 // direct initializer using VarDecl::getInitStyle(). 7111 // A major benefit is that clients that don't particularly care about which 7112 // exactly form was it (like the CodeGen) can handle both cases without 7113 // special case code. 7114 7115 // C++ 8.5p11: 7116 // The form of initialization (using parentheses or '=') is generally 7117 // insignificant, but does matter when the entity being initialized has a 7118 // class type. 7119 if (CXXDirectInit) { 7120 assert(DirectInit && "Call-style initializer must be direct init."); 7121 VDecl->setInitStyle(VarDecl::CallInit); 7122 } else if (DirectInit) { 7123 // This must be list-initialization. No other way is direct-initialization. 7124 VDecl->setInitStyle(VarDecl::ListInit); 7125 } 7126 7127 CheckCompleteVariableDeclaration(VDecl); 7128} 7129 7130/// ActOnInitializerError - Given that there was an error parsing an 7131/// initializer for the given declaration, try to return to some form 7132/// of sanity. 7133void Sema::ActOnInitializerError(Decl *D) { 7134 // Our main concern here is re-establishing invariants like "a 7135 // variable's type is either dependent or complete". 7136 if (!D || D->isInvalidDecl()) return; 7137 7138 VarDecl *VD = dyn_cast<VarDecl>(D); 7139 if (!VD) return; 7140 7141 // Auto types are meaningless if we can't make sense of the initializer. 7142 if (ParsingInitForAutoVars.count(D)) { 7143 D->setInvalidDecl(); 7144 return; 7145 } 7146 7147 QualType Ty = VD->getType(); 7148 if (Ty->isDependentType()) return; 7149 7150 // Require a complete type. 7151 if (RequireCompleteType(VD->getLocation(), 7152 Context.getBaseElementType(Ty), 7153 diag::err_typecheck_decl_incomplete_type)) { 7154 VD->setInvalidDecl(); 7155 return; 7156 } 7157 7158 // Require an abstract type. 7159 if (RequireNonAbstractType(VD->getLocation(), Ty, 7160 diag::err_abstract_type_in_decl, 7161 AbstractVariableType)) { 7162 VD->setInvalidDecl(); 7163 return; 7164 } 7165 7166 // Don't bother complaining about constructors or destructors, 7167 // though. 7168} 7169 7170void Sema::ActOnUninitializedDecl(Decl *RealDecl, 7171 bool TypeMayContainAuto) { 7172 // If there is no declaration, there was an error parsing it. Just ignore it. 7173 if (RealDecl == 0) 7174 return; 7175 7176 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 7177 QualType Type = Var->getType(); 7178 7179 // C++11 [dcl.spec.auto]p3 7180 if (TypeMayContainAuto && Type->getContainedAutoType()) { 7181 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 7182 << Var->getDeclName() << Type; 7183 Var->setInvalidDecl(); 7184 return; 7185 } 7186 7187 // C++11 [class.static.data]p3: A static data member can be declared with 7188 // the constexpr specifier; if so, its declaration shall specify 7189 // a brace-or-equal-initializer. 7190 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 7191 // the definition of a variable [...] or the declaration of a static data 7192 // member. 7193 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 7194 if (Var->isStaticDataMember()) 7195 Diag(Var->getLocation(), 7196 diag::err_constexpr_static_mem_var_requires_init) 7197 << Var->getDeclName(); 7198 else 7199 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 7200 Var->setInvalidDecl(); 7201 return; 7202 } 7203 7204 switch (Var->isThisDeclarationADefinition()) { 7205 case VarDecl::Definition: 7206 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 7207 break; 7208 7209 // We have an out-of-line definition of a static data member 7210 // that has an in-class initializer, so we type-check this like 7211 // a declaration. 7212 // 7213 // Fall through 7214 7215 case VarDecl::DeclarationOnly: 7216 // It's only a declaration. 7217 7218 // Block scope. C99 6.7p7: If an identifier for an object is 7219 // declared with no linkage (C99 6.2.2p6), the type for the 7220 // object shall be complete. 7221 if (!Type->isDependentType() && Var->isLocalVarDecl() && 7222 !Var->getLinkage() && !Var->isInvalidDecl() && 7223 RequireCompleteType(Var->getLocation(), Type, 7224 diag::err_typecheck_decl_incomplete_type)) 7225 Var->setInvalidDecl(); 7226 7227 // Make sure that the type is not abstract. 7228 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7229 RequireNonAbstractType(Var->getLocation(), Type, 7230 diag::err_abstract_type_in_decl, 7231 AbstractVariableType)) 7232 Var->setInvalidDecl(); 7233 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7234 Var->getStorageClass() == SC_PrivateExtern) { 7235 Diag(Var->getLocation(), diag::warn_private_extern); 7236 Diag(Var->getLocation(), diag::note_private_extern); 7237 } 7238 7239 return; 7240 7241 case VarDecl::TentativeDefinition: 7242 // File scope. C99 6.9.2p2: A declaration of an identifier for an 7243 // object that has file scope without an initializer, and without a 7244 // storage-class specifier or with the storage-class specifier "static", 7245 // constitutes a tentative definition. Note: A tentative definition with 7246 // external linkage is valid (C99 6.2.2p5). 7247 if (!Var->isInvalidDecl()) { 7248 if (const IncompleteArrayType *ArrayT 7249 = Context.getAsIncompleteArrayType(Type)) { 7250 if (RequireCompleteType(Var->getLocation(), 7251 ArrayT->getElementType(), 7252 diag::err_illegal_decl_array_incomplete_type)) 7253 Var->setInvalidDecl(); 7254 } else if (Var->getStorageClass() == SC_Static) { 7255 // C99 6.9.2p3: If the declaration of an identifier for an object is 7256 // a tentative definition and has internal linkage (C99 6.2.2p3), the 7257 // declared type shall not be an incomplete type. 7258 // NOTE: code such as the following 7259 // static struct s; 7260 // struct s { int a; }; 7261 // is accepted by gcc. Hence here we issue a warning instead of 7262 // an error and we do not invalidate the static declaration. 7263 // NOTE: to avoid multiple warnings, only check the first declaration. 7264 if (Var->getPreviousDecl() == 0) 7265 RequireCompleteType(Var->getLocation(), Type, 7266 diag::ext_typecheck_decl_incomplete_type); 7267 } 7268 } 7269 7270 // Record the tentative definition; we're done. 7271 if (!Var->isInvalidDecl()) 7272 TentativeDefinitions.push_back(Var); 7273 return; 7274 } 7275 7276 // Provide a specific diagnostic for uninitialized variable 7277 // definitions with incomplete array type. 7278 if (Type->isIncompleteArrayType()) { 7279 Diag(Var->getLocation(), 7280 diag::err_typecheck_incomplete_array_needs_initializer); 7281 Var->setInvalidDecl(); 7282 return; 7283 } 7284 7285 // Provide a specific diagnostic for uninitialized variable 7286 // definitions with reference type. 7287 if (Type->isReferenceType()) { 7288 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 7289 << Var->getDeclName() 7290 << SourceRange(Var->getLocation(), Var->getLocation()); 7291 Var->setInvalidDecl(); 7292 return; 7293 } 7294 7295 // Do not attempt to type-check the default initializer for a 7296 // variable with dependent type. 7297 if (Type->isDependentType()) 7298 return; 7299 7300 if (Var->isInvalidDecl()) 7301 return; 7302 7303 if (RequireCompleteType(Var->getLocation(), 7304 Context.getBaseElementType(Type), 7305 diag::err_typecheck_decl_incomplete_type)) { 7306 Var->setInvalidDecl(); 7307 return; 7308 } 7309 7310 // The variable can not have an abstract class type. 7311 if (RequireNonAbstractType(Var->getLocation(), Type, 7312 diag::err_abstract_type_in_decl, 7313 AbstractVariableType)) { 7314 Var->setInvalidDecl(); 7315 return; 7316 } 7317 7318 // Check for jumps past the implicit initializer. C++0x 7319 // clarifies that this applies to a "variable with automatic 7320 // storage duration", not a "local variable". 7321 // C++11 [stmt.dcl]p3 7322 // A program that jumps from a point where a variable with automatic 7323 // storage duration is not in scope to a point where it is in scope is 7324 // ill-formed unless the variable has scalar type, class type with a 7325 // trivial default constructor and a trivial destructor, a cv-qualified 7326 // version of one of these types, or an array of one of the preceding 7327 // types and is declared without an initializer. 7328 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 7329 if (const RecordType *Record 7330 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 7331 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 7332 // Mark the function for further checking even if the looser rules of 7333 // C++11 do not require such checks, so that we can diagnose 7334 // incompatibilities with C++98. 7335 if (!CXXRecord->isPOD()) 7336 getCurFunction()->setHasBranchProtectedScope(); 7337 } 7338 } 7339 7340 // C++03 [dcl.init]p9: 7341 // If no initializer is specified for an object, and the 7342 // object is of (possibly cv-qualified) non-POD class type (or 7343 // array thereof), the object shall be default-initialized; if 7344 // the object is of const-qualified type, the underlying class 7345 // type shall have a user-declared default 7346 // constructor. Otherwise, if no initializer is specified for 7347 // a non- static object, the object and its subobjects, if 7348 // any, have an indeterminate initial value); if the object 7349 // or any of its subobjects are of const-qualified type, the 7350 // program is ill-formed. 7351 // C++0x [dcl.init]p11: 7352 // If no initializer is specified for an object, the object is 7353 // default-initialized; [...]. 7354 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 7355 InitializationKind Kind 7356 = InitializationKind::CreateDefault(Var->getLocation()); 7357 7358 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 7359 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg()); 7360 if (Init.isInvalid()) 7361 Var->setInvalidDecl(); 7362 else if (Init.get()) { 7363 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 7364 // This is important for template substitution. 7365 Var->setInitStyle(VarDecl::CallInit); 7366 } 7367 7368 CheckCompleteVariableDeclaration(Var); 7369 } 7370} 7371 7372void Sema::ActOnCXXForRangeDecl(Decl *D) { 7373 VarDecl *VD = dyn_cast<VarDecl>(D); 7374 if (!VD) { 7375 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 7376 D->setInvalidDecl(); 7377 return; 7378 } 7379 7380 VD->setCXXForRangeDecl(true); 7381 7382 // for-range-declaration cannot be given a storage class specifier. 7383 int Error = -1; 7384 switch (VD->getStorageClassAsWritten()) { 7385 case SC_None: 7386 break; 7387 case SC_Extern: 7388 Error = 0; 7389 break; 7390 case SC_Static: 7391 Error = 1; 7392 break; 7393 case SC_PrivateExtern: 7394 Error = 2; 7395 break; 7396 case SC_Auto: 7397 Error = 3; 7398 break; 7399 case SC_Register: 7400 Error = 4; 7401 break; 7402 case SC_OpenCLWorkGroupLocal: 7403 llvm_unreachable("Unexpected storage class"); 7404 } 7405 if (VD->isConstexpr()) 7406 Error = 5; 7407 if (Error != -1) { 7408 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 7409 << VD->getDeclName() << Error; 7410 D->setInvalidDecl(); 7411 } 7412} 7413 7414void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 7415 if (var->isInvalidDecl()) return; 7416 7417 // In ARC, don't allow jumps past the implicit initialization of a 7418 // local retaining variable. 7419 if (getLangOpts().ObjCAutoRefCount && 7420 var->hasLocalStorage()) { 7421 switch (var->getType().getObjCLifetime()) { 7422 case Qualifiers::OCL_None: 7423 case Qualifiers::OCL_ExplicitNone: 7424 case Qualifiers::OCL_Autoreleasing: 7425 break; 7426 7427 case Qualifiers::OCL_Weak: 7428 case Qualifiers::OCL_Strong: 7429 getCurFunction()->setHasBranchProtectedScope(); 7430 break; 7431 } 7432 } 7433 7434 if (var->isThisDeclarationADefinition() && 7435 var->getLinkage() == ExternalLinkage && 7436 getDiagnostics().getDiagnosticLevel( 7437 diag::warn_missing_variable_declarations, 7438 var->getLocation())) { 7439 // Find a previous declaration that's not a definition. 7440 VarDecl *prev = var->getPreviousDecl(); 7441 while (prev && prev->isThisDeclarationADefinition()) 7442 prev = prev->getPreviousDecl(); 7443 7444 if (!prev) 7445 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 7446 } 7447 7448 // All the following checks are C++ only. 7449 if (!getLangOpts().CPlusPlus) return; 7450 7451 QualType type = var->getType(); 7452 if (type->isDependentType()) return; 7453 7454 // __block variables might require us to capture a copy-initializer. 7455 if (var->hasAttr<BlocksAttr>()) { 7456 // It's currently invalid to ever have a __block variable with an 7457 // array type; should we diagnose that here? 7458 7459 // Regardless, we don't want to ignore array nesting when 7460 // constructing this copy. 7461 if (type->isStructureOrClassType()) { 7462 SourceLocation poi = var->getLocation(); 7463 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 7464 ExprResult result = 7465 PerformCopyInitialization( 7466 InitializedEntity::InitializeBlock(poi, type, false), 7467 poi, Owned(varRef)); 7468 if (!result.isInvalid()) { 7469 result = MaybeCreateExprWithCleanups(result); 7470 Expr *init = result.takeAs<Expr>(); 7471 Context.setBlockVarCopyInits(var, init); 7472 } 7473 } 7474 } 7475 7476 Expr *Init = var->getInit(); 7477 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 7478 QualType baseType = Context.getBaseElementType(type); 7479 7480 if (!var->getDeclContext()->isDependentContext() && 7481 Init && !Init->isValueDependent()) { 7482 if (IsGlobal && !var->isConstexpr() && 7483 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 7484 var->getLocation()) 7485 != DiagnosticsEngine::Ignored && 7486 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 7487 Diag(var->getLocation(), diag::warn_global_constructor) 7488 << Init->getSourceRange(); 7489 7490 if (var->isConstexpr()) { 7491 SmallVector<PartialDiagnosticAt, 8> Notes; 7492 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 7493 SourceLocation DiagLoc = var->getLocation(); 7494 // If the note doesn't add any useful information other than a source 7495 // location, fold it into the primary diagnostic. 7496 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 7497 diag::note_invalid_subexpr_in_const_expr) { 7498 DiagLoc = Notes[0].first; 7499 Notes.clear(); 7500 } 7501 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 7502 << var << Init->getSourceRange(); 7503 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 7504 Diag(Notes[I].first, Notes[I].second); 7505 } 7506 } else if (var->isUsableInConstantExpressions(Context)) { 7507 // Check whether the initializer of a const variable of integral or 7508 // enumeration type is an ICE now, since we can't tell whether it was 7509 // initialized by a constant expression if we check later. 7510 var->checkInitIsICE(); 7511 } 7512 } 7513 7514 // Require the destructor. 7515 if (const RecordType *recordType = baseType->getAs<RecordType>()) 7516 FinalizeVarWithDestructor(var, recordType); 7517} 7518 7519/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 7520/// any semantic actions necessary after any initializer has been attached. 7521void 7522Sema::FinalizeDeclaration(Decl *ThisDecl) { 7523 // Note that we are no longer parsing the initializer for this declaration. 7524 ParsingInitForAutoVars.erase(ThisDecl); 7525 7526 const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 7527 if (!VD) 7528 return; 7529 7530 if (VD->isFileVarDecl()) 7531 MarkUnusedFileScopedDecl(VD); 7532 7533 // Now we have parsed the initializer and can update the table of magic 7534 // tag values. 7535 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 7536 !VD->getType()->isIntegralOrEnumerationType()) 7537 return; 7538 7539 for (specific_attr_iterator<TypeTagForDatatypeAttr> 7540 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 7541 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 7542 I != E; ++I) { 7543 const Expr *MagicValueExpr = VD->getInit(); 7544 if (!MagicValueExpr) { 7545 continue; 7546 } 7547 llvm::APSInt MagicValueInt; 7548 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 7549 Diag(I->getRange().getBegin(), 7550 diag::err_type_tag_for_datatype_not_ice) 7551 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7552 continue; 7553 } 7554 if (MagicValueInt.getActiveBits() > 64) { 7555 Diag(I->getRange().getBegin(), 7556 diag::err_type_tag_for_datatype_too_large) 7557 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7558 continue; 7559 } 7560 uint64_t MagicValue = MagicValueInt.getZExtValue(); 7561 RegisterTypeTagForDatatype(I->getArgumentKind(), 7562 MagicValue, 7563 I->getMatchingCType(), 7564 I->getLayoutCompatible(), 7565 I->getMustBeNull()); 7566 } 7567} 7568 7569Sema::DeclGroupPtrTy 7570Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 7571 Decl **Group, unsigned NumDecls) { 7572 SmallVector<Decl*, 8> Decls; 7573 7574 if (DS.isTypeSpecOwned()) 7575 Decls.push_back(DS.getRepAsDecl()); 7576 7577 for (unsigned i = 0; i != NumDecls; ++i) 7578 if (Decl *D = Group[i]) 7579 Decls.push_back(D); 7580 7581 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) 7582 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) 7583 getASTContext().addUnnamedTag(Tag); 7584 7585 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 7586 DS.getTypeSpecType() == DeclSpec::TST_auto); 7587} 7588 7589/// BuildDeclaratorGroup - convert a list of declarations into a declaration 7590/// group, performing any necessary semantic checking. 7591Sema::DeclGroupPtrTy 7592Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 7593 bool TypeMayContainAuto) { 7594 // C++0x [dcl.spec.auto]p7: 7595 // If the type deduced for the template parameter U is not the same in each 7596 // deduction, the program is ill-formed. 7597 // FIXME: When initializer-list support is added, a distinction is needed 7598 // between the deduced type U and the deduced type which 'auto' stands for. 7599 // auto a = 0, b = { 1, 2, 3 }; 7600 // is legal because the deduced type U is 'int' in both cases. 7601 if (TypeMayContainAuto && NumDecls > 1) { 7602 QualType Deduced; 7603 CanQualType DeducedCanon; 7604 VarDecl *DeducedDecl = 0; 7605 for (unsigned i = 0; i != NumDecls; ++i) { 7606 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 7607 AutoType *AT = D->getType()->getContainedAutoType(); 7608 // Don't reissue diagnostics when instantiating a template. 7609 if (AT && D->isInvalidDecl()) 7610 break; 7611 if (AT && AT->isDeduced()) { 7612 QualType U = AT->getDeducedType(); 7613 CanQualType UCanon = Context.getCanonicalType(U); 7614 if (Deduced.isNull()) { 7615 Deduced = U; 7616 DeducedCanon = UCanon; 7617 DeducedDecl = D; 7618 } else if (DeducedCanon != UCanon) { 7619 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 7620 diag::err_auto_different_deductions) 7621 << Deduced << DeducedDecl->getDeclName() 7622 << U << D->getDeclName() 7623 << DeducedDecl->getInit()->getSourceRange() 7624 << D->getInit()->getSourceRange(); 7625 D->setInvalidDecl(); 7626 break; 7627 } 7628 } 7629 } 7630 } 7631 } 7632 7633 ActOnDocumentableDecls(Group, NumDecls); 7634 7635 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 7636} 7637 7638void Sema::ActOnDocumentableDecl(Decl *D) { 7639 ActOnDocumentableDecls(&D, 1); 7640} 7641 7642void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) { 7643 // Don't parse the comment if Doxygen diagnostics are ignored. 7644 if (NumDecls == 0 || !Group[0]) 7645 return; 7646 7647 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 7648 Group[0]->getLocation()) 7649 == DiagnosticsEngine::Ignored) 7650 return; 7651 7652 if (NumDecls >= 2) { 7653 // This is a decl group. Normally it will contain only declarations 7654 // procuded from declarator list. But in case we have any definitions or 7655 // additional declaration references: 7656 // 'typedef struct S {} S;' 7657 // 'typedef struct S *S;' 7658 // 'struct S *pS;' 7659 // FinalizeDeclaratorGroup adds these as separate declarations. 7660 Decl *MaybeTagDecl = Group[0]; 7661 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 7662 Group++; 7663 NumDecls--; 7664 } 7665 } 7666 7667 // See if there are any new comments that are not attached to a decl. 7668 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 7669 if (!Comments.empty() && 7670 !Comments.back()->isAttached()) { 7671 // There is at least one comment that not attached to a decl. 7672 // Maybe it should be attached to one of these decls? 7673 // 7674 // Note that this way we pick up not only comments that precede the 7675 // declaration, but also comments that *follow* the declaration -- thanks to 7676 // the lookahead in the lexer: we've consumed the semicolon and looked 7677 // ahead through comments. 7678 for (unsigned i = 0; i != NumDecls; ++i) 7679 Context.getCommentForDecl(Group[i], &PP); 7680 } 7681} 7682 7683/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 7684/// to introduce parameters into function prototype scope. 7685Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 7686 const DeclSpec &DS = D.getDeclSpec(); 7687 7688 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 7689 // C++03 [dcl.stc]p2 also permits 'auto'. 7690 VarDecl::StorageClass StorageClass = SC_None; 7691 VarDecl::StorageClass StorageClassAsWritten = SC_None; 7692 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 7693 StorageClass = SC_Register; 7694 StorageClassAsWritten = SC_Register; 7695 } else if (getLangOpts().CPlusPlus && 7696 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 7697 StorageClass = SC_Auto; 7698 StorageClassAsWritten = SC_Auto; 7699 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 7700 Diag(DS.getStorageClassSpecLoc(), 7701 diag::err_invalid_storage_class_in_func_decl); 7702 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7703 } 7704 7705 if (D.getDeclSpec().isThreadSpecified()) 7706 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 7707 if (D.getDeclSpec().isConstexprSpecified()) 7708 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 7709 << 0; 7710 7711 DiagnoseFunctionSpecifiers(D); 7712 7713 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7714 QualType parmDeclType = TInfo->getType(); 7715 7716 if (getLangOpts().CPlusPlus) { 7717 // Check that there are no default arguments inside the type of this 7718 // parameter. 7719 CheckExtraCXXDefaultArguments(D); 7720 7721 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 7722 if (D.getCXXScopeSpec().isSet()) { 7723 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 7724 << D.getCXXScopeSpec().getRange(); 7725 D.getCXXScopeSpec().clear(); 7726 } 7727 } 7728 7729 // Ensure we have a valid name 7730 IdentifierInfo *II = 0; 7731 if (D.hasName()) { 7732 II = D.getIdentifier(); 7733 if (!II) { 7734 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 7735 << GetNameForDeclarator(D).getName().getAsString(); 7736 D.setInvalidType(true); 7737 } 7738 } 7739 7740 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 7741 if (II) { 7742 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 7743 ForRedeclaration); 7744 LookupName(R, S); 7745 if (R.isSingleResult()) { 7746 NamedDecl *PrevDecl = R.getFoundDecl(); 7747 if (PrevDecl->isTemplateParameter()) { 7748 // Maybe we will complain about the shadowed template parameter. 7749 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 7750 // Just pretend that we didn't see the previous declaration. 7751 PrevDecl = 0; 7752 } else if (S->isDeclScope(PrevDecl)) { 7753 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 7754 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 7755 7756 // Recover by removing the name 7757 II = 0; 7758 D.SetIdentifier(0, D.getIdentifierLoc()); 7759 D.setInvalidType(true); 7760 } 7761 } 7762 } 7763 7764 // Temporarily put parameter variables in the translation unit, not 7765 // the enclosing context. This prevents them from accidentally 7766 // looking like class members in C++. 7767 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 7768 D.getLocStart(), 7769 D.getIdentifierLoc(), II, 7770 parmDeclType, TInfo, 7771 StorageClass, StorageClassAsWritten); 7772 7773 if (D.isInvalidType()) 7774 New->setInvalidDecl(); 7775 7776 assert(S->isFunctionPrototypeScope()); 7777 assert(S->getFunctionPrototypeDepth() >= 1); 7778 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 7779 S->getNextFunctionPrototypeIndex()); 7780 7781 // Add the parameter declaration into this scope. 7782 S->AddDecl(New); 7783 if (II) 7784 IdResolver.AddDecl(New); 7785 7786 ProcessDeclAttributes(S, New, D); 7787 7788 if (D.getDeclSpec().isModulePrivateSpecified()) 7789 Diag(New->getLocation(), diag::err_module_private_local) 7790 << 1 << New->getDeclName() 7791 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7792 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7793 7794 if (New->hasAttr<BlocksAttr>()) { 7795 Diag(New->getLocation(), diag::err_block_on_nonlocal); 7796 } 7797 return New; 7798} 7799 7800/// \brief Synthesizes a variable for a parameter arising from a 7801/// typedef. 7802ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 7803 SourceLocation Loc, 7804 QualType T) { 7805 /* FIXME: setting StartLoc == Loc. 7806 Would it be worth to modify callers so as to provide proper source 7807 location for the unnamed parameters, embedding the parameter's type? */ 7808 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 7809 T, Context.getTrivialTypeSourceInfo(T, Loc), 7810 SC_None, SC_None, 0); 7811 Param->setImplicit(); 7812 return Param; 7813} 7814 7815void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 7816 ParmVarDecl * const *ParamEnd) { 7817 // Don't diagnose unused-parameter errors in template instantiations; we 7818 // will already have done so in the template itself. 7819 if (!ActiveTemplateInstantiations.empty()) 7820 return; 7821 7822 for (; Param != ParamEnd; ++Param) { 7823 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 7824 !(*Param)->hasAttr<UnusedAttr>()) { 7825 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 7826 << (*Param)->getDeclName(); 7827 } 7828 } 7829} 7830 7831void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 7832 ParmVarDecl * const *ParamEnd, 7833 QualType ReturnTy, 7834 NamedDecl *D) { 7835 if (LangOpts.NumLargeByValueCopy == 0) // No check. 7836 return; 7837 7838 // Warn if the return value is pass-by-value and larger than the specified 7839 // threshold. 7840 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 7841 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 7842 if (Size > LangOpts.NumLargeByValueCopy) 7843 Diag(D->getLocation(), diag::warn_return_value_size) 7844 << D->getDeclName() << Size; 7845 } 7846 7847 // Warn if any parameter is pass-by-value and larger than the specified 7848 // threshold. 7849 for (; Param != ParamEnd; ++Param) { 7850 QualType T = (*Param)->getType(); 7851 if (T->isDependentType() || !T.isPODType(Context)) 7852 continue; 7853 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 7854 if (Size > LangOpts.NumLargeByValueCopy) 7855 Diag((*Param)->getLocation(), diag::warn_parameter_size) 7856 << (*Param)->getDeclName() << Size; 7857 } 7858} 7859 7860ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 7861 SourceLocation NameLoc, IdentifierInfo *Name, 7862 QualType T, TypeSourceInfo *TSInfo, 7863 VarDecl::StorageClass StorageClass, 7864 VarDecl::StorageClass StorageClassAsWritten) { 7865 // In ARC, infer a lifetime qualifier for appropriate parameter types. 7866 if (getLangOpts().ObjCAutoRefCount && 7867 T.getObjCLifetime() == Qualifiers::OCL_None && 7868 T->isObjCLifetimeType()) { 7869 7870 Qualifiers::ObjCLifetime lifetime; 7871 7872 // Special cases for arrays: 7873 // - if it's const, use __unsafe_unretained 7874 // - otherwise, it's an error 7875 if (T->isArrayType()) { 7876 if (!T.isConstQualified()) { 7877 DelayedDiagnostics.add( 7878 sema::DelayedDiagnostic::makeForbiddenType( 7879 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 7880 } 7881 lifetime = Qualifiers::OCL_ExplicitNone; 7882 } else { 7883 lifetime = T->getObjCARCImplicitLifetime(); 7884 } 7885 T = Context.getLifetimeQualifiedType(T, lifetime); 7886 } 7887 7888 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 7889 Context.getAdjustedParameterType(T), 7890 TSInfo, 7891 StorageClass, StorageClassAsWritten, 7892 0); 7893 7894 // Parameters can not be abstract class types. 7895 // For record types, this is done by the AbstractClassUsageDiagnoser once 7896 // the class has been completely parsed. 7897 if (!CurContext->isRecord() && 7898 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 7899 AbstractParamType)) 7900 New->setInvalidDecl(); 7901 7902 // Parameter declarators cannot be interface types. All ObjC objects are 7903 // passed by reference. 7904 if (T->isObjCObjectType()) { 7905 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 7906 Diag(NameLoc, 7907 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 7908 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 7909 T = Context.getObjCObjectPointerType(T); 7910 New->setType(T); 7911 } 7912 7913 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 7914 // duration shall not be qualified by an address-space qualifier." 7915 // Since all parameters have automatic store duration, they can not have 7916 // an address space. 7917 if (T.getAddressSpace() != 0) { 7918 Diag(NameLoc, diag::err_arg_with_address_space); 7919 New->setInvalidDecl(); 7920 } 7921 7922 return New; 7923} 7924 7925void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 7926 SourceLocation LocAfterDecls) { 7927 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7928 7929 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 7930 // for a K&R function. 7931 if (!FTI.hasPrototype) { 7932 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 7933 --i; 7934 if (FTI.ArgInfo[i].Param == 0) { 7935 SmallString<256> Code; 7936 llvm::raw_svector_ostream(Code) << " int " 7937 << FTI.ArgInfo[i].Ident->getName() 7938 << ";\n"; 7939 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 7940 << FTI.ArgInfo[i].Ident 7941 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 7942 7943 // Implicitly declare the argument as type 'int' for lack of a better 7944 // type. 7945 AttributeFactory attrs; 7946 DeclSpec DS(attrs); 7947 const char* PrevSpec; // unused 7948 unsigned DiagID; // unused 7949 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 7950 PrevSpec, DiagID); 7951 // Use the identifier location for the type source range. 7952 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 7953 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 7954 Declarator ParamD(DS, Declarator::KNRTypeListContext); 7955 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 7956 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 7957 } 7958 } 7959 } 7960} 7961 7962Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 7963 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 7964 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 7965 Scope *ParentScope = FnBodyScope->getParent(); 7966 7967 D.setFunctionDefinitionKind(FDK_Definition); 7968 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 7969 return ActOnStartOfFunctionDef(FnBodyScope, DP); 7970} 7971 7972static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 7973 const FunctionDecl*& PossibleZeroParamPrototype) { 7974 // Don't warn about invalid declarations. 7975 if (FD->isInvalidDecl()) 7976 return false; 7977 7978 // Or declarations that aren't global. 7979 if (!FD->isGlobal()) 7980 return false; 7981 7982 // Don't warn about C++ member functions. 7983 if (isa<CXXMethodDecl>(FD)) 7984 return false; 7985 7986 // Don't warn about 'main'. 7987 if (FD->isMain()) 7988 return false; 7989 7990 // Don't warn about inline functions. 7991 if (FD->isInlined()) 7992 return false; 7993 7994 // Don't warn about function templates. 7995 if (FD->getDescribedFunctionTemplate()) 7996 return false; 7997 7998 // Don't warn about function template specializations. 7999 if (FD->isFunctionTemplateSpecialization()) 8000 return false; 8001 8002 // Don't warn for OpenCL kernels. 8003 if (FD->hasAttr<OpenCLKernelAttr>()) 8004 return false; 8005 8006 bool MissingPrototype = true; 8007 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 8008 Prev; Prev = Prev->getPreviousDecl()) { 8009 // Ignore any declarations that occur in function or method 8010 // scope, because they aren't visible from the header. 8011 if (Prev->getDeclContext()->isFunctionOrMethod()) 8012 continue; 8013 8014 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 8015 if (FD->getNumParams() == 0) 8016 PossibleZeroParamPrototype = Prev; 8017 break; 8018 } 8019 8020 return MissingPrototype; 8021} 8022 8023void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 8024 // Don't complain if we're in GNU89 mode and the previous definition 8025 // was an extern inline function. 8026 const FunctionDecl *Definition; 8027 if (FD->isDefined(Definition) && 8028 !canRedefineFunction(Definition, getLangOpts())) { 8029 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 8030 Definition->getStorageClass() == SC_Extern) 8031 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 8032 << FD->getDeclName() << getLangOpts().CPlusPlus; 8033 else 8034 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 8035 Diag(Definition->getLocation(), diag::note_previous_definition); 8036 FD->setInvalidDecl(); 8037 } 8038} 8039 8040Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 8041 // Clear the last template instantiation error context. 8042 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 8043 8044 if (!D) 8045 return D; 8046 FunctionDecl *FD = 0; 8047 8048 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 8049 FD = FunTmpl->getTemplatedDecl(); 8050 else 8051 FD = cast<FunctionDecl>(D); 8052 8053 // Enter a new function scope 8054 PushFunctionScope(); 8055 8056 // See if this is a redefinition. 8057 if (!FD->isLateTemplateParsed()) 8058 CheckForFunctionRedefinition(FD); 8059 8060 // Builtin functions cannot be defined. 8061 if (unsigned BuiltinID = FD->getBuiltinID()) { 8062 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 8063 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 8064 FD->setInvalidDecl(); 8065 } 8066 } 8067 8068 // The return type of a function definition must be complete 8069 // (C99 6.9.1p3, C++ [dcl.fct]p6). 8070 QualType ResultType = FD->getResultType(); 8071 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 8072 !FD->isInvalidDecl() && 8073 RequireCompleteType(FD->getLocation(), ResultType, 8074 diag::err_func_def_incomplete_result)) 8075 FD->setInvalidDecl(); 8076 8077 // GNU warning -Wmissing-prototypes: 8078 // Warn if a global function is defined without a previous 8079 // prototype declaration. This warning is issued even if the 8080 // definition itself provides a prototype. The aim is to detect 8081 // global functions that fail to be declared in header files. 8082 const FunctionDecl *PossibleZeroParamPrototype = 0; 8083 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 8084 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 8085 8086 if (PossibleZeroParamPrototype) { 8087 // We found a declaration that is not a prototype, 8088 // but that could be a zero-parameter prototype 8089 TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo(); 8090 TypeLoc TL = TI->getTypeLoc(); 8091 if (FunctionNoProtoTypeLoc* FTL = dyn_cast<FunctionNoProtoTypeLoc>(&TL)) 8092 Diag(PossibleZeroParamPrototype->getLocation(), 8093 diag::note_declaration_not_a_prototype) 8094 << PossibleZeroParamPrototype 8095 << FixItHint::CreateInsertion(FTL->getRParenLoc(), "void"); 8096 } 8097 } 8098 8099 if (FnBodyScope) 8100 PushDeclContext(FnBodyScope, FD); 8101 8102 // Check the validity of our function parameters 8103 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 8104 /*CheckParameterNames=*/true); 8105 8106 // Introduce our parameters into the function scope 8107 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 8108 ParmVarDecl *Param = FD->getParamDecl(p); 8109 Param->setOwningFunction(FD); 8110 8111 // If this has an identifier, add it to the scope stack. 8112 if (Param->getIdentifier() && FnBodyScope) { 8113 CheckShadow(FnBodyScope, Param); 8114 8115 PushOnScopeChains(Param, FnBodyScope); 8116 } 8117 } 8118 8119 // If we had any tags defined in the function prototype, 8120 // introduce them into the function scope. 8121 if (FnBodyScope) { 8122 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 8123 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 8124 NamedDecl *D = *I; 8125 8126 // Some of these decls (like enums) may have been pinned to the translation unit 8127 // for lack of a real context earlier. If so, remove from the translation unit 8128 // and reattach to the current context. 8129 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 8130 // Is the decl actually in the context? 8131 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 8132 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 8133 if (*DI == D) { 8134 Context.getTranslationUnitDecl()->removeDecl(D); 8135 break; 8136 } 8137 } 8138 // Either way, reassign the lexical decl context to our FunctionDecl. 8139 D->setLexicalDeclContext(CurContext); 8140 } 8141 8142 // If the decl has a non-null name, make accessible in the current scope. 8143 if (!D->getName().empty()) 8144 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 8145 8146 // Similarly, dive into enums and fish their constants out, making them 8147 // accessible in this scope. 8148 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 8149 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 8150 EE = ED->enumerator_end(); EI != EE; ++EI) 8151 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 8152 } 8153 } 8154 } 8155 8156 // Ensure that the function's exception specification is instantiated. 8157 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 8158 ResolveExceptionSpec(D->getLocation(), FPT); 8159 8160 // Checking attributes of current function definition 8161 // dllimport attribute. 8162 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 8163 if (DA && (!FD->getAttr<DLLExportAttr>())) { 8164 // dllimport attribute cannot be directly applied to definition. 8165 // Microsoft accepts dllimport for functions defined within class scope. 8166 if (!DA->isInherited() && 8167 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 8168 Diag(FD->getLocation(), 8169 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 8170 << "dllimport"; 8171 FD->setInvalidDecl(); 8172 return D; 8173 } 8174 8175 // Visual C++ appears to not think this is an issue, so only issue 8176 // a warning when Microsoft extensions are disabled. 8177 if (!LangOpts.MicrosoftExt) { 8178 // If a symbol previously declared dllimport is later defined, the 8179 // attribute is ignored in subsequent references, and a warning is 8180 // emitted. 8181 Diag(FD->getLocation(), 8182 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 8183 << FD->getName() << "dllimport"; 8184 } 8185 } 8186 // We want to attach documentation to original Decl (which might be 8187 // a function template). 8188 ActOnDocumentableDecl(D); 8189 return D; 8190} 8191 8192/// \brief Given the set of return statements within a function body, 8193/// compute the variables that are subject to the named return value 8194/// optimization. 8195/// 8196/// Each of the variables that is subject to the named return value 8197/// optimization will be marked as NRVO variables in the AST, and any 8198/// return statement that has a marked NRVO variable as its NRVO candidate can 8199/// use the named return value optimization. 8200/// 8201/// This function applies a very simplistic algorithm for NRVO: if every return 8202/// statement in the function has the same NRVO candidate, that candidate is 8203/// the NRVO variable. 8204/// 8205/// FIXME: Employ a smarter algorithm that accounts for multiple return 8206/// statements and the lifetimes of the NRVO candidates. We should be able to 8207/// find a maximal set of NRVO variables. 8208void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 8209 ReturnStmt **Returns = Scope->Returns.data(); 8210 8211 const VarDecl *NRVOCandidate = 0; 8212 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 8213 if (!Returns[I]->getNRVOCandidate()) 8214 return; 8215 8216 if (!NRVOCandidate) 8217 NRVOCandidate = Returns[I]->getNRVOCandidate(); 8218 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 8219 return; 8220 } 8221 8222 if (NRVOCandidate) 8223 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 8224} 8225 8226bool Sema::canSkipFunctionBody(Decl *D) { 8227 if (!Consumer.shouldSkipFunctionBody(D)) 8228 return false; 8229 8230 if (isa<ObjCMethodDecl>(D)) 8231 return true; 8232 8233 FunctionDecl *FD = 0; 8234 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 8235 FD = FTD->getTemplatedDecl(); 8236 else 8237 FD = cast<FunctionDecl>(D); 8238 8239 // We cannot skip the body of a function (or function template) which is 8240 // constexpr, since we may need to evaluate its body in order to parse the 8241 // rest of the file. 8242 return !FD->isConstexpr(); 8243} 8244 8245Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 8246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl)) 8247 FD->setHasSkippedBody(); 8248 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 8249 MD->setHasSkippedBody(); 8250 return ActOnFinishFunctionBody(Decl, 0); 8251} 8252 8253Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 8254 return ActOnFinishFunctionBody(D, BodyArg, false); 8255} 8256 8257Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 8258 bool IsInstantiation) { 8259 FunctionDecl *FD = 0; 8260 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 8261 if (FunTmpl) 8262 FD = FunTmpl->getTemplatedDecl(); 8263 else 8264 FD = dyn_cast_or_null<FunctionDecl>(dcl); 8265 8266 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 8267 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 8268 8269 if (FD) { 8270 FD->setBody(Body); 8271 8272 // If the function implicitly returns zero (like 'main') or is naked, 8273 // don't complain about missing return statements. 8274 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 8275 WP.disableCheckFallThrough(); 8276 8277 // MSVC permits the use of pure specifier (=0) on function definition, 8278 // defined at class scope, warn about this non standard construct. 8279 if (getLangOpts().MicrosoftExt && FD->isPure()) 8280 Diag(FD->getLocation(), diag::warn_pure_function_definition); 8281 8282 if (!FD->isInvalidDecl()) { 8283 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 8284 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 8285 FD->getResultType(), FD); 8286 8287 // If this is a constructor, we need a vtable. 8288 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 8289 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 8290 8291 // Try to apply the named return value optimization. We have to check 8292 // if we can do this here because lambdas keep return statements around 8293 // to deduce an implicit return type. 8294 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 8295 !FD->isDependentContext()) 8296 computeNRVO(Body, getCurFunction()); 8297 } 8298 8299 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 8300 "Function parsing confused"); 8301 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 8302 assert(MD == getCurMethodDecl() && "Method parsing confused"); 8303 MD->setBody(Body); 8304 if (!MD->isInvalidDecl()) { 8305 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 8306 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 8307 MD->getResultType(), MD); 8308 8309 if (Body) 8310 computeNRVO(Body, getCurFunction()); 8311 } 8312 if (getCurFunction()->ObjCShouldCallSuper) { 8313 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 8314 << MD->getSelector().getAsString(); 8315 getCurFunction()->ObjCShouldCallSuper = false; 8316 } 8317 } else { 8318 return 0; 8319 } 8320 8321 assert(!getCurFunction()->ObjCShouldCallSuper && 8322 "This should only be set for ObjC methods, which should have been " 8323 "handled in the block above."); 8324 8325 // Verify and clean out per-function state. 8326 if (Body) { 8327 // C++ constructors that have function-try-blocks can't have return 8328 // statements in the handlers of that block. (C++ [except.handle]p14) 8329 // Verify this. 8330 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 8331 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 8332 8333 // Verify that gotos and switch cases don't jump into scopes illegally. 8334 if (getCurFunction()->NeedsScopeChecking() && 8335 !dcl->isInvalidDecl() && 8336 !hasAnyUnrecoverableErrorsInThisFunction() && 8337 !PP.isCodeCompletionEnabled()) 8338 DiagnoseInvalidJumps(Body); 8339 8340 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 8341 if (!Destructor->getParent()->isDependentType()) 8342 CheckDestructor(Destructor); 8343 8344 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8345 Destructor->getParent()); 8346 } 8347 8348 // If any errors have occurred, clear out any temporaries that may have 8349 // been leftover. This ensures that these temporaries won't be picked up for 8350 // deletion in some later function. 8351 if (PP.getDiagnostics().hasErrorOccurred() || 8352 PP.getDiagnostics().getSuppressAllDiagnostics()) { 8353 DiscardCleanupsInEvaluationContext(); 8354 } 8355 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 8356 !isa<FunctionTemplateDecl>(dcl)) { 8357 // Since the body is valid, issue any analysis-based warnings that are 8358 // enabled. 8359 ActivePolicy = &WP; 8360 } 8361 8362 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 8363 (!CheckConstexprFunctionDecl(FD) || 8364 !CheckConstexprFunctionBody(FD, Body))) 8365 FD->setInvalidDecl(); 8366 8367 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 8368 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 8369 assert(MaybeODRUseExprs.empty() && 8370 "Leftover expressions for odr-use checking"); 8371 } 8372 8373 if (!IsInstantiation) 8374 PopDeclContext(); 8375 8376 PopFunctionScopeInfo(ActivePolicy, dcl); 8377 8378 // If any errors have occurred, clear out any temporaries that may have 8379 // been leftover. This ensures that these temporaries won't be picked up for 8380 // deletion in some later function. 8381 if (getDiagnostics().hasErrorOccurred()) { 8382 DiscardCleanupsInEvaluationContext(); 8383 } 8384 8385 return dcl; 8386} 8387 8388 8389/// When we finish delayed parsing of an attribute, we must attach it to the 8390/// relevant Decl. 8391void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 8392 ParsedAttributes &Attrs) { 8393 // Always attach attributes to the underlying decl. 8394 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8395 D = TD->getTemplatedDecl(); 8396 ProcessDeclAttributeList(S, D, Attrs.getList()); 8397 8398 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 8399 if (Method->isStatic()) 8400 checkThisInStaticMemberFunctionAttributes(Method); 8401} 8402 8403 8404/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 8405/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 8406NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 8407 IdentifierInfo &II, Scope *S) { 8408 // Before we produce a declaration for an implicitly defined 8409 // function, see whether there was a locally-scoped declaration of 8410 // this name as a function or variable. If so, use that 8411 // (non-visible) declaration, and complain about it. 8412 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 8413 = findLocallyScopedExternCDecl(&II); 8414 if (Pos != LocallyScopedExternCDecls.end()) { 8415 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 8416 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 8417 return Pos->second; 8418 } 8419 8420 // Extension in C99. Legal in C90, but warn about it. 8421 unsigned diag_id; 8422 if (II.getName().startswith("__builtin_")) 8423 diag_id = diag::warn_builtin_unknown; 8424 else if (getLangOpts().C99) 8425 diag_id = diag::ext_implicit_function_decl; 8426 else 8427 diag_id = diag::warn_implicit_function_decl; 8428 Diag(Loc, diag_id) << &II; 8429 8430 // Because typo correction is expensive, only do it if the implicit 8431 // function declaration is going to be treated as an error. 8432 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 8433 TypoCorrection Corrected; 8434 DeclFilterCCC<FunctionDecl> Validator; 8435 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 8436 LookupOrdinaryName, S, 0, Validator))) { 8437 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 8438 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 8439 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 8440 8441 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 8442 << FixItHint::CreateReplacement(Loc, CorrectedStr); 8443 8444 if (Func->getLocation().isValid() 8445 && !II.getName().startswith("__builtin_")) 8446 Diag(Func->getLocation(), diag::note_previous_decl) 8447 << CorrectedQuotedStr; 8448 } 8449 } 8450 8451 // Set a Declarator for the implicit definition: int foo(); 8452 const char *Dummy; 8453 AttributeFactory attrFactory; 8454 DeclSpec DS(attrFactory); 8455 unsigned DiagID; 8456 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 8457 (void)Error; // Silence warning. 8458 assert(!Error && "Error setting up implicit decl!"); 8459 SourceLocation NoLoc; 8460 Declarator D(DS, Declarator::BlockContext); 8461 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 8462 /*IsAmbiguous=*/false, 8463 /*RParenLoc=*/NoLoc, 8464 /*ArgInfo=*/0, 8465 /*NumArgs=*/0, 8466 /*EllipsisLoc=*/NoLoc, 8467 /*RParenLoc=*/NoLoc, 8468 /*TypeQuals=*/0, 8469 /*RefQualifierIsLvalueRef=*/true, 8470 /*RefQualifierLoc=*/NoLoc, 8471 /*ConstQualifierLoc=*/NoLoc, 8472 /*VolatileQualifierLoc=*/NoLoc, 8473 /*MutableLoc=*/NoLoc, 8474 EST_None, 8475 /*ESpecLoc=*/NoLoc, 8476 /*Exceptions=*/0, 8477 /*ExceptionRanges=*/0, 8478 /*NumExceptions=*/0, 8479 /*NoexceptExpr=*/0, 8480 Loc, Loc, D), 8481 DS.getAttributes(), 8482 SourceLocation()); 8483 D.SetIdentifier(&II, Loc); 8484 8485 // Insert this function into translation-unit scope. 8486 8487 DeclContext *PrevDC = CurContext; 8488 CurContext = Context.getTranslationUnitDecl(); 8489 8490 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 8491 FD->setImplicit(); 8492 8493 CurContext = PrevDC; 8494 8495 AddKnownFunctionAttributes(FD); 8496 8497 return FD; 8498} 8499 8500/// \brief Adds any function attributes that we know a priori based on 8501/// the declaration of this function. 8502/// 8503/// These attributes can apply both to implicitly-declared builtins 8504/// (like __builtin___printf_chk) or to library-declared functions 8505/// like NSLog or printf. 8506/// 8507/// We need to check for duplicate attributes both here and where user-written 8508/// attributes are applied to declarations. 8509void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 8510 if (FD->isInvalidDecl()) 8511 return; 8512 8513 // If this is a built-in function, map its builtin attributes to 8514 // actual attributes. 8515 if (unsigned BuiltinID = FD->getBuiltinID()) { 8516 // Handle printf-formatting attributes. 8517 unsigned FormatIdx; 8518 bool HasVAListArg; 8519 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 8520 if (!FD->getAttr<FormatAttr>()) { 8521 const char *fmt = "printf"; 8522 unsigned int NumParams = FD->getNumParams(); 8523 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 8524 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 8525 fmt = "NSString"; 8526 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8527 fmt, FormatIdx+1, 8528 HasVAListArg ? 0 : FormatIdx+2)); 8529 } 8530 } 8531 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 8532 HasVAListArg)) { 8533 if (!FD->getAttr<FormatAttr>()) 8534 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8535 "scanf", FormatIdx+1, 8536 HasVAListArg ? 0 : FormatIdx+2)); 8537 } 8538 8539 // Mark const if we don't care about errno and that is the only 8540 // thing preventing the function from being const. This allows 8541 // IRgen to use LLVM intrinsics for such functions. 8542 if (!getLangOpts().MathErrno && 8543 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 8544 if (!FD->getAttr<ConstAttr>()) 8545 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8546 } 8547 8548 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 8549 !FD->getAttr<ReturnsTwiceAttr>()) 8550 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 8551 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 8552 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 8553 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 8554 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8555 } 8556 8557 IdentifierInfo *Name = FD->getIdentifier(); 8558 if (!Name) 8559 return; 8560 if ((!getLangOpts().CPlusPlus && 8561 FD->getDeclContext()->isTranslationUnit()) || 8562 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 8563 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 8564 LinkageSpecDecl::lang_c)) { 8565 // Okay: this could be a libc/libm/Objective-C function we know 8566 // about. 8567 } else 8568 return; 8569 8570 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 8571 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 8572 // target-specific builtins, perhaps? 8573 if (!FD->getAttr<FormatAttr>()) 8574 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8575 "printf", 2, 8576 Name->isStr("vasprintf") ? 0 : 3)); 8577 } 8578 8579 if (Name->isStr("__CFStringMakeConstantString")) { 8580 // We already have a __builtin___CFStringMakeConstantString, 8581 // but builds that use -fno-constant-cfstrings don't go through that. 8582 if (!FD->getAttr<FormatArgAttr>()) 8583 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 8584 } 8585} 8586 8587TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 8588 TypeSourceInfo *TInfo) { 8589 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 8590 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 8591 8592 if (!TInfo) { 8593 assert(D.isInvalidType() && "no declarator info for valid type"); 8594 TInfo = Context.getTrivialTypeSourceInfo(T); 8595 } 8596 8597 // Scope manipulation handled by caller. 8598 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 8599 D.getLocStart(), 8600 D.getIdentifierLoc(), 8601 D.getIdentifier(), 8602 TInfo); 8603 8604 // Bail out immediately if we have an invalid declaration. 8605 if (D.isInvalidType()) { 8606 NewTD->setInvalidDecl(); 8607 return NewTD; 8608 } 8609 8610 if (D.getDeclSpec().isModulePrivateSpecified()) { 8611 if (CurContext->isFunctionOrMethod()) 8612 Diag(NewTD->getLocation(), diag::err_module_private_local) 8613 << 2 << NewTD->getDeclName() 8614 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 8615 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 8616 else 8617 NewTD->setModulePrivate(); 8618 } 8619 8620 // C++ [dcl.typedef]p8: 8621 // If the typedef declaration defines an unnamed class (or 8622 // enum), the first typedef-name declared by the declaration 8623 // to be that class type (or enum type) is used to denote the 8624 // class type (or enum type) for linkage purposes only. 8625 // We need to check whether the type was declared in the declaration. 8626 switch (D.getDeclSpec().getTypeSpecType()) { 8627 case TST_enum: 8628 case TST_struct: 8629 case TST_interface: 8630 case TST_union: 8631 case TST_class: { 8632 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 8633 8634 // Do nothing if the tag is not anonymous or already has an 8635 // associated typedef (from an earlier typedef in this decl group). 8636 if (tagFromDeclSpec->getIdentifier()) break; 8637 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 8638 8639 // A well-formed anonymous tag must always be a TUK_Definition. 8640 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 8641 8642 // The type must match the tag exactly; no qualifiers allowed. 8643 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 8644 break; 8645 8646 // Otherwise, set this is the anon-decl typedef for the tag. 8647 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 8648 break; 8649 } 8650 8651 default: 8652 break; 8653 } 8654 8655 return NewTD; 8656} 8657 8658 8659/// \brief Check that this is a valid underlying type for an enum declaration. 8660bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 8661 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 8662 QualType T = TI->getType(); 8663 8664 if (T->isDependentType()) 8665 return false; 8666 8667 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 8668 if (BT->isInteger()) 8669 return false; 8670 8671 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 8672 return true; 8673} 8674 8675/// Check whether this is a valid redeclaration of a previous enumeration. 8676/// \return true if the redeclaration was invalid. 8677bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 8678 QualType EnumUnderlyingTy, 8679 const EnumDecl *Prev) { 8680 bool IsFixed = !EnumUnderlyingTy.isNull(); 8681 8682 if (IsScoped != Prev->isScoped()) { 8683 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 8684 << Prev->isScoped(); 8685 Diag(Prev->getLocation(), diag::note_previous_use); 8686 return true; 8687 } 8688 8689 if (IsFixed && Prev->isFixed()) { 8690 if (!EnumUnderlyingTy->isDependentType() && 8691 !Prev->getIntegerType()->isDependentType() && 8692 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 8693 Prev->getIntegerType())) { 8694 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 8695 << EnumUnderlyingTy << Prev->getIntegerType(); 8696 Diag(Prev->getLocation(), diag::note_previous_use); 8697 return true; 8698 } 8699 } else if (IsFixed != Prev->isFixed()) { 8700 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 8701 << Prev->isFixed(); 8702 Diag(Prev->getLocation(), diag::note_previous_use); 8703 return true; 8704 } 8705 8706 return false; 8707} 8708 8709/// \brief Get diagnostic %select index for tag kind for 8710/// redeclaration diagnostic message. 8711/// WARNING: Indexes apply to particular diagnostics only! 8712/// 8713/// \returns diagnostic %select index. 8714static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 8715 switch (Tag) { 8716 case TTK_Struct: return 0; 8717 case TTK_Interface: return 1; 8718 case TTK_Class: return 2; 8719 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 8720 } 8721} 8722 8723/// \brief Determine if tag kind is a class-key compatible with 8724/// class for redeclaration (class, struct, or __interface). 8725/// 8726/// \returns true iff the tag kind is compatible. 8727static bool isClassCompatTagKind(TagTypeKind Tag) 8728{ 8729 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 8730} 8731 8732/// \brief Determine whether a tag with a given kind is acceptable 8733/// as a redeclaration of the given tag declaration. 8734/// 8735/// \returns true if the new tag kind is acceptable, false otherwise. 8736bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 8737 TagTypeKind NewTag, bool isDefinition, 8738 SourceLocation NewTagLoc, 8739 const IdentifierInfo &Name) { 8740 // C++ [dcl.type.elab]p3: 8741 // The class-key or enum keyword present in the 8742 // elaborated-type-specifier shall agree in kind with the 8743 // declaration to which the name in the elaborated-type-specifier 8744 // refers. This rule also applies to the form of 8745 // elaborated-type-specifier that declares a class-name or 8746 // friend class since it can be construed as referring to the 8747 // definition of the class. Thus, in any 8748 // elaborated-type-specifier, the enum keyword shall be used to 8749 // refer to an enumeration (7.2), the union class-key shall be 8750 // used to refer to a union (clause 9), and either the class or 8751 // struct class-key shall be used to refer to a class (clause 9) 8752 // declared using the class or struct class-key. 8753 TagTypeKind OldTag = Previous->getTagKind(); 8754 if (!isDefinition || !isClassCompatTagKind(NewTag)) 8755 if (OldTag == NewTag) 8756 return true; 8757 8758 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 8759 // Warn about the struct/class tag mismatch. 8760 bool isTemplate = false; 8761 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 8762 isTemplate = Record->getDescribedClassTemplate(); 8763 8764 if (!ActiveTemplateInstantiations.empty()) { 8765 // In a template instantiation, do not offer fix-its for tag mismatches 8766 // since they usually mess up the template instead of fixing the problem. 8767 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 8768 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 8769 << getRedeclDiagFromTagKind(OldTag); 8770 return true; 8771 } 8772 8773 if (isDefinition) { 8774 // On definitions, check previous tags and issue a fix-it for each 8775 // one that doesn't match the current tag. 8776 if (Previous->getDefinition()) { 8777 // Don't suggest fix-its for redefinitions. 8778 return true; 8779 } 8780 8781 bool previousMismatch = false; 8782 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 8783 E(Previous->redecls_end()); I != E; ++I) { 8784 if (I->getTagKind() != NewTag) { 8785 if (!previousMismatch) { 8786 previousMismatch = true; 8787 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 8788 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 8789 << getRedeclDiagFromTagKind(I->getTagKind()); 8790 } 8791 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 8792 << getRedeclDiagFromTagKind(NewTag) 8793 << FixItHint::CreateReplacement(I->getInnerLocStart(), 8794 TypeWithKeyword::getTagTypeKindName(NewTag)); 8795 } 8796 } 8797 return true; 8798 } 8799 8800 // Check for a previous definition. If current tag and definition 8801 // are same type, do nothing. If no definition, but disagree with 8802 // with previous tag type, give a warning, but no fix-it. 8803 const TagDecl *Redecl = Previous->getDefinition() ? 8804 Previous->getDefinition() : Previous; 8805 if (Redecl->getTagKind() == NewTag) { 8806 return true; 8807 } 8808 8809 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 8810 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 8811 << getRedeclDiagFromTagKind(OldTag); 8812 Diag(Redecl->getLocation(), diag::note_previous_use); 8813 8814 // If there is a previous defintion, suggest a fix-it. 8815 if (Previous->getDefinition()) { 8816 Diag(NewTagLoc, diag::note_struct_class_suggestion) 8817 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 8818 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 8819 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 8820 } 8821 8822 return true; 8823 } 8824 return false; 8825} 8826 8827/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 8828/// former case, Name will be non-null. In the later case, Name will be null. 8829/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 8830/// reference/declaration/definition of a tag. 8831Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 8832 SourceLocation KWLoc, CXXScopeSpec &SS, 8833 IdentifierInfo *Name, SourceLocation NameLoc, 8834 AttributeList *Attr, AccessSpecifier AS, 8835 SourceLocation ModulePrivateLoc, 8836 MultiTemplateParamsArg TemplateParameterLists, 8837 bool &OwnedDecl, bool &IsDependent, 8838 SourceLocation ScopedEnumKWLoc, 8839 bool ScopedEnumUsesClassTag, 8840 TypeResult UnderlyingType) { 8841 // If this is not a definition, it must have a name. 8842 IdentifierInfo *OrigName = Name; 8843 assert((Name != 0 || TUK == TUK_Definition) && 8844 "Nameless record must be a definition!"); 8845 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 8846 8847 OwnedDecl = false; 8848 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8849 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 8850 8851 // FIXME: Check explicit specializations more carefully. 8852 bool isExplicitSpecialization = false; 8853 bool Invalid = false; 8854 8855 // We only need to do this matching if we have template parameters 8856 // or a scope specifier, which also conveniently avoids this work 8857 // for non-C++ cases. 8858 if (TemplateParameterLists.size() > 0 || 8859 (SS.isNotEmpty() && TUK != TUK_Reference)) { 8860 if (TemplateParameterList *TemplateParams 8861 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 8862 TemplateParameterLists.data(), 8863 TemplateParameterLists.size(), 8864 TUK == TUK_Friend, 8865 isExplicitSpecialization, 8866 Invalid)) { 8867 if (TemplateParams->size() > 0) { 8868 // This is a declaration or definition of a class template (which may 8869 // be a member of another template). 8870 8871 if (Invalid) 8872 return 0; 8873 8874 OwnedDecl = false; 8875 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 8876 SS, Name, NameLoc, Attr, 8877 TemplateParams, AS, 8878 ModulePrivateLoc, 8879 TemplateParameterLists.size()-1, 8880 TemplateParameterLists.data()); 8881 return Result.get(); 8882 } else { 8883 // The "template<>" header is extraneous. 8884 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 8885 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 8886 isExplicitSpecialization = true; 8887 } 8888 } 8889 } 8890 8891 // Figure out the underlying type if this a enum declaration. We need to do 8892 // this early, because it's needed to detect if this is an incompatible 8893 // redeclaration. 8894 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 8895 8896 if (Kind == TTK_Enum) { 8897 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 8898 // No underlying type explicitly specified, or we failed to parse the 8899 // type, default to int. 8900 EnumUnderlying = Context.IntTy.getTypePtr(); 8901 else if (UnderlyingType.get()) { 8902 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 8903 // integral type; any cv-qualification is ignored. 8904 TypeSourceInfo *TI = 0; 8905 GetTypeFromParser(UnderlyingType.get(), &TI); 8906 EnumUnderlying = TI; 8907 8908 if (CheckEnumUnderlyingType(TI)) 8909 // Recover by falling back to int. 8910 EnumUnderlying = Context.IntTy.getTypePtr(); 8911 8912 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 8913 UPPC_FixedUnderlyingType)) 8914 EnumUnderlying = Context.IntTy.getTypePtr(); 8915 8916 } else if (getLangOpts().MicrosoftMode) 8917 // Microsoft enums are always of int type. 8918 EnumUnderlying = Context.IntTy.getTypePtr(); 8919 } 8920 8921 DeclContext *SearchDC = CurContext; 8922 DeclContext *DC = CurContext; 8923 bool isStdBadAlloc = false; 8924 8925 RedeclarationKind Redecl = ForRedeclaration; 8926 if (TUK == TUK_Friend || TUK == TUK_Reference) 8927 Redecl = NotForRedeclaration; 8928 8929 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 8930 8931 if (Name && SS.isNotEmpty()) { 8932 // We have a nested-name tag ('struct foo::bar'). 8933 8934 // Check for invalid 'foo::'. 8935 if (SS.isInvalid()) { 8936 Name = 0; 8937 goto CreateNewDecl; 8938 } 8939 8940 // If this is a friend or a reference to a class in a dependent 8941 // context, don't try to make a decl for it. 8942 if (TUK == TUK_Friend || TUK == TUK_Reference) { 8943 DC = computeDeclContext(SS, false); 8944 if (!DC) { 8945 IsDependent = true; 8946 return 0; 8947 } 8948 } else { 8949 DC = computeDeclContext(SS, true); 8950 if (!DC) { 8951 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 8952 << SS.getRange(); 8953 return 0; 8954 } 8955 } 8956 8957 if (RequireCompleteDeclContext(SS, DC)) 8958 return 0; 8959 8960 SearchDC = DC; 8961 // Look-up name inside 'foo::'. 8962 LookupQualifiedName(Previous, DC); 8963 8964 if (Previous.isAmbiguous()) 8965 return 0; 8966 8967 if (Previous.empty()) { 8968 // Name lookup did not find anything. However, if the 8969 // nested-name-specifier refers to the current instantiation, 8970 // and that current instantiation has any dependent base 8971 // classes, we might find something at instantiation time: treat 8972 // this as a dependent elaborated-type-specifier. 8973 // But this only makes any sense for reference-like lookups. 8974 if (Previous.wasNotFoundInCurrentInstantiation() && 8975 (TUK == TUK_Reference || TUK == TUK_Friend)) { 8976 IsDependent = true; 8977 return 0; 8978 } 8979 8980 // A tag 'foo::bar' must already exist. 8981 Diag(NameLoc, diag::err_not_tag_in_scope) 8982 << Kind << Name << DC << SS.getRange(); 8983 Name = 0; 8984 Invalid = true; 8985 goto CreateNewDecl; 8986 } 8987 } else if (Name) { 8988 // If this is a named struct, check to see if there was a previous forward 8989 // declaration or definition. 8990 // FIXME: We're looking into outer scopes here, even when we 8991 // shouldn't be. Doing so can result in ambiguities that we 8992 // shouldn't be diagnosing. 8993 LookupName(Previous, S); 8994 8995 if (Previous.isAmbiguous() && 8996 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 8997 LookupResult::Filter F = Previous.makeFilter(); 8998 while (F.hasNext()) { 8999 NamedDecl *ND = F.next(); 9000 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 9001 F.erase(); 9002 } 9003 F.done(); 9004 } 9005 9006 // Note: there used to be some attempt at recovery here. 9007 if (Previous.isAmbiguous()) 9008 return 0; 9009 9010 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 9011 // FIXME: This makes sure that we ignore the contexts associated 9012 // with C structs, unions, and enums when looking for a matching 9013 // tag declaration or definition. See the similar lookup tweak 9014 // in Sema::LookupName; is there a better way to deal with this? 9015 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 9016 SearchDC = SearchDC->getParent(); 9017 } 9018 } else if (S->isFunctionPrototypeScope()) { 9019 // If this is an enum declaration in function prototype scope, set its 9020 // initial context to the translation unit. 9021 // FIXME: [citation needed] 9022 SearchDC = Context.getTranslationUnitDecl(); 9023 } 9024 9025 if (Previous.isSingleResult() && 9026 Previous.getFoundDecl()->isTemplateParameter()) { 9027 // Maybe we will complain about the shadowed template parameter. 9028 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 9029 // Just pretend that we didn't see the previous declaration. 9030 Previous.clear(); 9031 } 9032 9033 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 9034 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 9035 // This is a declaration of or a reference to "std::bad_alloc". 9036 isStdBadAlloc = true; 9037 9038 if (Previous.empty() && StdBadAlloc) { 9039 // std::bad_alloc has been implicitly declared (but made invisible to 9040 // name lookup). Fill in this implicit declaration as the previous 9041 // declaration, so that the declarations get chained appropriately. 9042 Previous.addDecl(getStdBadAlloc()); 9043 } 9044 } 9045 9046 // If we didn't find a previous declaration, and this is a reference 9047 // (or friend reference), move to the correct scope. In C++, we 9048 // also need to do a redeclaration lookup there, just in case 9049 // there's a shadow friend decl. 9050 if (Name && Previous.empty() && 9051 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9052 if (Invalid) goto CreateNewDecl; 9053 assert(SS.isEmpty()); 9054 9055 if (TUK == TUK_Reference) { 9056 // C++ [basic.scope.pdecl]p5: 9057 // -- for an elaborated-type-specifier of the form 9058 // 9059 // class-key identifier 9060 // 9061 // if the elaborated-type-specifier is used in the 9062 // decl-specifier-seq or parameter-declaration-clause of a 9063 // function defined in namespace scope, the identifier is 9064 // declared as a class-name in the namespace that contains 9065 // the declaration; otherwise, except as a friend 9066 // declaration, the identifier is declared in the smallest 9067 // non-class, non-function-prototype scope that contains the 9068 // declaration. 9069 // 9070 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 9071 // C structs and unions. 9072 // 9073 // It is an error in C++ to declare (rather than define) an enum 9074 // type, including via an elaborated type specifier. We'll 9075 // diagnose that later; for now, declare the enum in the same 9076 // scope as we would have picked for any other tag type. 9077 // 9078 // GNU C also supports this behavior as part of its incomplete 9079 // enum types extension, while GNU C++ does not. 9080 // 9081 // Find the context where we'll be declaring the tag. 9082 // FIXME: We would like to maintain the current DeclContext as the 9083 // lexical context, 9084 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 9085 SearchDC = SearchDC->getParent(); 9086 9087 // Find the scope where we'll be declaring the tag. 9088 while (S->isClassScope() || 9089 (getLangOpts().CPlusPlus && 9090 S->isFunctionPrototypeScope()) || 9091 ((S->getFlags() & Scope::DeclScope) == 0) || 9092 (S->getEntity() && 9093 ((DeclContext *)S->getEntity())->isTransparentContext())) 9094 S = S->getParent(); 9095 } else { 9096 assert(TUK == TUK_Friend); 9097 // C++ [namespace.memdef]p3: 9098 // If a friend declaration in a non-local class first declares a 9099 // class or function, the friend class or function is a member of 9100 // the innermost enclosing namespace. 9101 SearchDC = SearchDC->getEnclosingNamespaceContext(); 9102 } 9103 9104 // In C++, we need to do a redeclaration lookup to properly 9105 // diagnose some problems. 9106 if (getLangOpts().CPlusPlus) { 9107 Previous.setRedeclarationKind(ForRedeclaration); 9108 LookupQualifiedName(Previous, SearchDC); 9109 } 9110 } 9111 9112 if (!Previous.empty()) { 9113 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 9114 9115 // It's okay to have a tag decl in the same scope as a typedef 9116 // which hides a tag decl in the same scope. Finding this 9117 // insanity with a redeclaration lookup can only actually happen 9118 // in C++. 9119 // 9120 // This is also okay for elaborated-type-specifiers, which is 9121 // technically forbidden by the current standard but which is 9122 // okay according to the likely resolution of an open issue; 9123 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 9124 if (getLangOpts().CPlusPlus) { 9125 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9126 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 9127 TagDecl *Tag = TT->getDecl(); 9128 if (Tag->getDeclName() == Name && 9129 Tag->getDeclContext()->getRedeclContext() 9130 ->Equals(TD->getDeclContext()->getRedeclContext())) { 9131 PrevDecl = Tag; 9132 Previous.clear(); 9133 Previous.addDecl(Tag); 9134 Previous.resolveKind(); 9135 } 9136 } 9137 } 9138 } 9139 9140 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 9141 // If this is a use of a previous tag, or if the tag is already declared 9142 // in the same scope (so that the definition/declaration completes or 9143 // rementions the tag), reuse the decl. 9144 if (TUK == TUK_Reference || TUK == TUK_Friend || 9145 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 9146 // Make sure that this wasn't declared as an enum and now used as a 9147 // struct or something similar. 9148 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 9149 TUK == TUK_Definition, KWLoc, 9150 *Name)) { 9151 bool SafeToContinue 9152 = (PrevTagDecl->getTagKind() != TTK_Enum && 9153 Kind != TTK_Enum); 9154 if (SafeToContinue) 9155 Diag(KWLoc, diag::err_use_with_wrong_tag) 9156 << Name 9157 << FixItHint::CreateReplacement(SourceRange(KWLoc), 9158 PrevTagDecl->getKindName()); 9159 else 9160 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 9161 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 9162 9163 if (SafeToContinue) 9164 Kind = PrevTagDecl->getTagKind(); 9165 else { 9166 // Recover by making this an anonymous redefinition. 9167 Name = 0; 9168 Previous.clear(); 9169 Invalid = true; 9170 } 9171 } 9172 9173 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 9174 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 9175 9176 // If this is an elaborated-type-specifier for a scoped enumeration, 9177 // the 'class' keyword is not necessary and not permitted. 9178 if (TUK == TUK_Reference || TUK == TUK_Friend) { 9179 if (ScopedEnum) 9180 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 9181 << PrevEnum->isScoped() 9182 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 9183 return PrevTagDecl; 9184 } 9185 9186 QualType EnumUnderlyingTy; 9187 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9188 EnumUnderlyingTy = TI->getType(); 9189 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 9190 EnumUnderlyingTy = QualType(T, 0); 9191 9192 // All conflicts with previous declarations are recovered by 9193 // returning the previous declaration, unless this is a definition, 9194 // in which case we want the caller to bail out. 9195 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 9196 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 9197 return TUK == TUK_Declaration ? PrevTagDecl : 0; 9198 } 9199 9200 if (!Invalid) { 9201 // If this is a use, just return the declaration we found. 9202 9203 // FIXME: In the future, return a variant or some other clue 9204 // for the consumer of this Decl to know it doesn't own it. 9205 // For our current ASTs this shouldn't be a problem, but will 9206 // need to be changed with DeclGroups. 9207 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 9208 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 9209 return PrevTagDecl; 9210 9211 // Diagnose attempts to redefine a tag. 9212 if (TUK == TUK_Definition) { 9213 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 9214 // If we're defining a specialization and the previous definition 9215 // is from an implicit instantiation, don't emit an error 9216 // here; we'll catch this in the general case below. 9217 bool IsExplicitSpecializationAfterInstantiation = false; 9218 if (isExplicitSpecialization) { 9219 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 9220 IsExplicitSpecializationAfterInstantiation = 9221 RD->getTemplateSpecializationKind() != 9222 TSK_ExplicitSpecialization; 9223 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 9224 IsExplicitSpecializationAfterInstantiation = 9225 ED->getTemplateSpecializationKind() != 9226 TSK_ExplicitSpecialization; 9227 } 9228 9229 if (!IsExplicitSpecializationAfterInstantiation) { 9230 // A redeclaration in function prototype scope in C isn't 9231 // visible elsewhere, so merely issue a warning. 9232 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 9233 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 9234 else 9235 Diag(NameLoc, diag::err_redefinition) << Name; 9236 Diag(Def->getLocation(), diag::note_previous_definition); 9237 // If this is a redefinition, recover by making this 9238 // struct be anonymous, which will make any later 9239 // references get the previous definition. 9240 Name = 0; 9241 Previous.clear(); 9242 Invalid = true; 9243 } 9244 } else { 9245 // If the type is currently being defined, complain 9246 // about a nested redefinition. 9247 const TagType *Tag 9248 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 9249 if (Tag->isBeingDefined()) { 9250 Diag(NameLoc, diag::err_nested_redefinition) << Name; 9251 Diag(PrevTagDecl->getLocation(), 9252 diag::note_previous_definition); 9253 Name = 0; 9254 Previous.clear(); 9255 Invalid = true; 9256 } 9257 } 9258 9259 // Okay, this is definition of a previously declared or referenced 9260 // tag PrevDecl. We're going to create a new Decl for it. 9261 } 9262 } 9263 // If we get here we have (another) forward declaration or we 9264 // have a definition. Just create a new decl. 9265 9266 } else { 9267 // If we get here, this is a definition of a new tag type in a nested 9268 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 9269 // new decl/type. We set PrevDecl to NULL so that the entities 9270 // have distinct types. 9271 Previous.clear(); 9272 } 9273 // If we get here, we're going to create a new Decl. If PrevDecl 9274 // is non-NULL, it's a definition of the tag declared by 9275 // PrevDecl. If it's NULL, we have a new definition. 9276 9277 9278 // Otherwise, PrevDecl is not a tag, but was found with tag 9279 // lookup. This is only actually possible in C++, where a few 9280 // things like templates still live in the tag namespace. 9281 } else { 9282 // Use a better diagnostic if an elaborated-type-specifier 9283 // found the wrong kind of type on the first 9284 // (non-redeclaration) lookup. 9285 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 9286 !Previous.isForRedeclaration()) { 9287 unsigned Kind = 0; 9288 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9289 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9290 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9291 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 9292 Diag(PrevDecl->getLocation(), diag::note_declared_at); 9293 Invalid = true; 9294 9295 // Otherwise, only diagnose if the declaration is in scope. 9296 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 9297 isExplicitSpecialization)) { 9298 // do nothing 9299 9300 // Diagnose implicit declarations introduced by elaborated types. 9301 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 9302 unsigned Kind = 0; 9303 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9304 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9305 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9306 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 9307 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9308 Invalid = true; 9309 9310 // Otherwise it's a declaration. Call out a particularly common 9311 // case here. 9312 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9313 unsigned Kind = 0; 9314 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 9315 Diag(NameLoc, diag::err_tag_definition_of_typedef) 9316 << Name << Kind << TND->getUnderlyingType(); 9317 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9318 Invalid = true; 9319 9320 // Otherwise, diagnose. 9321 } else { 9322 // The tag name clashes with something else in the target scope, 9323 // issue an error and recover by making this tag be anonymous. 9324 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 9325 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9326 Name = 0; 9327 Invalid = true; 9328 } 9329 9330 // The existing declaration isn't relevant to us; we're in a 9331 // new scope, so clear out the previous declaration. 9332 Previous.clear(); 9333 } 9334 } 9335 9336CreateNewDecl: 9337 9338 TagDecl *PrevDecl = 0; 9339 if (Previous.isSingleResult()) 9340 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 9341 9342 // If there is an identifier, use the location of the identifier as the 9343 // location of the decl, otherwise use the location of the struct/union 9344 // keyword. 9345 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 9346 9347 // Otherwise, create a new declaration. If there is a previous 9348 // declaration of the same entity, the two will be linked via 9349 // PrevDecl. 9350 TagDecl *New; 9351 9352 bool IsForwardReference = false; 9353 if (Kind == TTK_Enum) { 9354 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9355 // enum X { A, B, C } D; D should chain to X. 9356 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 9357 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 9358 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 9359 // If this is an undefined enum, warn. 9360 if (TUK != TUK_Definition && !Invalid) { 9361 TagDecl *Def; 9362 if (getLangOpts().CPlusPlus11 && cast<EnumDecl>(New)->isFixed()) { 9363 // C++0x: 7.2p2: opaque-enum-declaration. 9364 // Conflicts are diagnosed above. Do nothing. 9365 } 9366 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 9367 Diag(Loc, diag::ext_forward_ref_enum_def) 9368 << New; 9369 Diag(Def->getLocation(), diag::note_previous_definition); 9370 } else { 9371 unsigned DiagID = diag::ext_forward_ref_enum; 9372 if (getLangOpts().MicrosoftMode) 9373 DiagID = diag::ext_ms_forward_ref_enum; 9374 else if (getLangOpts().CPlusPlus) 9375 DiagID = diag::err_forward_ref_enum; 9376 Diag(Loc, DiagID); 9377 9378 // If this is a forward-declared reference to an enumeration, make a 9379 // note of it; we won't actually be introducing the declaration into 9380 // the declaration context. 9381 if (TUK == TUK_Reference) 9382 IsForwardReference = true; 9383 } 9384 } 9385 9386 if (EnumUnderlying) { 9387 EnumDecl *ED = cast<EnumDecl>(New); 9388 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9389 ED->setIntegerTypeSourceInfo(TI); 9390 else 9391 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 9392 ED->setPromotionType(ED->getIntegerType()); 9393 } 9394 9395 } else { 9396 // struct/union/class 9397 9398 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9399 // struct X { int A; } D; D should chain to X. 9400 if (getLangOpts().CPlusPlus) { 9401 // FIXME: Look for a way to use RecordDecl for simple structs. 9402 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9403 cast_or_null<CXXRecordDecl>(PrevDecl)); 9404 9405 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 9406 StdBadAlloc = cast<CXXRecordDecl>(New); 9407 } else 9408 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9409 cast_or_null<RecordDecl>(PrevDecl)); 9410 } 9411 9412 // Maybe add qualifier info. 9413 if (SS.isNotEmpty()) { 9414 if (SS.isSet()) { 9415 // If this is either a declaration or a definition, check the 9416 // nested-name-specifier against the current context. We don't do this 9417 // for explicit specializations, because they have similar checking 9418 // (with more specific diagnostics) in the call to 9419 // CheckMemberSpecialization, below. 9420 if (!isExplicitSpecialization && 9421 (TUK == TUK_Definition || TUK == TUK_Declaration) && 9422 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 9423 Invalid = true; 9424 9425 New->setQualifierInfo(SS.getWithLocInContext(Context)); 9426 if (TemplateParameterLists.size() > 0) { 9427 New->setTemplateParameterListsInfo(Context, 9428 TemplateParameterLists.size(), 9429 TemplateParameterLists.data()); 9430 } 9431 } 9432 else 9433 Invalid = true; 9434 } 9435 9436 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 9437 // Add alignment attributes if necessary; these attributes are checked when 9438 // the ASTContext lays out the structure. 9439 // 9440 // It is important for implementing the correct semantics that this 9441 // happen here (in act on tag decl). The #pragma pack stack is 9442 // maintained as a result of parser callbacks which can occur at 9443 // many points during the parsing of a struct declaration (because 9444 // the #pragma tokens are effectively skipped over during the 9445 // parsing of the struct). 9446 if (TUK == TUK_Definition) { 9447 AddAlignmentAttributesForRecord(RD); 9448 AddMsStructLayoutForRecord(RD); 9449 } 9450 } 9451 9452 if (ModulePrivateLoc.isValid()) { 9453 if (isExplicitSpecialization) 9454 Diag(New->getLocation(), diag::err_module_private_specialization) 9455 << 2 9456 << FixItHint::CreateRemoval(ModulePrivateLoc); 9457 // __module_private__ does not apply to local classes. However, we only 9458 // diagnose this as an error when the declaration specifiers are 9459 // freestanding. Here, we just ignore the __module_private__. 9460 else if (!SearchDC->isFunctionOrMethod()) 9461 New->setModulePrivate(); 9462 } 9463 9464 // If this is a specialization of a member class (of a class template), 9465 // check the specialization. 9466 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 9467 Invalid = true; 9468 9469 if (Invalid) 9470 New->setInvalidDecl(); 9471 9472 if (Attr) 9473 ProcessDeclAttributeList(S, New, Attr); 9474 9475 // If we're declaring or defining a tag in function prototype scope 9476 // in C, note that this type can only be used within the function. 9477 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 9478 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 9479 9480 // Set the lexical context. If the tag has a C++ scope specifier, the 9481 // lexical context will be different from the semantic context. 9482 New->setLexicalDeclContext(CurContext); 9483 9484 // Mark this as a friend decl if applicable. 9485 // In Microsoft mode, a friend declaration also acts as a forward 9486 // declaration so we always pass true to setObjectOfFriendDecl to make 9487 // the tag name visible. 9488 if (TUK == TUK_Friend) 9489 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 9490 getLangOpts().MicrosoftExt); 9491 9492 // Set the access specifier. 9493 if (!Invalid && SearchDC->isRecord()) 9494 SetMemberAccessSpecifier(New, PrevDecl, AS); 9495 9496 if (TUK == TUK_Definition) 9497 New->startDefinition(); 9498 9499 // If this has an identifier, add it to the scope stack. 9500 if (TUK == TUK_Friend) { 9501 // We might be replacing an existing declaration in the lookup tables; 9502 // if so, borrow its access specifier. 9503 if (PrevDecl) 9504 New->setAccess(PrevDecl->getAccess()); 9505 9506 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 9507 DC->makeDeclVisibleInContext(New); 9508 if (Name) // can be null along some error paths 9509 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 9510 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 9511 } else if (Name) { 9512 S = getNonFieldDeclScope(S); 9513 PushOnScopeChains(New, S, !IsForwardReference); 9514 if (IsForwardReference) 9515 SearchDC->makeDeclVisibleInContext(New); 9516 9517 } else { 9518 CurContext->addDecl(New); 9519 } 9520 9521 // If this is the C FILE type, notify the AST context. 9522 if (IdentifierInfo *II = New->getIdentifier()) 9523 if (!New->isInvalidDecl() && 9524 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 9525 II->isStr("FILE")) 9526 Context.setFILEDecl(New); 9527 9528 // If we were in function prototype scope (and not in C++ mode), add this 9529 // tag to the list of decls to inject into the function definition scope. 9530 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 9531 InFunctionDeclarator && Name) 9532 DeclsInPrototypeScope.push_back(New); 9533 9534 if (PrevDecl) 9535 mergeDeclAttributes(New, PrevDecl); 9536 9537 // If there's a #pragma GCC visibility in scope, set the visibility of this 9538 // record. 9539 AddPushedVisibilityAttribute(New); 9540 9541 OwnedDecl = true; 9542 // In C++, don't return an invalid declaration. We can't recover well from 9543 // the cases where we make the type anonymous. 9544 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 9545} 9546 9547void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 9548 AdjustDeclIfTemplate(TagD); 9549 TagDecl *Tag = cast<TagDecl>(TagD); 9550 9551 // Enter the tag context. 9552 PushDeclContext(S, Tag); 9553 9554 ActOnDocumentableDecl(TagD); 9555 9556 // If there's a #pragma GCC visibility in scope, set the visibility of this 9557 // record. 9558 AddPushedVisibilityAttribute(Tag); 9559} 9560 9561Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 9562 assert(isa<ObjCContainerDecl>(IDecl) && 9563 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 9564 DeclContext *OCD = cast<DeclContext>(IDecl); 9565 assert(getContainingDC(OCD) == CurContext && 9566 "The next DeclContext should be lexically contained in the current one."); 9567 CurContext = OCD; 9568 return IDecl; 9569} 9570 9571void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 9572 SourceLocation FinalLoc, 9573 SourceLocation LBraceLoc) { 9574 AdjustDeclIfTemplate(TagD); 9575 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 9576 9577 FieldCollector->StartClass(); 9578 9579 if (!Record->getIdentifier()) 9580 return; 9581 9582 if (FinalLoc.isValid()) 9583 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 9584 9585 // C++ [class]p2: 9586 // [...] The class-name is also inserted into the scope of the 9587 // class itself; this is known as the injected-class-name. For 9588 // purposes of access checking, the injected-class-name is treated 9589 // as if it were a public member name. 9590 CXXRecordDecl *InjectedClassName 9591 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 9592 Record->getLocStart(), Record->getLocation(), 9593 Record->getIdentifier(), 9594 /*PrevDecl=*/0, 9595 /*DelayTypeCreation=*/true); 9596 Context.getTypeDeclType(InjectedClassName, Record); 9597 InjectedClassName->setImplicit(); 9598 InjectedClassName->setAccess(AS_public); 9599 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 9600 InjectedClassName->setDescribedClassTemplate(Template); 9601 PushOnScopeChains(InjectedClassName, S); 9602 assert(InjectedClassName->isInjectedClassName() && 9603 "Broken injected-class-name"); 9604} 9605 9606void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 9607 SourceLocation RBraceLoc) { 9608 AdjustDeclIfTemplate(TagD); 9609 TagDecl *Tag = cast<TagDecl>(TagD); 9610 Tag->setRBraceLoc(RBraceLoc); 9611 9612 // Make sure we "complete" the definition even it is invalid. 9613 if (Tag->isBeingDefined()) { 9614 assert(Tag->isInvalidDecl() && "We should already have completed it"); 9615 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 9616 RD->completeDefinition(); 9617 } 9618 9619 if (isa<CXXRecordDecl>(Tag)) 9620 FieldCollector->FinishClass(); 9621 9622 // Exit this scope of this tag's definition. 9623 PopDeclContext(); 9624 9625 // Notify the consumer that we've defined a tag. 9626 Consumer.HandleTagDeclDefinition(Tag); 9627} 9628 9629void Sema::ActOnObjCContainerFinishDefinition() { 9630 // Exit this scope of this interface definition. 9631 PopDeclContext(); 9632} 9633 9634void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 9635 assert(DC == CurContext && "Mismatch of container contexts"); 9636 OriginalLexicalContext = DC; 9637 ActOnObjCContainerFinishDefinition(); 9638} 9639 9640void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 9641 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 9642 OriginalLexicalContext = 0; 9643} 9644 9645void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 9646 AdjustDeclIfTemplate(TagD); 9647 TagDecl *Tag = cast<TagDecl>(TagD); 9648 Tag->setInvalidDecl(); 9649 9650 // Make sure we "complete" the definition even it is invalid. 9651 if (Tag->isBeingDefined()) { 9652 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 9653 RD->completeDefinition(); 9654 } 9655 9656 // We're undoing ActOnTagStartDefinition here, not 9657 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 9658 // the FieldCollector. 9659 9660 PopDeclContext(); 9661} 9662 9663// Note that FieldName may be null for anonymous bitfields. 9664ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 9665 IdentifierInfo *FieldName, 9666 QualType FieldTy, Expr *BitWidth, 9667 bool *ZeroWidth) { 9668 // Default to true; that shouldn't confuse checks for emptiness 9669 if (ZeroWidth) 9670 *ZeroWidth = true; 9671 9672 // C99 6.7.2.1p4 - verify the field type. 9673 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 9674 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 9675 // Handle incomplete types with specific error. 9676 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 9677 return ExprError(); 9678 if (FieldName) 9679 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 9680 << FieldName << FieldTy << BitWidth->getSourceRange(); 9681 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 9682 << FieldTy << BitWidth->getSourceRange(); 9683 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 9684 UPPC_BitFieldWidth)) 9685 return ExprError(); 9686 9687 // If the bit-width is type- or value-dependent, don't try to check 9688 // it now. 9689 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 9690 return Owned(BitWidth); 9691 9692 llvm::APSInt Value; 9693 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 9694 if (ICE.isInvalid()) 9695 return ICE; 9696 BitWidth = ICE.take(); 9697 9698 if (Value != 0 && ZeroWidth) 9699 *ZeroWidth = false; 9700 9701 // Zero-width bitfield is ok for anonymous field. 9702 if (Value == 0 && FieldName) 9703 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 9704 9705 if (Value.isSigned() && Value.isNegative()) { 9706 if (FieldName) 9707 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 9708 << FieldName << Value.toString(10); 9709 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 9710 << Value.toString(10); 9711 } 9712 9713 if (!FieldTy->isDependentType()) { 9714 uint64_t TypeSize = Context.getTypeSize(FieldTy); 9715 if (Value.getZExtValue() > TypeSize) { 9716 if (!getLangOpts().CPlusPlus) { 9717 if (FieldName) 9718 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 9719 << FieldName << (unsigned)Value.getZExtValue() 9720 << (unsigned)TypeSize; 9721 9722 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 9723 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 9724 } 9725 9726 if (FieldName) 9727 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 9728 << FieldName << (unsigned)Value.getZExtValue() 9729 << (unsigned)TypeSize; 9730 else 9731 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 9732 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 9733 } 9734 } 9735 9736 return Owned(BitWidth); 9737} 9738 9739/// ActOnField - Each field of a C struct/union is passed into this in order 9740/// to create a FieldDecl object for it. 9741Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 9742 Declarator &D, Expr *BitfieldWidth) { 9743 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 9744 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 9745 /*InitStyle=*/ICIS_NoInit, AS_public); 9746 return Res; 9747} 9748 9749/// HandleField - Analyze a field of a C struct or a C++ data member. 9750/// 9751FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 9752 SourceLocation DeclStart, 9753 Declarator &D, Expr *BitWidth, 9754 InClassInitStyle InitStyle, 9755 AccessSpecifier AS) { 9756 IdentifierInfo *II = D.getIdentifier(); 9757 SourceLocation Loc = DeclStart; 9758 if (II) Loc = D.getIdentifierLoc(); 9759 9760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9761 QualType T = TInfo->getType(); 9762 if (getLangOpts().CPlusPlus) { 9763 CheckExtraCXXDefaultArguments(D); 9764 9765 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9766 UPPC_DataMemberType)) { 9767 D.setInvalidType(); 9768 T = Context.IntTy; 9769 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 9770 } 9771 } 9772 9773 DiagnoseFunctionSpecifiers(D); 9774 9775 if (D.getDeclSpec().isThreadSpecified()) 9776 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 9777 if (D.getDeclSpec().isConstexprSpecified()) 9778 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 9779 << 2; 9780 9781 // Check to see if this name was declared as a member previously 9782 NamedDecl *PrevDecl = 0; 9783 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 9784 LookupName(Previous, S); 9785 switch (Previous.getResultKind()) { 9786 case LookupResult::Found: 9787 case LookupResult::FoundUnresolvedValue: 9788 PrevDecl = Previous.getAsSingle<NamedDecl>(); 9789 break; 9790 9791 case LookupResult::FoundOverloaded: 9792 PrevDecl = Previous.getRepresentativeDecl(); 9793 break; 9794 9795 case LookupResult::NotFound: 9796 case LookupResult::NotFoundInCurrentInstantiation: 9797 case LookupResult::Ambiguous: 9798 break; 9799 } 9800 Previous.suppressDiagnostics(); 9801 9802 if (PrevDecl && PrevDecl->isTemplateParameter()) { 9803 // Maybe we will complain about the shadowed template parameter. 9804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9805 // Just pretend that we didn't see the previous declaration. 9806 PrevDecl = 0; 9807 } 9808 9809 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 9810 PrevDecl = 0; 9811 9812 bool Mutable 9813 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 9814 SourceLocation TSSL = D.getLocStart(); 9815 FieldDecl *NewFD 9816 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 9817 TSSL, AS, PrevDecl, &D); 9818 9819 if (NewFD->isInvalidDecl()) 9820 Record->setInvalidDecl(); 9821 9822 if (D.getDeclSpec().isModulePrivateSpecified()) 9823 NewFD->setModulePrivate(); 9824 9825 if (NewFD->isInvalidDecl() && PrevDecl) { 9826 // Don't introduce NewFD into scope; there's already something 9827 // with the same name in the same scope. 9828 } else if (II) { 9829 PushOnScopeChains(NewFD, S); 9830 } else 9831 Record->addDecl(NewFD); 9832 9833 return NewFD; 9834} 9835 9836/// \brief Build a new FieldDecl and check its well-formedness. 9837/// 9838/// This routine builds a new FieldDecl given the fields name, type, 9839/// record, etc. \p PrevDecl should refer to any previous declaration 9840/// with the same name and in the same scope as the field to be 9841/// created. 9842/// 9843/// \returns a new FieldDecl. 9844/// 9845/// \todo The Declarator argument is a hack. It will be removed once 9846FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 9847 TypeSourceInfo *TInfo, 9848 RecordDecl *Record, SourceLocation Loc, 9849 bool Mutable, Expr *BitWidth, 9850 InClassInitStyle InitStyle, 9851 SourceLocation TSSL, 9852 AccessSpecifier AS, NamedDecl *PrevDecl, 9853 Declarator *D) { 9854 IdentifierInfo *II = Name.getAsIdentifierInfo(); 9855 bool InvalidDecl = false; 9856 if (D) InvalidDecl = D->isInvalidType(); 9857 9858 // If we receive a broken type, recover by assuming 'int' and 9859 // marking this declaration as invalid. 9860 if (T.isNull()) { 9861 InvalidDecl = true; 9862 T = Context.IntTy; 9863 } 9864 9865 QualType EltTy = Context.getBaseElementType(T); 9866 if (!EltTy->isDependentType()) { 9867 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 9868 // Fields of incomplete type force their record to be invalid. 9869 Record->setInvalidDecl(); 9870 InvalidDecl = true; 9871 } else { 9872 NamedDecl *Def; 9873 EltTy->isIncompleteType(&Def); 9874 if (Def && Def->isInvalidDecl()) { 9875 Record->setInvalidDecl(); 9876 InvalidDecl = true; 9877 } 9878 } 9879 } 9880 9881 // OpenCL v1.2 s6.9.c: bitfields are not supported. 9882 if (BitWidth && getLangOpts().OpenCL) { 9883 Diag(Loc, diag::err_opencl_bitfields); 9884 InvalidDecl = true; 9885 } 9886 9887 // C99 6.7.2.1p8: A member of a structure or union may have any type other 9888 // than a variably modified type. 9889 if (!InvalidDecl && T->isVariablyModifiedType()) { 9890 bool SizeIsNegative; 9891 llvm::APSInt Oversized; 9892 9893 TypeSourceInfo *FixedTInfo = 9894 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 9895 SizeIsNegative, 9896 Oversized); 9897 if (FixedTInfo) { 9898 Diag(Loc, diag::warn_illegal_constant_array_size); 9899 TInfo = FixedTInfo; 9900 T = FixedTInfo->getType(); 9901 } else { 9902 if (SizeIsNegative) 9903 Diag(Loc, diag::err_typecheck_negative_array_size); 9904 else if (Oversized.getBoolValue()) 9905 Diag(Loc, diag::err_array_too_large) 9906 << Oversized.toString(10); 9907 else 9908 Diag(Loc, diag::err_typecheck_field_variable_size); 9909 InvalidDecl = true; 9910 } 9911 } 9912 9913 // Fields can not have abstract class types 9914 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 9915 diag::err_abstract_type_in_decl, 9916 AbstractFieldType)) 9917 InvalidDecl = true; 9918 9919 bool ZeroWidth = false; 9920 // If this is declared as a bit-field, check the bit-field. 9921 if (!InvalidDecl && BitWidth) { 9922 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 9923 if (!BitWidth) { 9924 InvalidDecl = true; 9925 BitWidth = 0; 9926 ZeroWidth = false; 9927 } 9928 } 9929 9930 // Check that 'mutable' is consistent with the type of the declaration. 9931 if (!InvalidDecl && Mutable) { 9932 unsigned DiagID = 0; 9933 if (T->isReferenceType()) 9934 DiagID = diag::err_mutable_reference; 9935 else if (T.isConstQualified()) 9936 DiagID = diag::err_mutable_const; 9937 9938 if (DiagID) { 9939 SourceLocation ErrLoc = Loc; 9940 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 9941 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 9942 Diag(ErrLoc, DiagID); 9943 Mutable = false; 9944 InvalidDecl = true; 9945 } 9946 } 9947 9948 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 9949 BitWidth, Mutable, InitStyle); 9950 if (InvalidDecl) 9951 NewFD->setInvalidDecl(); 9952 9953 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 9954 Diag(Loc, diag::err_duplicate_member) << II; 9955 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9956 NewFD->setInvalidDecl(); 9957 } 9958 9959 if (!InvalidDecl && getLangOpts().CPlusPlus) { 9960 if (Record->isUnion()) { 9961 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 9962 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 9963 if (RDecl->getDefinition()) { 9964 // C++ [class.union]p1: An object of a class with a non-trivial 9965 // constructor, a non-trivial copy constructor, a non-trivial 9966 // destructor, or a non-trivial copy assignment operator 9967 // cannot be a member of a union, nor can an array of such 9968 // objects. 9969 if (CheckNontrivialField(NewFD)) 9970 NewFD->setInvalidDecl(); 9971 } 9972 } 9973 9974 // C++ [class.union]p1: If a union contains a member of reference type, 9975 // the program is ill-formed. 9976 if (EltTy->isReferenceType()) { 9977 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 9978 << NewFD->getDeclName() << EltTy; 9979 NewFD->setInvalidDecl(); 9980 } 9981 } 9982 } 9983 9984 // FIXME: We need to pass in the attributes given an AST 9985 // representation, not a parser representation. 9986 if (D) 9987 // FIXME: What to pass instead of TUScope? 9988 ProcessDeclAttributes(TUScope, NewFD, *D); 9989 9990 // In auto-retain/release, infer strong retension for fields of 9991 // retainable type. 9992 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 9993 NewFD->setInvalidDecl(); 9994 9995 if (T.isObjCGCWeak()) 9996 Diag(Loc, diag::warn_attribute_weak_on_field); 9997 9998 NewFD->setAccess(AS); 9999 return NewFD; 10000} 10001 10002bool Sema::CheckNontrivialField(FieldDecl *FD) { 10003 assert(FD); 10004 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 10005 10006 if (FD->isInvalidDecl()) 10007 return true; 10008 10009 QualType EltTy = Context.getBaseElementType(FD->getType()); 10010 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10011 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10012 if (RDecl->getDefinition()) { 10013 // We check for copy constructors before constructors 10014 // because otherwise we'll never get complaints about 10015 // copy constructors. 10016 10017 CXXSpecialMember member = CXXInvalid; 10018 // We're required to check for any non-trivial constructors. Since the 10019 // implicit default constructor is suppressed if there are any 10020 // user-declared constructors, we just need to check that there is a 10021 // trivial default constructor and a trivial copy constructor. (We don't 10022 // worry about move constructors here, since this is a C++98 check.) 10023 if (RDecl->hasNonTrivialCopyConstructor()) 10024 member = CXXCopyConstructor; 10025 else if (!RDecl->hasTrivialDefaultConstructor()) 10026 member = CXXDefaultConstructor; 10027 else if (RDecl->hasNonTrivialCopyAssignment()) 10028 member = CXXCopyAssignment; 10029 else if (RDecl->hasNonTrivialDestructor()) 10030 member = CXXDestructor; 10031 10032 if (member != CXXInvalid) { 10033 if (!getLangOpts().CPlusPlus11 && 10034 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 10035 // Objective-C++ ARC: it is an error to have a non-trivial field of 10036 // a union. However, system headers in Objective-C programs 10037 // occasionally have Objective-C lifetime objects within unions, 10038 // and rather than cause the program to fail, we make those 10039 // members unavailable. 10040 SourceLocation Loc = FD->getLocation(); 10041 if (getSourceManager().isInSystemHeader(Loc)) { 10042 if (!FD->hasAttr<UnavailableAttr>()) 10043 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 10044 "this system field has retaining ownership")); 10045 return false; 10046 } 10047 } 10048 10049 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 10050 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 10051 diag::err_illegal_union_or_anon_struct_member) 10052 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 10053 DiagnoseNontrivial(RDecl, member); 10054 return !getLangOpts().CPlusPlus11; 10055 } 10056 } 10057 } 10058 10059 return false; 10060} 10061 10062/// TranslateIvarVisibility - Translate visibility from a token ID to an 10063/// AST enum value. 10064static ObjCIvarDecl::AccessControl 10065TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 10066 switch (ivarVisibility) { 10067 default: llvm_unreachable("Unknown visitibility kind"); 10068 case tok::objc_private: return ObjCIvarDecl::Private; 10069 case tok::objc_public: return ObjCIvarDecl::Public; 10070 case tok::objc_protected: return ObjCIvarDecl::Protected; 10071 case tok::objc_package: return ObjCIvarDecl::Package; 10072 } 10073} 10074 10075/// ActOnIvar - Each ivar field of an objective-c class is passed into this 10076/// in order to create an IvarDecl object for it. 10077Decl *Sema::ActOnIvar(Scope *S, 10078 SourceLocation DeclStart, 10079 Declarator &D, Expr *BitfieldWidth, 10080 tok::ObjCKeywordKind Visibility) { 10081 10082 IdentifierInfo *II = D.getIdentifier(); 10083 Expr *BitWidth = (Expr*)BitfieldWidth; 10084 SourceLocation Loc = DeclStart; 10085 if (II) Loc = D.getIdentifierLoc(); 10086 10087 // FIXME: Unnamed fields can be handled in various different ways, for 10088 // example, unnamed unions inject all members into the struct namespace! 10089 10090 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10091 QualType T = TInfo->getType(); 10092 10093 if (BitWidth) { 10094 // 6.7.2.1p3, 6.7.2.1p4 10095 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 10096 if (!BitWidth) 10097 D.setInvalidType(); 10098 } else { 10099 // Not a bitfield. 10100 10101 // validate II. 10102 10103 } 10104 if (T->isReferenceType()) { 10105 Diag(Loc, diag::err_ivar_reference_type); 10106 D.setInvalidType(); 10107 } 10108 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10109 // than a variably modified type. 10110 else if (T->isVariablyModifiedType()) { 10111 Diag(Loc, diag::err_typecheck_ivar_variable_size); 10112 D.setInvalidType(); 10113 } 10114 10115 // Get the visibility (access control) for this ivar. 10116 ObjCIvarDecl::AccessControl ac = 10117 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 10118 : ObjCIvarDecl::None; 10119 // Must set ivar's DeclContext to its enclosing interface. 10120 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 10121 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 10122 return 0; 10123 ObjCContainerDecl *EnclosingContext; 10124 if (ObjCImplementationDecl *IMPDecl = 10125 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10126 if (LangOpts.ObjCRuntime.isFragile()) { 10127 // Case of ivar declared in an implementation. Context is that of its class. 10128 EnclosingContext = IMPDecl->getClassInterface(); 10129 assert(EnclosingContext && "Implementation has no class interface!"); 10130 } 10131 else 10132 EnclosingContext = EnclosingDecl; 10133 } else { 10134 if (ObjCCategoryDecl *CDecl = 10135 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10136 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 10137 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 10138 return 0; 10139 } 10140 } 10141 EnclosingContext = EnclosingDecl; 10142 } 10143 10144 // Construct the decl. 10145 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 10146 DeclStart, Loc, II, T, 10147 TInfo, ac, (Expr *)BitfieldWidth); 10148 10149 if (II) { 10150 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 10151 ForRedeclaration); 10152 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 10153 && !isa<TagDecl>(PrevDecl)) { 10154 Diag(Loc, diag::err_duplicate_member) << II; 10155 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10156 NewID->setInvalidDecl(); 10157 } 10158 } 10159 10160 // Process attributes attached to the ivar. 10161 ProcessDeclAttributes(S, NewID, D); 10162 10163 if (D.isInvalidType()) 10164 NewID->setInvalidDecl(); 10165 10166 // In ARC, infer 'retaining' for ivars of retainable type. 10167 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 10168 NewID->setInvalidDecl(); 10169 10170 if (D.getDeclSpec().isModulePrivateSpecified()) 10171 NewID->setModulePrivate(); 10172 10173 if (II) { 10174 // FIXME: When interfaces are DeclContexts, we'll need to add 10175 // these to the interface. 10176 S->AddDecl(NewID); 10177 IdResolver.AddDecl(NewID); 10178 } 10179 10180 if (LangOpts.ObjCRuntime.isNonFragile() && 10181 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 10182 Diag(Loc, diag::warn_ivars_in_interface); 10183 10184 return NewID; 10185} 10186 10187/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 10188/// class and class extensions. For every class @interface and class 10189/// extension @interface, if the last ivar is a bitfield of any type, 10190/// then add an implicit `char :0` ivar to the end of that interface. 10191void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 10192 SmallVectorImpl<Decl *> &AllIvarDecls) { 10193 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 10194 return; 10195 10196 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 10197 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 10198 10199 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 10200 return; 10201 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 10202 if (!ID) { 10203 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 10204 if (!CD->IsClassExtension()) 10205 return; 10206 } 10207 // No need to add this to end of @implementation. 10208 else 10209 return; 10210 } 10211 // All conditions are met. Add a new bitfield to the tail end of ivars. 10212 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 10213 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 10214 10215 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 10216 DeclLoc, DeclLoc, 0, 10217 Context.CharTy, 10218 Context.getTrivialTypeSourceInfo(Context.CharTy, 10219 DeclLoc), 10220 ObjCIvarDecl::Private, BW, 10221 true); 10222 AllIvarDecls.push_back(Ivar); 10223} 10224 10225void Sema::ActOnFields(Scope* S, 10226 SourceLocation RecLoc, Decl *EnclosingDecl, 10227 llvm::ArrayRef<Decl *> Fields, 10228 SourceLocation LBrac, SourceLocation RBrac, 10229 AttributeList *Attr) { 10230 assert(EnclosingDecl && "missing record or interface decl"); 10231 10232 // If this is an Objective-C @implementation or category and we have 10233 // new fields here we should reset the layout of the interface since 10234 // it will now change. 10235 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 10236 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 10237 switch (DC->getKind()) { 10238 default: break; 10239 case Decl::ObjCCategory: 10240 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 10241 break; 10242 case Decl::ObjCImplementation: 10243 Context. 10244 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 10245 break; 10246 } 10247 } 10248 10249 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 10250 10251 // Start counting up the number of named members; make sure to include 10252 // members of anonymous structs and unions in the total. 10253 unsigned NumNamedMembers = 0; 10254 if (Record) { 10255 for (RecordDecl::decl_iterator i = Record->decls_begin(), 10256 e = Record->decls_end(); i != e; i++) { 10257 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 10258 if (IFD->getDeclName()) 10259 ++NumNamedMembers; 10260 } 10261 } 10262 10263 // Verify that all the fields are okay. 10264 SmallVector<FieldDecl*, 32> RecFields; 10265 10266 bool ARCErrReported = false; 10267 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 10268 i != end; ++i) { 10269 FieldDecl *FD = cast<FieldDecl>(*i); 10270 10271 // Get the type for the field. 10272 const Type *FDTy = FD->getType().getTypePtr(); 10273 10274 if (!FD->isAnonymousStructOrUnion()) { 10275 // Remember all fields written by the user. 10276 RecFields.push_back(FD); 10277 } 10278 10279 // If the field is already invalid for some reason, don't emit more 10280 // diagnostics about it. 10281 if (FD->isInvalidDecl()) { 10282 EnclosingDecl->setInvalidDecl(); 10283 continue; 10284 } 10285 10286 // C99 6.7.2.1p2: 10287 // A structure or union shall not contain a member with 10288 // incomplete or function type (hence, a structure shall not 10289 // contain an instance of itself, but may contain a pointer to 10290 // an instance of itself), except that the last member of a 10291 // structure with more than one named member may have incomplete 10292 // array type; such a structure (and any union containing, 10293 // possibly recursively, a member that is such a structure) 10294 // shall not be a member of a structure or an element of an 10295 // array. 10296 if (FDTy->isFunctionType()) { 10297 // Field declared as a function. 10298 Diag(FD->getLocation(), diag::err_field_declared_as_function) 10299 << FD->getDeclName(); 10300 FD->setInvalidDecl(); 10301 EnclosingDecl->setInvalidDecl(); 10302 continue; 10303 } else if (FDTy->isIncompleteArrayType() && Record && 10304 ((i + 1 == Fields.end() && !Record->isUnion()) || 10305 ((getLangOpts().MicrosoftExt || 10306 getLangOpts().CPlusPlus) && 10307 (i + 1 == Fields.end() || Record->isUnion())))) { 10308 // Flexible array member. 10309 // Microsoft and g++ is more permissive regarding flexible array. 10310 // It will accept flexible array in union and also 10311 // as the sole element of a struct/class. 10312 if (getLangOpts().MicrosoftExt) { 10313 if (Record->isUnion()) 10314 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 10315 << FD->getDeclName(); 10316 else if (Fields.size() == 1) 10317 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 10318 << FD->getDeclName() << Record->getTagKind(); 10319 } else if (getLangOpts().CPlusPlus) { 10320 if (Record->isUnion()) 10321 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10322 << FD->getDeclName(); 10323 else if (Fields.size() == 1) 10324 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 10325 << FD->getDeclName() << Record->getTagKind(); 10326 } else if (!getLangOpts().C99) { 10327 if (Record->isUnion()) 10328 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10329 << FD->getDeclName(); 10330 else 10331 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 10332 << FD->getDeclName() << Record->getTagKind(); 10333 } else if (NumNamedMembers < 1) { 10334 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 10335 << FD->getDeclName(); 10336 FD->setInvalidDecl(); 10337 EnclosingDecl->setInvalidDecl(); 10338 continue; 10339 } 10340 if (!FD->getType()->isDependentType() && 10341 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 10342 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 10343 << FD->getDeclName() << FD->getType(); 10344 FD->setInvalidDecl(); 10345 EnclosingDecl->setInvalidDecl(); 10346 continue; 10347 } 10348 // Okay, we have a legal flexible array member at the end of the struct. 10349 if (Record) 10350 Record->setHasFlexibleArrayMember(true); 10351 } else if (!FDTy->isDependentType() && 10352 RequireCompleteType(FD->getLocation(), FD->getType(), 10353 diag::err_field_incomplete)) { 10354 // Incomplete type 10355 FD->setInvalidDecl(); 10356 EnclosingDecl->setInvalidDecl(); 10357 continue; 10358 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 10359 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 10360 // If this is a member of a union, then entire union becomes "flexible". 10361 if (Record && Record->isUnion()) { 10362 Record->setHasFlexibleArrayMember(true); 10363 } else { 10364 // If this is a struct/class and this is not the last element, reject 10365 // it. Note that GCC supports variable sized arrays in the middle of 10366 // structures. 10367 if (i + 1 != Fields.end()) 10368 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 10369 << FD->getDeclName() << FD->getType(); 10370 else { 10371 // We support flexible arrays at the end of structs in 10372 // other structs as an extension. 10373 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 10374 << FD->getDeclName(); 10375 if (Record) 10376 Record->setHasFlexibleArrayMember(true); 10377 } 10378 } 10379 } 10380 if (isa<ObjCContainerDecl>(EnclosingDecl) && 10381 RequireNonAbstractType(FD->getLocation(), FD->getType(), 10382 diag::err_abstract_type_in_decl, 10383 AbstractIvarType)) { 10384 // Ivars can not have abstract class types 10385 FD->setInvalidDecl(); 10386 } 10387 if (Record && FDTTy->getDecl()->hasObjectMember()) 10388 Record->setHasObjectMember(true); 10389 } else if (FDTy->isObjCObjectType()) { 10390 /// A field cannot be an Objective-c object 10391 Diag(FD->getLocation(), diag::err_statically_allocated_object) 10392 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 10393 QualType T = Context.getObjCObjectPointerType(FD->getType()); 10394 FD->setType(T); 10395 } else if (!getLangOpts().CPlusPlus) { 10396 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) { 10397 // It's an error in ARC if a field has lifetime. 10398 // We don't want to report this in a system header, though, 10399 // so we just make the field unavailable. 10400 // FIXME: that's really not sufficient; we need to make the type 10401 // itself invalid to, say, initialize or copy. 10402 QualType T = FD->getType(); 10403 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 10404 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 10405 SourceLocation loc = FD->getLocation(); 10406 if (getSourceManager().isInSystemHeader(loc)) { 10407 if (!FD->hasAttr<UnavailableAttr>()) { 10408 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 10409 "this system field has retaining ownership")); 10410 } 10411 } else { 10412 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct) 10413 << T->isBlockPointerType(); 10414 } 10415 ARCErrReported = true; 10416 } 10417 } 10418 else if (getLangOpts().ObjC1 && 10419 getLangOpts().getGC() != LangOptions::NonGC && 10420 Record && !Record->hasObjectMember()) { 10421 if (FD->getType()->isObjCObjectPointerType() || 10422 FD->getType().isObjCGCStrong()) 10423 Record->setHasObjectMember(true); 10424 else if (Context.getAsArrayType(FD->getType())) { 10425 QualType BaseType = Context.getBaseElementType(FD->getType()); 10426 if (BaseType->isRecordType() && 10427 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 10428 Record->setHasObjectMember(true); 10429 else if (BaseType->isObjCObjectPointerType() || 10430 BaseType.isObjCGCStrong()) 10431 Record->setHasObjectMember(true); 10432 } 10433 } 10434 } 10435 // Keep track of the number of named members. 10436 if (FD->getIdentifier()) 10437 ++NumNamedMembers; 10438 } 10439 10440 // Okay, we successfully defined 'Record'. 10441 if (Record) { 10442 bool Completed = false; 10443 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 10444 if (!CXXRecord->isInvalidDecl()) { 10445 // Set access bits correctly on the directly-declared conversions. 10446 for (CXXRecordDecl::conversion_iterator 10447 I = CXXRecord->conversion_begin(), 10448 E = CXXRecord->conversion_end(); I != E; ++I) 10449 I.setAccess((*I)->getAccess()); 10450 10451 if (!CXXRecord->isDependentType()) { 10452 // Adjust user-defined destructor exception spec. 10453 if (getLangOpts().CPlusPlus11 && 10454 CXXRecord->hasUserDeclaredDestructor()) 10455 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 10456 10457 // Add any implicitly-declared members to this class. 10458 AddImplicitlyDeclaredMembersToClass(CXXRecord); 10459 10460 // If we have virtual base classes, we may end up finding multiple 10461 // final overriders for a given virtual function. Check for this 10462 // problem now. 10463 if (CXXRecord->getNumVBases()) { 10464 CXXFinalOverriderMap FinalOverriders; 10465 CXXRecord->getFinalOverriders(FinalOverriders); 10466 10467 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 10468 MEnd = FinalOverriders.end(); 10469 M != MEnd; ++M) { 10470 for (OverridingMethods::iterator SO = M->second.begin(), 10471 SOEnd = M->second.end(); 10472 SO != SOEnd; ++SO) { 10473 assert(SO->second.size() > 0 && 10474 "Virtual function without overridding functions?"); 10475 if (SO->second.size() == 1) 10476 continue; 10477 10478 // C++ [class.virtual]p2: 10479 // In a derived class, if a virtual member function of a base 10480 // class subobject has more than one final overrider the 10481 // program is ill-formed. 10482 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 10483 << (const NamedDecl *)M->first << Record; 10484 Diag(M->first->getLocation(), 10485 diag::note_overridden_virtual_function); 10486 for (OverridingMethods::overriding_iterator 10487 OM = SO->second.begin(), 10488 OMEnd = SO->second.end(); 10489 OM != OMEnd; ++OM) 10490 Diag(OM->Method->getLocation(), diag::note_final_overrider) 10491 << (const NamedDecl *)M->first << OM->Method->getParent(); 10492 10493 Record->setInvalidDecl(); 10494 } 10495 } 10496 CXXRecord->completeDefinition(&FinalOverriders); 10497 Completed = true; 10498 } 10499 } 10500 } 10501 } 10502 10503 if (!Completed) 10504 Record->completeDefinition(); 10505 10506 } else { 10507 ObjCIvarDecl **ClsFields = 10508 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 10509 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 10510 ID->setEndOfDefinitionLoc(RBrac); 10511 // Add ivar's to class's DeclContext. 10512 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10513 ClsFields[i]->setLexicalDeclContext(ID); 10514 ID->addDecl(ClsFields[i]); 10515 } 10516 // Must enforce the rule that ivars in the base classes may not be 10517 // duplicates. 10518 if (ID->getSuperClass()) 10519 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 10520 } else if (ObjCImplementationDecl *IMPDecl = 10521 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10522 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 10523 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 10524 // Ivar declared in @implementation never belongs to the implementation. 10525 // Only it is in implementation's lexical context. 10526 ClsFields[I]->setLexicalDeclContext(IMPDecl); 10527 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 10528 IMPDecl->setIvarLBraceLoc(LBrac); 10529 IMPDecl->setIvarRBraceLoc(RBrac); 10530 } else if (ObjCCategoryDecl *CDecl = 10531 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10532 // case of ivars in class extension; all other cases have been 10533 // reported as errors elsewhere. 10534 // FIXME. Class extension does not have a LocEnd field. 10535 // CDecl->setLocEnd(RBrac); 10536 // Add ivar's to class extension's DeclContext. 10537 // Diagnose redeclaration of private ivars. 10538 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 10539 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10540 if (IDecl) { 10541 if (const ObjCIvarDecl *ClsIvar = 10542 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 10543 Diag(ClsFields[i]->getLocation(), 10544 diag::err_duplicate_ivar_declaration); 10545 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 10546 continue; 10547 } 10548 for (ObjCInterfaceDecl::known_extensions_iterator 10549 Ext = IDecl->known_extensions_begin(), 10550 ExtEnd = IDecl->known_extensions_end(); 10551 Ext != ExtEnd; ++Ext) { 10552 if (const ObjCIvarDecl *ClsExtIvar 10553 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 10554 Diag(ClsFields[i]->getLocation(), 10555 diag::err_duplicate_ivar_declaration); 10556 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 10557 continue; 10558 } 10559 } 10560 } 10561 ClsFields[i]->setLexicalDeclContext(CDecl); 10562 CDecl->addDecl(ClsFields[i]); 10563 } 10564 CDecl->setIvarLBraceLoc(LBrac); 10565 CDecl->setIvarRBraceLoc(RBrac); 10566 } 10567 } 10568 10569 if (Attr) 10570 ProcessDeclAttributeList(S, Record, Attr); 10571} 10572 10573/// \brief Determine whether the given integral value is representable within 10574/// the given type T. 10575static bool isRepresentableIntegerValue(ASTContext &Context, 10576 llvm::APSInt &Value, 10577 QualType T) { 10578 assert(T->isIntegralType(Context) && "Integral type required!"); 10579 unsigned BitWidth = Context.getIntWidth(T); 10580 10581 if (Value.isUnsigned() || Value.isNonNegative()) { 10582 if (T->isSignedIntegerOrEnumerationType()) 10583 --BitWidth; 10584 return Value.getActiveBits() <= BitWidth; 10585 } 10586 return Value.getMinSignedBits() <= BitWidth; 10587} 10588 10589// \brief Given an integral type, return the next larger integral type 10590// (or a NULL type of no such type exists). 10591static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 10592 // FIXME: Int128/UInt128 support, which also needs to be introduced into 10593 // enum checking below. 10594 assert(T->isIntegralType(Context) && "Integral type required!"); 10595 const unsigned NumTypes = 4; 10596 QualType SignedIntegralTypes[NumTypes] = { 10597 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 10598 }; 10599 QualType UnsignedIntegralTypes[NumTypes] = { 10600 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 10601 Context.UnsignedLongLongTy 10602 }; 10603 10604 unsigned BitWidth = Context.getTypeSize(T); 10605 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 10606 : UnsignedIntegralTypes; 10607 for (unsigned I = 0; I != NumTypes; ++I) 10608 if (Context.getTypeSize(Types[I]) > BitWidth) 10609 return Types[I]; 10610 10611 return QualType(); 10612} 10613 10614EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 10615 EnumConstantDecl *LastEnumConst, 10616 SourceLocation IdLoc, 10617 IdentifierInfo *Id, 10618 Expr *Val) { 10619 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10620 llvm::APSInt EnumVal(IntWidth); 10621 QualType EltTy; 10622 10623 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 10624 Val = 0; 10625 10626 if (Val) 10627 Val = DefaultLvalueConversion(Val).take(); 10628 10629 if (Val) { 10630 if (Enum->isDependentType() || Val->isTypeDependent()) 10631 EltTy = Context.DependentTy; 10632 else { 10633 SourceLocation ExpLoc; 10634 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 10635 !getLangOpts().MicrosoftMode) { 10636 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 10637 // constant-expression in the enumerator-definition shall be a converted 10638 // constant expression of the underlying type. 10639 EltTy = Enum->getIntegerType(); 10640 ExprResult Converted = 10641 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 10642 CCEK_Enumerator); 10643 if (Converted.isInvalid()) 10644 Val = 0; 10645 else 10646 Val = Converted.take(); 10647 } else if (!Val->isValueDependent() && 10648 !(Val = VerifyIntegerConstantExpression(Val, 10649 &EnumVal).take())) { 10650 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 10651 } else { 10652 if (Enum->isFixed()) { 10653 EltTy = Enum->getIntegerType(); 10654 10655 // In Obj-C and Microsoft mode, require the enumeration value to be 10656 // representable in the underlying type of the enumeration. In C++11, 10657 // we perform a non-narrowing conversion as part of converted constant 10658 // expression checking. 10659 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10660 if (getLangOpts().MicrosoftMode) { 10661 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 10662 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10663 } else 10664 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 10665 } else 10666 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10667 } else if (getLangOpts().CPlusPlus) { 10668 // C++11 [dcl.enum]p5: 10669 // If the underlying type is not fixed, the type of each enumerator 10670 // is the type of its initializing value: 10671 // - If an initializer is specified for an enumerator, the 10672 // initializing value has the same type as the expression. 10673 EltTy = Val->getType(); 10674 } else { 10675 // C99 6.7.2.2p2: 10676 // The expression that defines the value of an enumeration constant 10677 // shall be an integer constant expression that has a value 10678 // representable as an int. 10679 10680 // Complain if the value is not representable in an int. 10681 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 10682 Diag(IdLoc, diag::ext_enum_value_not_int) 10683 << EnumVal.toString(10) << Val->getSourceRange() 10684 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 10685 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 10686 // Force the type of the expression to 'int'. 10687 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 10688 } 10689 EltTy = Val->getType(); 10690 } 10691 } 10692 } 10693 } 10694 10695 if (!Val) { 10696 if (Enum->isDependentType()) 10697 EltTy = Context.DependentTy; 10698 else if (!LastEnumConst) { 10699 // C++0x [dcl.enum]p5: 10700 // If the underlying type is not fixed, the type of each enumerator 10701 // is the type of its initializing value: 10702 // - If no initializer is specified for the first enumerator, the 10703 // initializing value has an unspecified integral type. 10704 // 10705 // GCC uses 'int' for its unspecified integral type, as does 10706 // C99 6.7.2.2p3. 10707 if (Enum->isFixed()) { 10708 EltTy = Enum->getIntegerType(); 10709 } 10710 else { 10711 EltTy = Context.IntTy; 10712 } 10713 } else { 10714 // Assign the last value + 1. 10715 EnumVal = LastEnumConst->getInitVal(); 10716 ++EnumVal; 10717 EltTy = LastEnumConst->getType(); 10718 10719 // Check for overflow on increment. 10720 if (EnumVal < LastEnumConst->getInitVal()) { 10721 // C++0x [dcl.enum]p5: 10722 // If the underlying type is not fixed, the type of each enumerator 10723 // is the type of its initializing value: 10724 // 10725 // - Otherwise the type of the initializing value is the same as 10726 // the type of the initializing value of the preceding enumerator 10727 // unless the incremented value is not representable in that type, 10728 // in which case the type is an unspecified integral type 10729 // sufficient to contain the incremented value. If no such type 10730 // exists, the program is ill-formed. 10731 QualType T = getNextLargerIntegralType(Context, EltTy); 10732 if (T.isNull() || Enum->isFixed()) { 10733 // There is no integral type larger enough to represent this 10734 // value. Complain, then allow the value to wrap around. 10735 EnumVal = LastEnumConst->getInitVal(); 10736 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 10737 ++EnumVal; 10738 if (Enum->isFixed()) 10739 // When the underlying type is fixed, this is ill-formed. 10740 Diag(IdLoc, diag::err_enumerator_wrapped) 10741 << EnumVal.toString(10) 10742 << EltTy; 10743 else 10744 Diag(IdLoc, diag::warn_enumerator_too_large) 10745 << EnumVal.toString(10); 10746 } else { 10747 EltTy = T; 10748 } 10749 10750 // Retrieve the last enumerator's value, extent that type to the 10751 // type that is supposed to be large enough to represent the incremented 10752 // value, then increment. 10753 EnumVal = LastEnumConst->getInitVal(); 10754 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10755 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 10756 ++EnumVal; 10757 10758 // If we're not in C++, diagnose the overflow of enumerator values, 10759 // which in C99 means that the enumerator value is not representable in 10760 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 10761 // permits enumerator values that are representable in some larger 10762 // integral type. 10763 if (!getLangOpts().CPlusPlus && !T.isNull()) 10764 Diag(IdLoc, diag::warn_enum_value_overflow); 10765 } else if (!getLangOpts().CPlusPlus && 10766 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10767 // Enforce C99 6.7.2.2p2 even when we compute the next value. 10768 Diag(IdLoc, diag::ext_enum_value_not_int) 10769 << EnumVal.toString(10) << 1; 10770 } 10771 } 10772 } 10773 10774 if (!EltTy->isDependentType()) { 10775 // Make the enumerator value match the signedness and size of the 10776 // enumerator's type. 10777 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 10778 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10779 } 10780 10781 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 10782 Val, EnumVal); 10783} 10784 10785 10786Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 10787 SourceLocation IdLoc, IdentifierInfo *Id, 10788 AttributeList *Attr, 10789 SourceLocation EqualLoc, Expr *Val) { 10790 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 10791 EnumConstantDecl *LastEnumConst = 10792 cast_or_null<EnumConstantDecl>(lastEnumConst); 10793 10794 // The scope passed in may not be a decl scope. Zip up the scope tree until 10795 // we find one that is. 10796 S = getNonFieldDeclScope(S); 10797 10798 // Verify that there isn't already something declared with this name in this 10799 // scope. 10800 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 10801 ForRedeclaration); 10802 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10803 // Maybe we will complain about the shadowed template parameter. 10804 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 10805 // Just pretend that we didn't see the previous declaration. 10806 PrevDecl = 0; 10807 } 10808 10809 if (PrevDecl) { 10810 // When in C++, we may get a TagDecl with the same name; in this case the 10811 // enum constant will 'hide' the tag. 10812 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 10813 "Received TagDecl when not in C++!"); 10814 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 10815 if (isa<EnumConstantDecl>(PrevDecl)) 10816 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 10817 else 10818 Diag(IdLoc, diag::err_redefinition) << Id; 10819 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10820 return 0; 10821 } 10822 } 10823 10824 // C++ [class.mem]p15: 10825 // If T is the name of a class, then each of the following shall have a name 10826 // different from T: 10827 // - every enumerator of every member of class T that is an unscoped 10828 // enumerated type 10829 if (CXXRecordDecl *Record 10830 = dyn_cast<CXXRecordDecl>( 10831 TheEnumDecl->getDeclContext()->getRedeclContext())) 10832 if (!TheEnumDecl->isScoped() && 10833 Record->getIdentifier() && Record->getIdentifier() == Id) 10834 Diag(IdLoc, diag::err_member_name_of_class) << Id; 10835 10836 EnumConstantDecl *New = 10837 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 10838 10839 if (New) { 10840 // Process attributes. 10841 if (Attr) ProcessDeclAttributeList(S, New, Attr); 10842 10843 // Register this decl in the current scope stack. 10844 New->setAccess(TheEnumDecl->getAccess()); 10845 PushOnScopeChains(New, S); 10846 } 10847 10848 ActOnDocumentableDecl(New); 10849 10850 return New; 10851} 10852 10853// Returns true when the enum initial expression does not trigger the 10854// duplicate enum warning. A few common cases are exempted as follows: 10855// Element2 = Element1 10856// Element2 = Element1 + 1 10857// Element2 = Element1 - 1 10858// Where Element2 and Element1 are from the same enum. 10859static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 10860 Expr *InitExpr = ECD->getInitExpr(); 10861 if (!InitExpr) 10862 return true; 10863 InitExpr = InitExpr->IgnoreImpCasts(); 10864 10865 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 10866 if (!BO->isAdditiveOp()) 10867 return true; 10868 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 10869 if (!IL) 10870 return true; 10871 if (IL->getValue() != 1) 10872 return true; 10873 10874 InitExpr = BO->getLHS(); 10875 } 10876 10877 // This checks if the elements are from the same enum. 10878 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 10879 if (!DRE) 10880 return true; 10881 10882 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 10883 if (!EnumConstant) 10884 return true; 10885 10886 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 10887 Enum) 10888 return true; 10889 10890 return false; 10891} 10892 10893struct DupKey { 10894 int64_t val; 10895 bool isTombstoneOrEmptyKey; 10896 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 10897 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 10898}; 10899 10900static DupKey GetDupKey(const llvm::APSInt& Val) { 10901 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 10902 false); 10903} 10904 10905struct DenseMapInfoDupKey { 10906 static DupKey getEmptyKey() { return DupKey(0, true); } 10907 static DupKey getTombstoneKey() { return DupKey(1, true); } 10908 static unsigned getHashValue(const DupKey Key) { 10909 return (unsigned)(Key.val * 37); 10910 } 10911 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 10912 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 10913 LHS.val == RHS.val; 10914 } 10915}; 10916 10917// Emits a warning when an element is implicitly set a value that 10918// a previous element has already been set to. 10919static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements, 10920 unsigned NumElements, EnumDecl *Enum, 10921 QualType EnumType) { 10922 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 10923 Enum->getLocation()) == 10924 DiagnosticsEngine::Ignored) 10925 return; 10926 // Avoid anonymous enums 10927 if (!Enum->getIdentifier()) 10928 return; 10929 10930 // Only check for small enums. 10931 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 10932 return; 10933 10934 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 10935 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 10936 10937 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 10938 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 10939 ValueToVectorMap; 10940 10941 DuplicatesVector DupVector; 10942 ValueToVectorMap EnumMap; 10943 10944 // Populate the EnumMap with all values represented by enum constants without 10945 // an initialier. 10946 for (unsigned i = 0; i < NumElements; ++i) { 10947 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 10948 10949 // Null EnumConstantDecl means a previous diagnostic has been emitted for 10950 // this constant. Skip this enum since it may be ill-formed. 10951 if (!ECD) { 10952 return; 10953 } 10954 10955 if (ECD->getInitExpr()) 10956 continue; 10957 10958 DupKey Key = GetDupKey(ECD->getInitVal()); 10959 DeclOrVector &Entry = EnumMap[Key]; 10960 10961 // First time encountering this value. 10962 if (Entry.isNull()) 10963 Entry = ECD; 10964 } 10965 10966 // Create vectors for any values that has duplicates. 10967 for (unsigned i = 0; i < NumElements; ++i) { 10968 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 10969 if (!ValidDuplicateEnum(ECD, Enum)) 10970 continue; 10971 10972 DupKey Key = GetDupKey(ECD->getInitVal()); 10973 10974 DeclOrVector& Entry = EnumMap[Key]; 10975 if (Entry.isNull()) 10976 continue; 10977 10978 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 10979 // Ensure constants are different. 10980 if (D == ECD) 10981 continue; 10982 10983 // Create new vector and push values onto it. 10984 ECDVector *Vec = new ECDVector(); 10985 Vec->push_back(D); 10986 Vec->push_back(ECD); 10987 10988 // Update entry to point to the duplicates vector. 10989 Entry = Vec; 10990 10991 // Store the vector somewhere we can consult later for quick emission of 10992 // diagnostics. 10993 DupVector.push_back(Vec); 10994 continue; 10995 } 10996 10997 ECDVector *Vec = Entry.get<ECDVector*>(); 10998 // Make sure constants are not added more than once. 10999 if (*Vec->begin() == ECD) 11000 continue; 11001 11002 Vec->push_back(ECD); 11003 } 11004 11005 // Emit diagnostics. 11006 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 11007 DupVectorEnd = DupVector.end(); 11008 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 11009 ECDVector *Vec = *DupVectorIter; 11010 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 11011 11012 // Emit warning for one enum constant. 11013 ECDVector::iterator I = Vec->begin(); 11014 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 11015 << (*I)->getName() << (*I)->getInitVal().toString(10) 11016 << (*I)->getSourceRange(); 11017 ++I; 11018 11019 // Emit one note for each of the remaining enum constants with 11020 // the same value. 11021 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 11022 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 11023 << (*I)->getName() << (*I)->getInitVal().toString(10) 11024 << (*I)->getSourceRange(); 11025 delete Vec; 11026 } 11027} 11028 11029void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 11030 SourceLocation RBraceLoc, Decl *EnumDeclX, 11031 Decl **Elements, unsigned NumElements, 11032 Scope *S, AttributeList *Attr) { 11033 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 11034 QualType EnumType = Context.getTypeDeclType(Enum); 11035 11036 if (Attr) 11037 ProcessDeclAttributeList(S, Enum, Attr); 11038 11039 if (Enum->isDependentType()) { 11040 for (unsigned i = 0; i != NumElements; ++i) { 11041 EnumConstantDecl *ECD = 11042 cast_or_null<EnumConstantDecl>(Elements[i]); 11043 if (!ECD) continue; 11044 11045 ECD->setType(EnumType); 11046 } 11047 11048 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 11049 return; 11050 } 11051 11052 // TODO: If the result value doesn't fit in an int, it must be a long or long 11053 // long value. ISO C does not support this, but GCC does as an extension, 11054 // emit a warning. 11055 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11056 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 11057 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 11058 11059 // Verify that all the values are okay, compute the size of the values, and 11060 // reverse the list. 11061 unsigned NumNegativeBits = 0; 11062 unsigned NumPositiveBits = 0; 11063 11064 // Keep track of whether all elements have type int. 11065 bool AllElementsInt = true; 11066 11067 for (unsigned i = 0; i != NumElements; ++i) { 11068 EnumConstantDecl *ECD = 11069 cast_or_null<EnumConstantDecl>(Elements[i]); 11070 if (!ECD) continue; // Already issued a diagnostic. 11071 11072 const llvm::APSInt &InitVal = ECD->getInitVal(); 11073 11074 // Keep track of the size of positive and negative values. 11075 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 11076 NumPositiveBits = std::max(NumPositiveBits, 11077 (unsigned)InitVal.getActiveBits()); 11078 else 11079 NumNegativeBits = std::max(NumNegativeBits, 11080 (unsigned)InitVal.getMinSignedBits()); 11081 11082 // Keep track of whether every enum element has type int (very commmon). 11083 if (AllElementsInt) 11084 AllElementsInt = ECD->getType() == Context.IntTy; 11085 } 11086 11087 // Figure out the type that should be used for this enum. 11088 QualType BestType; 11089 unsigned BestWidth; 11090 11091 // C++0x N3000 [conv.prom]p3: 11092 // An rvalue of an unscoped enumeration type whose underlying 11093 // type is not fixed can be converted to an rvalue of the first 11094 // of the following types that can represent all the values of 11095 // the enumeration: int, unsigned int, long int, unsigned long 11096 // int, long long int, or unsigned long long int. 11097 // C99 6.4.4.3p2: 11098 // An identifier declared as an enumeration constant has type int. 11099 // The C99 rule is modified by a gcc extension 11100 QualType BestPromotionType; 11101 11102 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 11103 // -fshort-enums is the equivalent to specifying the packed attribute on all 11104 // enum definitions. 11105 if (LangOpts.ShortEnums) 11106 Packed = true; 11107 11108 if (Enum->isFixed()) { 11109 BestType = Enum->getIntegerType(); 11110 if (BestType->isPromotableIntegerType()) 11111 BestPromotionType = Context.getPromotedIntegerType(BestType); 11112 else 11113 BestPromotionType = BestType; 11114 // We don't need to set BestWidth, because BestType is going to be the type 11115 // of the enumerators, but we do anyway because otherwise some compilers 11116 // warn that it might be used uninitialized. 11117 BestWidth = CharWidth; 11118 } 11119 else if (NumNegativeBits) { 11120 // If there is a negative value, figure out the smallest integer type (of 11121 // int/long/longlong) that fits. 11122 // If it's packed, check also if it fits a char or a short. 11123 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 11124 BestType = Context.SignedCharTy; 11125 BestWidth = CharWidth; 11126 } else if (Packed && NumNegativeBits <= ShortWidth && 11127 NumPositiveBits < ShortWidth) { 11128 BestType = Context.ShortTy; 11129 BestWidth = ShortWidth; 11130 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 11131 BestType = Context.IntTy; 11132 BestWidth = IntWidth; 11133 } else { 11134 BestWidth = Context.getTargetInfo().getLongWidth(); 11135 11136 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 11137 BestType = Context.LongTy; 11138 } else { 11139 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11140 11141 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 11142 Diag(Enum->getLocation(), diag::warn_enum_too_large); 11143 BestType = Context.LongLongTy; 11144 } 11145 } 11146 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 11147 } else { 11148 // If there is no negative value, figure out the smallest type that fits 11149 // all of the enumerator values. 11150 // If it's packed, check also if it fits a char or a short. 11151 if (Packed && NumPositiveBits <= CharWidth) { 11152 BestType = Context.UnsignedCharTy; 11153 BestPromotionType = Context.IntTy; 11154 BestWidth = CharWidth; 11155 } else if (Packed && NumPositiveBits <= ShortWidth) { 11156 BestType = Context.UnsignedShortTy; 11157 BestPromotionType = Context.IntTy; 11158 BestWidth = ShortWidth; 11159 } else if (NumPositiveBits <= IntWidth) { 11160 BestType = Context.UnsignedIntTy; 11161 BestWidth = IntWidth; 11162 BestPromotionType 11163 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11164 ? Context.UnsignedIntTy : Context.IntTy; 11165 } else if (NumPositiveBits <= 11166 (BestWidth = Context.getTargetInfo().getLongWidth())) { 11167 BestType = Context.UnsignedLongTy; 11168 BestPromotionType 11169 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11170 ? Context.UnsignedLongTy : Context.LongTy; 11171 } else { 11172 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11173 assert(NumPositiveBits <= BestWidth && 11174 "How could an initializer get larger than ULL?"); 11175 BestType = Context.UnsignedLongLongTy; 11176 BestPromotionType 11177 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11178 ? Context.UnsignedLongLongTy : Context.LongLongTy; 11179 } 11180 } 11181 11182 // Loop over all of the enumerator constants, changing their types to match 11183 // the type of the enum if needed. 11184 for (unsigned i = 0; i != NumElements; ++i) { 11185 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 11186 if (!ECD) continue; // Already issued a diagnostic. 11187 11188 // Standard C says the enumerators have int type, but we allow, as an 11189 // extension, the enumerators to be larger than int size. If each 11190 // enumerator value fits in an int, type it as an int, otherwise type it the 11191 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 11192 // that X has type 'int', not 'unsigned'. 11193 11194 // Determine whether the value fits into an int. 11195 llvm::APSInt InitVal = ECD->getInitVal(); 11196 11197 // If it fits into an integer type, force it. Otherwise force it to match 11198 // the enum decl type. 11199 QualType NewTy; 11200 unsigned NewWidth; 11201 bool NewSign; 11202 if (!getLangOpts().CPlusPlus && 11203 !Enum->isFixed() && 11204 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 11205 NewTy = Context.IntTy; 11206 NewWidth = IntWidth; 11207 NewSign = true; 11208 } else if (ECD->getType() == BestType) { 11209 // Already the right type! 11210 if (getLangOpts().CPlusPlus) 11211 // C++ [dcl.enum]p4: Following the closing brace of an 11212 // enum-specifier, each enumerator has the type of its 11213 // enumeration. 11214 ECD->setType(EnumType); 11215 continue; 11216 } else { 11217 NewTy = BestType; 11218 NewWidth = BestWidth; 11219 NewSign = BestType->isSignedIntegerOrEnumerationType(); 11220 } 11221 11222 // Adjust the APSInt value. 11223 InitVal = InitVal.extOrTrunc(NewWidth); 11224 InitVal.setIsSigned(NewSign); 11225 ECD->setInitVal(InitVal); 11226 11227 // Adjust the Expr initializer and type. 11228 if (ECD->getInitExpr() && 11229 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 11230 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 11231 CK_IntegralCast, 11232 ECD->getInitExpr(), 11233 /*base paths*/ 0, 11234 VK_RValue)); 11235 if (getLangOpts().CPlusPlus) 11236 // C++ [dcl.enum]p4: Following the closing brace of an 11237 // enum-specifier, each enumerator has the type of its 11238 // enumeration. 11239 ECD->setType(EnumType); 11240 else 11241 ECD->setType(NewTy); 11242 } 11243 11244 Enum->completeDefinition(BestType, BestPromotionType, 11245 NumPositiveBits, NumNegativeBits); 11246 11247 // If we're declaring a function, ensure this decl isn't forgotten about - 11248 // it needs to go into the function scope. 11249 if (InFunctionDeclarator) 11250 DeclsInPrototypeScope.push_back(Enum); 11251 11252 CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType); 11253} 11254 11255Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 11256 SourceLocation StartLoc, 11257 SourceLocation EndLoc) { 11258 StringLiteral *AsmString = cast<StringLiteral>(expr); 11259 11260 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 11261 AsmString, StartLoc, 11262 EndLoc); 11263 CurContext->addDecl(New); 11264 return New; 11265} 11266 11267DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 11268 SourceLocation ImportLoc, 11269 ModuleIdPath Path) { 11270 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 11271 Module::AllVisible, 11272 /*IsIncludeDirective=*/false); 11273 if (!Mod) 11274 return true; 11275 11276 SmallVector<SourceLocation, 2> IdentifierLocs; 11277 Module *ModCheck = Mod; 11278 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 11279 // If we've run out of module parents, just drop the remaining identifiers. 11280 // We need the length to be consistent. 11281 if (!ModCheck) 11282 break; 11283 ModCheck = ModCheck->Parent; 11284 11285 IdentifierLocs.push_back(Path[I].second); 11286 } 11287 11288 ImportDecl *Import = ImportDecl::Create(Context, 11289 Context.getTranslationUnitDecl(), 11290 AtLoc.isValid()? AtLoc : ImportLoc, 11291 Mod, IdentifierLocs); 11292 Context.getTranslationUnitDecl()->addDecl(Import); 11293 return Import; 11294} 11295 11296void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 11297 // Create the implicit import declaration. 11298 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 11299 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 11300 Loc, Mod, Loc); 11301 TU->addDecl(ImportD); 11302 Consumer.HandleImplicitImportDecl(ImportD); 11303 11304 // Make the module visible. 11305 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible); 11306} 11307 11308void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 11309 IdentifierInfo* AliasName, 11310 SourceLocation PragmaLoc, 11311 SourceLocation NameLoc, 11312 SourceLocation AliasNameLoc) { 11313 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 11314 LookupOrdinaryName); 11315 AsmLabelAttr *Attr = 11316 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 11317 11318 if (PrevDecl) 11319 PrevDecl->addAttr(Attr); 11320 else 11321 (void)ExtnameUndeclaredIdentifiers.insert( 11322 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 11323} 11324 11325void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 11326 SourceLocation PragmaLoc, 11327 SourceLocation NameLoc) { 11328 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 11329 11330 if (PrevDecl) { 11331 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 11332 } else { 11333 (void)WeakUndeclaredIdentifiers.insert( 11334 std::pair<IdentifierInfo*,WeakInfo> 11335 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 11336 } 11337} 11338 11339void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 11340 IdentifierInfo* AliasName, 11341 SourceLocation PragmaLoc, 11342 SourceLocation NameLoc, 11343 SourceLocation AliasNameLoc) { 11344 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 11345 LookupOrdinaryName); 11346 WeakInfo W = WeakInfo(Name, NameLoc); 11347 11348 if (PrevDecl) { 11349 if (!PrevDecl->hasAttr<AliasAttr>()) 11350 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 11351 DeclApplyPragmaWeak(TUScope, ND, W); 11352 } else { 11353 (void)WeakUndeclaredIdentifiers.insert( 11354 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 11355 } 11356} 11357 11358Decl *Sema::getObjCDeclContext() const { 11359 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 11360} 11361 11362AvailabilityResult Sema::getCurContextAvailability() const { 11363 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 11364 return D->getAvailability(); 11365} 11366