SemaDecl.cpp revision 96db329b3a982ac83c700c4469a3f618dc53cb42
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 1177// We need this to handle 1178// 1179// typedef struct { 1180// void *foo() { return 0; } 1181// } A; 1182// 1183// When we see foo we don't know if after the typedef we will get 'A' or '*A' 1184// for example. If 'A', foo will have external linkage. If we have '*A', 1185// foo will have no linkage. Since we can't know untill we get to the end 1186// of the typedef, this function finds out if D might have non external linkage. 1187// Callers should verify at the end of the TU if it D has external linkage or 1188// not. 1189bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1190 const DeclContext *DC = D->getDeclContext(); 1191 while (!DC->isTranslationUnit()) { 1192 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1193 if (!RD->hasNameForLinkage()) 1194 return true; 1195 } 1196 DC = DC->getParent(); 1197 } 1198 1199 return !D->hasExternalLinkage(); 1200} 1201 1202bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1203 assert(D); 1204 1205 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1206 return false; 1207 1208 // Ignore class templates. 1209 if (D->getDeclContext()->isDependentContext() || 1210 D->getLexicalDeclContext()->isDependentContext()) 1211 return false; 1212 1213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1214 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1215 return false; 1216 1217 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1218 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1219 return false; 1220 } else { 1221 // 'static inline' functions are used in headers; don't warn. 1222 if (FD->getStorageClass() == SC_Static && 1223 FD->isInlineSpecified()) 1224 return false; 1225 } 1226 1227 if (FD->doesThisDeclarationHaveABody() && 1228 Context.DeclMustBeEmitted(FD)) 1229 return false; 1230 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1231 // Don't warn on variables of const-qualified or reference type, since their 1232 // values can be used even if though they're not odr-used, and because const 1233 // qualified variables can appear in headers in contexts where they're not 1234 // intended to be used. 1235 // FIXME: Use more principled rules for these exemptions. 1236 if (!VD->isFileVarDecl() || 1237 VD->getType().isConstQualified() || 1238 VD->getType()->isReferenceType() || 1239 Context.DeclMustBeEmitted(VD)) 1240 return false; 1241 1242 if (VD->isStaticDataMember() && 1243 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1244 return false; 1245 1246 } else { 1247 return false; 1248 } 1249 1250 // Only warn for unused decls internal to the translation unit. 1251 return mightHaveNonExternalLinkage(D); 1252} 1253 1254void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1255 if (!D) 1256 return; 1257 1258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1259 const FunctionDecl *First = FD->getFirstDeclaration(); 1260 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1261 return; // First should already be in the vector. 1262 } 1263 1264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1265 const VarDecl *First = VD->getFirstDeclaration(); 1266 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1267 return; // First should already be in the vector. 1268 } 1269 1270 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1271 UnusedFileScopedDecls.push_back(D); 1272} 1273 1274static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1275 if (D->isInvalidDecl()) 1276 return false; 1277 1278 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1279 return false; 1280 1281 if (isa<LabelDecl>(D)) 1282 return true; 1283 1284 // White-list anything that isn't a local variable. 1285 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1286 !D->getDeclContext()->isFunctionOrMethod()) 1287 return false; 1288 1289 // Types of valid local variables should be complete, so this should succeed. 1290 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1291 1292 // White-list anything with an __attribute__((unused)) type. 1293 QualType Ty = VD->getType(); 1294 1295 // Only look at the outermost level of typedef. 1296 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1297 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1298 return false; 1299 } 1300 1301 // If we failed to complete the type for some reason, or if the type is 1302 // dependent, don't diagnose the variable. 1303 if (Ty->isIncompleteType() || Ty->isDependentType()) 1304 return false; 1305 1306 if (const TagType *TT = Ty->getAs<TagType>()) { 1307 const TagDecl *Tag = TT->getDecl(); 1308 if (Tag->hasAttr<UnusedAttr>()) 1309 return false; 1310 1311 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1312 if (!RD->hasTrivialDestructor()) 1313 return false; 1314 1315 if (const Expr *Init = VD->getInit()) { 1316 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1317 Init = Cleanups->getSubExpr(); 1318 const CXXConstructExpr *Construct = 1319 dyn_cast<CXXConstructExpr>(Init); 1320 if (Construct && !Construct->isElidable()) { 1321 CXXConstructorDecl *CD = Construct->getConstructor(); 1322 if (!CD->isTrivial()) 1323 return false; 1324 } 1325 } 1326 } 1327 } 1328 1329 // TODO: __attribute__((unused)) templates? 1330 } 1331 1332 return true; 1333} 1334 1335static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1336 FixItHint &Hint) { 1337 if (isa<LabelDecl>(D)) { 1338 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1339 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1340 if (AfterColon.isInvalid()) 1341 return; 1342 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1343 getCharRange(D->getLocStart(), AfterColon)); 1344 } 1345 return; 1346} 1347 1348/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1349/// unless they are marked attr(unused). 1350void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1351 FixItHint Hint; 1352 if (!ShouldDiagnoseUnusedDecl(D)) 1353 return; 1354 1355 GenerateFixForUnusedDecl(D, Context, Hint); 1356 1357 unsigned DiagID; 1358 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1359 DiagID = diag::warn_unused_exception_param; 1360 else if (isa<LabelDecl>(D)) 1361 DiagID = diag::warn_unused_label; 1362 else 1363 DiagID = diag::warn_unused_variable; 1364 1365 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1366} 1367 1368static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1369 // Verify that we have no forward references left. If so, there was a goto 1370 // or address of a label taken, but no definition of it. Label fwd 1371 // definitions are indicated with a null substmt. 1372 if (L->getStmt() == 0) 1373 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1374} 1375 1376void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1377 if (S->decl_empty()) return; 1378 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1379 "Scope shouldn't contain decls!"); 1380 1381 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 1382 I != E; ++I) { 1383 Decl *TmpD = (*I); 1384 assert(TmpD && "This decl didn't get pushed??"); 1385 1386 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1387 NamedDecl *D = cast<NamedDecl>(TmpD); 1388 1389 if (!D->getDeclName()) continue; 1390 1391 // Diagnose unused variables in this scope. 1392 if (!S->hasErrorOccurred()) 1393 DiagnoseUnusedDecl(D); 1394 1395 // If this was a forward reference to a label, verify it was defined. 1396 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1397 CheckPoppedLabel(LD, *this); 1398 1399 // Remove this name from our lexical scope. 1400 IdResolver.RemoveDecl(D); 1401 } 1402} 1403 1404void Sema::ActOnStartFunctionDeclarator() { 1405 ++InFunctionDeclarator; 1406} 1407 1408void Sema::ActOnEndFunctionDeclarator() { 1409 assert(InFunctionDeclarator); 1410 --InFunctionDeclarator; 1411} 1412 1413/// \brief Look for an Objective-C class in the translation unit. 1414/// 1415/// \param Id The name of the Objective-C class we're looking for. If 1416/// typo-correction fixes this name, the Id will be updated 1417/// to the fixed name. 1418/// 1419/// \param IdLoc The location of the name in the translation unit. 1420/// 1421/// \param DoTypoCorrection If true, this routine will attempt typo correction 1422/// if there is no class with the given name. 1423/// 1424/// \returns The declaration of the named Objective-C class, or NULL if the 1425/// class could not be found. 1426ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1427 SourceLocation IdLoc, 1428 bool DoTypoCorrection) { 1429 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1430 // creation from this context. 1431 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1432 1433 if (!IDecl && DoTypoCorrection) { 1434 // Perform typo correction at the given location, but only if we 1435 // find an Objective-C class name. 1436 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1437 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1438 LookupOrdinaryName, TUScope, NULL, 1439 Validator)) { 1440 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1441 Diag(IdLoc, diag::err_undef_interface_suggest) 1442 << Id << IDecl->getDeclName() 1443 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 1444 Diag(IDecl->getLocation(), diag::note_previous_decl) 1445 << IDecl->getDeclName(); 1446 1447 Id = IDecl->getIdentifier(); 1448 } 1449 } 1450 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1451 // This routine must always return a class definition, if any. 1452 if (Def && Def->getDefinition()) 1453 Def = Def->getDefinition(); 1454 return Def; 1455} 1456 1457/// getNonFieldDeclScope - Retrieves the innermost scope, starting 1458/// from S, where a non-field would be declared. This routine copes 1459/// with the difference between C and C++ scoping rules in structs and 1460/// unions. For example, the following code is well-formed in C but 1461/// ill-formed in C++: 1462/// @code 1463/// struct S6 { 1464/// enum { BAR } e; 1465/// }; 1466/// 1467/// void test_S6() { 1468/// struct S6 a; 1469/// a.e = BAR; 1470/// } 1471/// @endcode 1472/// For the declaration of BAR, this routine will return a different 1473/// scope. The scope S will be the scope of the unnamed enumeration 1474/// within S6. In C++, this routine will return the scope associated 1475/// with S6, because the enumeration's scope is a transparent 1476/// context but structures can contain non-field names. In C, this 1477/// routine will return the translation unit scope, since the 1478/// enumeration's scope is a transparent context and structures cannot 1479/// contain non-field names. 1480Scope *Sema::getNonFieldDeclScope(Scope *S) { 1481 while (((S->getFlags() & Scope::DeclScope) == 0) || 1482 (S->getEntity() && 1483 ((DeclContext *)S->getEntity())->isTransparentContext()) || 1484 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1485 S = S->getParent(); 1486 return S; 1487} 1488 1489/// \brief Looks up the declaration of "struct objc_super" and 1490/// saves it for later use in building builtin declaration of 1491/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1492/// pre-existing declaration exists no action takes place. 1493static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1494 IdentifierInfo *II) { 1495 if (!II->isStr("objc_msgSendSuper")) 1496 return; 1497 ASTContext &Context = ThisSema.Context; 1498 1499 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1500 SourceLocation(), Sema::LookupTagName); 1501 ThisSema.LookupName(Result, S); 1502 if (Result.getResultKind() == LookupResult::Found) 1503 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1504 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1505} 1506 1507/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1508/// file scope. lazily create a decl for it. ForRedeclaration is true 1509/// if we're creating this built-in in anticipation of redeclaring the 1510/// built-in. 1511NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1512 Scope *S, bool ForRedeclaration, 1513 SourceLocation Loc) { 1514 LookupPredefedObjCSuperType(*this, S, II); 1515 1516 Builtin::ID BID = (Builtin::ID)bid; 1517 1518 ASTContext::GetBuiltinTypeError Error; 1519 QualType R = Context.GetBuiltinType(BID, Error); 1520 switch (Error) { 1521 case ASTContext::GE_None: 1522 // Okay 1523 break; 1524 1525 case ASTContext::GE_Missing_stdio: 1526 if (ForRedeclaration) 1527 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1528 << Context.BuiltinInfo.GetName(BID); 1529 return 0; 1530 1531 case ASTContext::GE_Missing_setjmp: 1532 if (ForRedeclaration) 1533 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1534 << Context.BuiltinInfo.GetName(BID); 1535 return 0; 1536 1537 case ASTContext::GE_Missing_ucontext: 1538 if (ForRedeclaration) 1539 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1540 << Context.BuiltinInfo.GetName(BID); 1541 return 0; 1542 } 1543 1544 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1545 Diag(Loc, diag::ext_implicit_lib_function_decl) 1546 << Context.BuiltinInfo.GetName(BID) 1547 << R; 1548 if (Context.BuiltinInfo.getHeaderName(BID) && 1549 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1550 != DiagnosticsEngine::Ignored) 1551 Diag(Loc, diag::note_please_include_header) 1552 << Context.BuiltinInfo.getHeaderName(BID) 1553 << Context.BuiltinInfo.GetName(BID); 1554 } 1555 1556 FunctionDecl *New = FunctionDecl::Create(Context, 1557 Context.getTranslationUnitDecl(), 1558 Loc, Loc, II, R, /*TInfo=*/0, 1559 SC_Extern, 1560 SC_None, false, 1561 /*hasPrototype=*/true); 1562 New->setImplicit(); 1563 1564 // Create Decl objects for each parameter, adding them to the 1565 // FunctionDecl. 1566 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1567 SmallVector<ParmVarDecl*, 16> Params; 1568 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 1569 ParmVarDecl *parm = 1570 ParmVarDecl::Create(Context, New, SourceLocation(), 1571 SourceLocation(), 0, 1572 FT->getArgType(i), /*TInfo=*/0, 1573 SC_None, SC_None, 0); 1574 parm->setScopeInfo(0, i); 1575 Params.push_back(parm); 1576 } 1577 New->setParams(Params); 1578 } 1579 1580 AddKnownFunctionAttributes(New); 1581 1582 // TUScope is the translation-unit scope to insert this function into. 1583 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1584 // relate Scopes to DeclContexts, and probably eliminate CurContext 1585 // entirely, but we're not there yet. 1586 DeclContext *SavedContext = CurContext; 1587 CurContext = Context.getTranslationUnitDecl(); 1588 PushOnScopeChains(New, TUScope); 1589 CurContext = SavedContext; 1590 return New; 1591} 1592 1593/// \brief Filter out any previous declarations that the given declaration 1594/// should not consider because they are not permitted to conflict, e.g., 1595/// because they come from hidden sub-modules and do not refer to the same 1596/// entity. 1597static void filterNonConflictingPreviousDecls(ASTContext &context, 1598 NamedDecl *decl, 1599 LookupResult &previous){ 1600 // This is only interesting when modules are enabled. 1601 if (!context.getLangOpts().Modules) 1602 return; 1603 1604 // Empty sets are uninteresting. 1605 if (previous.empty()) 1606 return; 1607 1608 // If this declaration has external 1609 bool hasExternalLinkage = decl->hasExternalLinkage(); 1610 1611 LookupResult::Filter filter = previous.makeFilter(); 1612 while (filter.hasNext()) { 1613 NamedDecl *old = filter.next(); 1614 1615 // Non-hidden declarations are never ignored. 1616 if (!old->isHidden()) 1617 continue; 1618 1619 // If either has no-external linkage, ignore the old declaration. 1620 if (!hasExternalLinkage || old->getLinkage() != ExternalLinkage) 1621 filter.erase(); 1622 } 1623 1624 filter.done(); 1625} 1626 1627bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1628 QualType OldType; 1629 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1630 OldType = OldTypedef->getUnderlyingType(); 1631 else 1632 OldType = Context.getTypeDeclType(Old); 1633 QualType NewType = New->getUnderlyingType(); 1634 1635 if (NewType->isVariablyModifiedType()) { 1636 // Must not redefine a typedef with a variably-modified type. 1637 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1638 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1639 << Kind << NewType; 1640 if (Old->getLocation().isValid()) 1641 Diag(Old->getLocation(), diag::note_previous_definition); 1642 New->setInvalidDecl(); 1643 return true; 1644 } 1645 1646 if (OldType != NewType && 1647 !OldType->isDependentType() && 1648 !NewType->isDependentType() && 1649 !Context.hasSameType(OldType, NewType)) { 1650 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1651 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1652 << Kind << NewType << OldType; 1653 if (Old->getLocation().isValid()) 1654 Diag(Old->getLocation(), diag::note_previous_definition); 1655 New->setInvalidDecl(); 1656 return true; 1657 } 1658 return false; 1659} 1660 1661/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1662/// same name and scope as a previous declaration 'Old'. Figure out 1663/// how to resolve this situation, merging decls or emitting 1664/// diagnostics as appropriate. If there was an error, set New to be invalid. 1665/// 1666void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1667 // If the new decl is known invalid already, don't bother doing any 1668 // merging checks. 1669 if (New->isInvalidDecl()) return; 1670 1671 // Allow multiple definitions for ObjC built-in typedefs. 1672 // FIXME: Verify the underlying types are equivalent! 1673 if (getLangOpts().ObjC1) { 1674 const IdentifierInfo *TypeID = New->getIdentifier(); 1675 switch (TypeID->getLength()) { 1676 default: break; 1677 case 2: 1678 { 1679 if (!TypeID->isStr("id")) 1680 break; 1681 QualType T = New->getUnderlyingType(); 1682 if (!T->isPointerType()) 1683 break; 1684 if (!T->isVoidPointerType()) { 1685 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1686 if (!PT->isStructureType()) 1687 break; 1688 } 1689 Context.setObjCIdRedefinitionType(T); 1690 // Install the built-in type for 'id', ignoring the current definition. 1691 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1692 return; 1693 } 1694 case 5: 1695 if (!TypeID->isStr("Class")) 1696 break; 1697 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1698 // Install the built-in type for 'Class', ignoring the current definition. 1699 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1700 return; 1701 case 3: 1702 if (!TypeID->isStr("SEL")) 1703 break; 1704 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1705 // Install the built-in type for 'SEL', ignoring the current definition. 1706 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1707 return; 1708 } 1709 // Fall through - the typedef name was not a builtin type. 1710 } 1711 1712 // Verify the old decl was also a type. 1713 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1714 if (!Old) { 1715 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1716 << New->getDeclName(); 1717 1718 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1719 if (OldD->getLocation().isValid()) 1720 Diag(OldD->getLocation(), diag::note_previous_definition); 1721 1722 return New->setInvalidDecl(); 1723 } 1724 1725 // If the old declaration is invalid, just give up here. 1726 if (Old->isInvalidDecl()) 1727 return New->setInvalidDecl(); 1728 1729 // If the typedef types are not identical, reject them in all languages and 1730 // with any extensions enabled. 1731 if (isIncompatibleTypedef(Old, New)) 1732 return; 1733 1734 // The types match. Link up the redeclaration chain if the old 1735 // declaration was a typedef. 1736 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 1737 New->setPreviousDeclaration(Typedef); 1738 1739 if (getLangOpts().MicrosoftExt) 1740 return; 1741 1742 if (getLangOpts().CPlusPlus) { 1743 // C++ [dcl.typedef]p2: 1744 // In a given non-class scope, a typedef specifier can be used to 1745 // redefine the name of any type declared in that scope to refer 1746 // to the type to which it already refers. 1747 if (!isa<CXXRecordDecl>(CurContext)) 1748 return; 1749 1750 // C++0x [dcl.typedef]p4: 1751 // In a given class scope, a typedef specifier can be used to redefine 1752 // any class-name declared in that scope that is not also a typedef-name 1753 // to refer to the type to which it already refers. 1754 // 1755 // This wording came in via DR424, which was a correction to the 1756 // wording in DR56, which accidentally banned code like: 1757 // 1758 // struct S { 1759 // typedef struct A { } A; 1760 // }; 1761 // 1762 // in the C++03 standard. We implement the C++0x semantics, which 1763 // allow the above but disallow 1764 // 1765 // struct S { 1766 // typedef int I; 1767 // typedef int I; 1768 // }; 1769 // 1770 // since that was the intent of DR56. 1771 if (!isa<TypedefNameDecl>(Old)) 1772 return; 1773 1774 Diag(New->getLocation(), diag::err_redefinition) 1775 << New->getDeclName(); 1776 Diag(Old->getLocation(), diag::note_previous_definition); 1777 return New->setInvalidDecl(); 1778 } 1779 1780 // Modules always permit redefinition of typedefs, as does C11. 1781 if (getLangOpts().Modules || getLangOpts().C11) 1782 return; 1783 1784 // If we have a redefinition of a typedef in C, emit a warning. This warning 1785 // is normally mapped to an error, but can be controlled with 1786 // -Wtypedef-redefinition. If either the original or the redefinition is 1787 // in a system header, don't emit this for compatibility with GCC. 1788 if (getDiagnostics().getSuppressSystemWarnings() && 1789 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1790 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1791 return; 1792 1793 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1794 << New->getDeclName(); 1795 Diag(Old->getLocation(), diag::note_previous_definition); 1796 return; 1797} 1798 1799/// DeclhasAttr - returns true if decl Declaration already has the target 1800/// attribute. 1801static bool 1802DeclHasAttr(const Decl *D, const Attr *A) { 1803 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 1804 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 1805 // responsible for making sure they are consistent. 1806 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 1807 if (AA) 1808 return false; 1809 1810 // The following thread safety attributes can also be duplicated. 1811 switch (A->getKind()) { 1812 case attr::ExclusiveLocksRequired: 1813 case attr::SharedLocksRequired: 1814 case attr::LocksExcluded: 1815 case attr::ExclusiveLockFunction: 1816 case attr::SharedLockFunction: 1817 case attr::UnlockFunction: 1818 case attr::ExclusiveTrylockFunction: 1819 case attr::SharedTrylockFunction: 1820 case attr::GuardedBy: 1821 case attr::PtGuardedBy: 1822 case attr::AcquiredBefore: 1823 case attr::AcquiredAfter: 1824 return false; 1825 default: 1826 ; 1827 } 1828 1829 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1830 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1831 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 1832 if ((*i)->getKind() == A->getKind()) { 1833 if (Ann) { 1834 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 1835 return true; 1836 continue; 1837 } 1838 // FIXME: Don't hardcode this check 1839 if (OA && isa<OwnershipAttr>(*i)) 1840 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 1841 return true; 1842 } 1843 1844 return false; 1845} 1846 1847static bool isAttributeTargetADefinition(Decl *D) { 1848 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1849 return VD->isThisDeclarationADefinition(); 1850 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1851 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1852 return true; 1853} 1854 1855/// Merge alignment attributes from \p Old to \p New, taking into account the 1856/// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1857/// 1858/// \return \c true if any attributes were added to \p New. 1859static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1860 // Look for alignas attributes on Old, and pick out whichever attribute 1861 // specifies the strictest alignment requirement. 1862 AlignedAttr *OldAlignasAttr = 0; 1863 AlignedAttr *OldStrictestAlignAttr = 0; 1864 unsigned OldAlign = 0; 1865 for (specific_attr_iterator<AlignedAttr> 1866 I = Old->specific_attr_begin<AlignedAttr>(), 1867 E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1868 // FIXME: We have no way of representing inherited dependent alignments 1869 // in a case like: 1870 // template<int A, int B> struct alignas(A) X; 1871 // template<int A, int B> struct alignas(B) X {}; 1872 // For now, we just ignore any alignas attributes which are not on the 1873 // definition in such a case. 1874 if (I->isAlignmentDependent()) 1875 return false; 1876 1877 if (I->isAlignas()) 1878 OldAlignasAttr = *I; 1879 1880 unsigned Align = I->getAlignment(S.Context); 1881 if (Align > OldAlign) { 1882 OldAlign = Align; 1883 OldStrictestAlignAttr = *I; 1884 } 1885 } 1886 1887 // Look for alignas attributes on New. 1888 AlignedAttr *NewAlignasAttr = 0; 1889 unsigned NewAlign = 0; 1890 for (specific_attr_iterator<AlignedAttr> 1891 I = New->specific_attr_begin<AlignedAttr>(), 1892 E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) { 1893 if (I->isAlignmentDependent()) 1894 return false; 1895 1896 if (I->isAlignas()) 1897 NewAlignasAttr = *I; 1898 1899 unsigned Align = I->getAlignment(S.Context); 1900 if (Align > NewAlign) 1901 NewAlign = Align; 1902 } 1903 1904 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1905 // Both declarations have 'alignas' attributes. We require them to match. 1906 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1907 // fall short. (If two declarations both have alignas, they must both match 1908 // every definition, and so must match each other if there is a definition.) 1909 1910 // If either declaration only contains 'alignas(0)' specifiers, then it 1911 // specifies the natural alignment for the type. 1912 if (OldAlign == 0 || NewAlign == 0) { 1913 QualType Ty; 1914 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1915 Ty = VD->getType(); 1916 else 1917 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1918 1919 if (OldAlign == 0) 1920 OldAlign = S.Context.getTypeAlign(Ty); 1921 if (NewAlign == 0) 1922 NewAlign = S.Context.getTypeAlign(Ty); 1923 } 1924 1925 if (OldAlign != NewAlign) { 1926 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1927 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1928 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1929 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1930 } 1931 } 1932 1933 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1934 // C++11 [dcl.align]p6: 1935 // if any declaration of an entity has an alignment-specifier, 1936 // every defining declaration of that entity shall specify an 1937 // equivalent alignment. 1938 // C11 6.7.5/7: 1939 // If the definition of an object does not have an alignment 1940 // specifier, any other declaration of that object shall also 1941 // have no alignment specifier. 1942 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1943 << OldAlignasAttr->isC11(); 1944 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1945 << OldAlignasAttr->isC11(); 1946 } 1947 1948 bool AnyAdded = false; 1949 1950 // Ensure we have an attribute representing the strictest alignment. 1951 if (OldAlign > NewAlign) { 1952 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1953 Clone->setInherited(true); 1954 New->addAttr(Clone); 1955 AnyAdded = true; 1956 } 1957 1958 // Ensure we have an alignas attribute if the old declaration had one. 1959 if (OldAlignasAttr && !NewAlignasAttr && 1960 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1961 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1962 Clone->setInherited(true); 1963 New->addAttr(Clone); 1964 AnyAdded = true; 1965 } 1966 1967 return AnyAdded; 1968} 1969 1970static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr, 1971 bool Override) { 1972 InheritableAttr *NewAttr = NULL; 1973 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1974 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 1975 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1976 AA->getIntroduced(), AA->getDeprecated(), 1977 AA->getObsoleted(), AA->getUnavailable(), 1978 AA->getMessage(), Override, 1979 AttrSpellingListIndex); 1980 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 1981 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1982 AttrSpellingListIndex); 1983 else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1984 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1985 AttrSpellingListIndex); 1986 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1987 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1988 AttrSpellingListIndex); 1989 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1990 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1991 AttrSpellingListIndex); 1992 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 1993 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1994 FA->getFormatIdx(), FA->getFirstArg(), 1995 AttrSpellingListIndex); 1996 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 1997 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1998 AttrSpellingListIndex); 1999 else if (isa<AlignedAttr>(Attr)) 2000 // AlignedAttrs are handled separately, because we need to handle all 2001 // such attributes on a declaration at the same time. 2002 NewAttr = 0; 2003 else if (!DeclHasAttr(D, Attr)) 2004 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2005 2006 if (NewAttr) { 2007 NewAttr->setInherited(true); 2008 D->addAttr(NewAttr); 2009 return true; 2010 } 2011 2012 return false; 2013} 2014 2015static const Decl *getDefinition(const Decl *D) { 2016 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2017 return TD->getDefinition(); 2018 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 2019 return VD->getDefinition(); 2020 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2021 const FunctionDecl* Def; 2022 if (FD->hasBody(Def)) 2023 return Def; 2024 } 2025 return NULL; 2026} 2027 2028static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2029 for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end(); 2030 I != E; ++I) { 2031 Attr *Attribute = *I; 2032 if (Attribute->getKind() == Kind) 2033 return true; 2034 } 2035 return false; 2036} 2037 2038/// checkNewAttributesAfterDef - If we already have a definition, check that 2039/// there are no new attributes in this declaration. 2040static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2041 if (!New->hasAttrs()) 2042 return; 2043 2044 const Decl *Def = getDefinition(Old); 2045 if (!Def || Def == New) 2046 return; 2047 2048 AttrVec &NewAttributes = New->getAttrs(); 2049 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2050 const Attr *NewAttribute = NewAttributes[I]; 2051 if (hasAttribute(Def, NewAttribute->getKind())) { 2052 ++I; 2053 continue; // regular attr merging will take care of validating this. 2054 } 2055 2056 if (isa<C11NoReturnAttr>(NewAttribute)) { 2057 // C's _Noreturn is allowed to be added to a function after it is defined. 2058 ++I; 2059 continue; 2060 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2061 if (AA->isAlignas()) { 2062 // C++11 [dcl.align]p6: 2063 // if any declaration of an entity has an alignment-specifier, 2064 // every defining declaration of that entity shall specify an 2065 // equivalent alignment. 2066 // C11 6.7.5/7: 2067 // If the definition of an object does not have an alignment 2068 // specifier, any other declaration of that object shall also 2069 // have no alignment specifier. 2070 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2071 << AA->isC11(); 2072 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2073 << AA->isC11(); 2074 NewAttributes.erase(NewAttributes.begin() + I); 2075 --E; 2076 continue; 2077 } 2078 } 2079 2080 S.Diag(NewAttribute->getLocation(), 2081 diag::warn_attribute_precede_definition); 2082 S.Diag(Def->getLocation(), diag::note_previous_definition); 2083 NewAttributes.erase(NewAttributes.begin() + I); 2084 --E; 2085 } 2086} 2087 2088/// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2089void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2090 AvailabilityMergeKind AMK) { 2091 if (!Old->hasAttrs() && !New->hasAttrs()) 2092 return; 2093 2094 // attributes declared post-definition are currently ignored 2095 checkNewAttributesAfterDef(*this, New, Old); 2096 2097 if (!Old->hasAttrs()) 2098 return; 2099 2100 bool foundAny = New->hasAttrs(); 2101 2102 // Ensure that any moving of objects within the allocated map is done before 2103 // we process them. 2104 if (!foundAny) New->setAttrs(AttrVec()); 2105 2106 for (specific_attr_iterator<InheritableAttr> 2107 i = Old->specific_attr_begin<InheritableAttr>(), 2108 e = Old->specific_attr_end<InheritableAttr>(); 2109 i != e; ++i) { 2110 bool Override = false; 2111 // Ignore deprecated/unavailable/availability attributes if requested. 2112 if (isa<DeprecatedAttr>(*i) || 2113 isa<UnavailableAttr>(*i) || 2114 isa<AvailabilityAttr>(*i)) { 2115 switch (AMK) { 2116 case AMK_None: 2117 continue; 2118 2119 case AMK_Redeclaration: 2120 break; 2121 2122 case AMK_Override: 2123 Override = true; 2124 break; 2125 } 2126 } 2127 2128 if (mergeDeclAttribute(*this, New, *i, Override)) 2129 foundAny = true; 2130 } 2131 2132 if (mergeAlignedAttrs(*this, New, Old)) 2133 foundAny = true; 2134 2135 if (!foundAny) New->dropAttrs(); 2136} 2137 2138/// mergeParamDeclAttributes - Copy attributes from the old parameter 2139/// to the new one. 2140static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2141 const ParmVarDecl *oldDecl, 2142 Sema &S) { 2143 // C++11 [dcl.attr.depend]p2: 2144 // The first declaration of a function shall specify the 2145 // carries_dependency attribute for its declarator-id if any declaration 2146 // of the function specifies the carries_dependency attribute. 2147 if (newDecl->hasAttr<CarriesDependencyAttr>() && 2148 !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2149 S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(), 2150 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2151 // Find the first declaration of the parameter. 2152 // FIXME: Should we build redeclaration chains for function parameters? 2153 const FunctionDecl *FirstFD = 2154 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDeclaration(); 2155 const ParmVarDecl *FirstVD = 2156 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2157 S.Diag(FirstVD->getLocation(), 2158 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2159 } 2160 2161 if (!oldDecl->hasAttrs()) 2162 return; 2163 2164 bool foundAny = newDecl->hasAttrs(); 2165 2166 // Ensure that any moving of objects within the allocated map is 2167 // done before we process them. 2168 if (!foundAny) newDecl->setAttrs(AttrVec()); 2169 2170 for (specific_attr_iterator<InheritableParamAttr> 2171 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 2172 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 2173 if (!DeclHasAttr(newDecl, *i)) { 2174 InheritableAttr *newAttr = 2175 cast<InheritableParamAttr>((*i)->clone(S.Context)); 2176 newAttr->setInherited(true); 2177 newDecl->addAttr(newAttr); 2178 foundAny = true; 2179 } 2180 } 2181 2182 if (!foundAny) newDecl->dropAttrs(); 2183} 2184 2185namespace { 2186 2187/// Used in MergeFunctionDecl to keep track of function parameters in 2188/// C. 2189struct GNUCompatibleParamWarning { 2190 ParmVarDecl *OldParm; 2191 ParmVarDecl *NewParm; 2192 QualType PromotedType; 2193}; 2194 2195} 2196 2197/// getSpecialMember - get the special member enum for a method. 2198Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2199 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2200 if (Ctor->isDefaultConstructor()) 2201 return Sema::CXXDefaultConstructor; 2202 2203 if (Ctor->isCopyConstructor()) 2204 return Sema::CXXCopyConstructor; 2205 2206 if (Ctor->isMoveConstructor()) 2207 return Sema::CXXMoveConstructor; 2208 } else if (isa<CXXDestructorDecl>(MD)) { 2209 return Sema::CXXDestructor; 2210 } else if (MD->isCopyAssignmentOperator()) { 2211 return Sema::CXXCopyAssignment; 2212 } else if (MD->isMoveAssignmentOperator()) { 2213 return Sema::CXXMoveAssignment; 2214 } 2215 2216 return Sema::CXXInvalid; 2217} 2218 2219/// canRedefineFunction - checks if a function can be redefined. Currently, 2220/// only extern inline functions can be redefined, and even then only in 2221/// GNU89 mode. 2222static bool canRedefineFunction(const FunctionDecl *FD, 2223 const LangOptions& LangOpts) { 2224 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2225 !LangOpts.CPlusPlus && 2226 FD->isInlineSpecified() && 2227 FD->getStorageClass() == SC_Extern); 2228} 2229 2230/// Is the given calling convention the ABI default for the given 2231/// declaration? 2232static bool isABIDefaultCC(Sema &S, CallingConv CC, FunctionDecl *D) { 2233 CallingConv ABIDefaultCC; 2234 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 2235 ABIDefaultCC = S.Context.getDefaultCXXMethodCallConv(D->isVariadic()); 2236 } else { 2237 // Free C function or a static method. 2238 ABIDefaultCC = (S.Context.getLangOpts().MRTD ? CC_X86StdCall : CC_C); 2239 } 2240 return ABIDefaultCC == CC; 2241} 2242 2243template <typename T> 2244static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2245 const DeclContext *DC = Old->getDeclContext(); 2246 if (DC->isRecord()) 2247 return false; 2248 2249 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2250 if (OldLinkage == CXXLanguageLinkage && 2251 New->getDeclContext()->isExternCContext()) 2252 return true; 2253 if (OldLinkage == CLanguageLinkage && 2254 New->getDeclContext()->isExternCXXContext()) 2255 return true; 2256 return false; 2257} 2258 2259/// MergeFunctionDecl - We just parsed a function 'New' from 2260/// declarator D which has the same name and scope as a previous 2261/// declaration 'Old'. Figure out how to resolve this situation, 2262/// merging decls or emitting diagnostics as appropriate. 2263/// 2264/// In C++, New and Old must be declarations that are not 2265/// overloaded. Use IsOverload to determine whether New and Old are 2266/// overloaded, and to select the Old declaration that New should be 2267/// merged with. 2268/// 2269/// Returns true if there was an error, false otherwise. 2270bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 2271 // Verify the old decl was also a function. 2272 FunctionDecl *Old = 0; 2273 if (FunctionTemplateDecl *OldFunctionTemplate 2274 = dyn_cast<FunctionTemplateDecl>(OldD)) 2275 Old = OldFunctionTemplate->getTemplatedDecl(); 2276 else 2277 Old = dyn_cast<FunctionDecl>(OldD); 2278 if (!Old) { 2279 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2280 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2281 Diag(Shadow->getTargetDecl()->getLocation(), 2282 diag::note_using_decl_target); 2283 Diag(Shadow->getUsingDecl()->getLocation(), 2284 diag::note_using_decl) << 0; 2285 return true; 2286 } 2287 2288 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2289 << New->getDeclName(); 2290 Diag(OldD->getLocation(), diag::note_previous_definition); 2291 return true; 2292 } 2293 2294 // Determine whether the previous declaration was a definition, 2295 // implicit declaration, or a declaration. 2296 diag::kind PrevDiag; 2297 if (Old->isThisDeclarationADefinition()) 2298 PrevDiag = diag::note_previous_definition; 2299 else if (Old->isImplicit()) 2300 PrevDiag = diag::note_previous_implicit_declaration; 2301 else 2302 PrevDiag = diag::note_previous_declaration; 2303 2304 QualType OldQType = Context.getCanonicalType(Old->getType()); 2305 QualType NewQType = Context.getCanonicalType(New->getType()); 2306 2307 // Don't complain about this if we're in GNU89 mode and the old function 2308 // is an extern inline function. 2309 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2310 New->getStorageClass() == SC_Static && 2311 Old->getStorageClass() != SC_Static && 2312 !canRedefineFunction(Old, getLangOpts())) { 2313 if (getLangOpts().MicrosoftExt) { 2314 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2315 Diag(Old->getLocation(), PrevDiag); 2316 } else { 2317 Diag(New->getLocation(), diag::err_static_non_static) << New; 2318 Diag(Old->getLocation(), PrevDiag); 2319 return true; 2320 } 2321 } 2322 2323 // If a function is first declared with a calling convention, but is 2324 // later declared or defined without one, the second decl assumes the 2325 // calling convention of the first. 2326 // 2327 // It's OK if a function is first declared without a calling convention, 2328 // but is later declared or defined with the default calling convention. 2329 // 2330 // For the new decl, we have to look at the NON-canonical type to tell the 2331 // difference between a function that really doesn't have a calling 2332 // convention and one that is declared cdecl. That's because in 2333 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 2334 // because it is the default calling convention. 2335 // 2336 // Note also that we DO NOT return at this point, because we still have 2337 // other tests to run. 2338 const FunctionType *OldType = cast<FunctionType>(OldQType); 2339 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 2340 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2341 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2342 bool RequiresAdjustment = false; 2343 if (OldTypeInfo.getCC() == NewTypeInfo.getCC()) { 2344 // Fast path: nothing to do. 2345 2346 // Inherit the CC from the previous declaration if it was specified 2347 // there but not here. 2348 } else if (NewTypeInfo.getCC() == CC_Default) { 2349 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2350 RequiresAdjustment = true; 2351 2352 // Don't complain about mismatches when the default CC is 2353 // effectively the same as the explict one. Only Old decl contains correct 2354 // information about storage class of CXXMethod. 2355 } else if (OldTypeInfo.getCC() == CC_Default && 2356 isABIDefaultCC(*this, NewTypeInfo.getCC(), Old)) { 2357 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2358 RequiresAdjustment = true; 2359 2360 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 2361 NewTypeInfo.getCC())) { 2362 // Calling conventions really aren't compatible, so complain. 2363 Diag(New->getLocation(), diag::err_cconv_change) 2364 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2365 << (OldTypeInfo.getCC() == CC_Default) 2366 << (OldTypeInfo.getCC() == CC_Default ? "" : 2367 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 2368 Diag(Old->getLocation(), diag::note_previous_declaration); 2369 return true; 2370 } 2371 2372 // FIXME: diagnose the other way around? 2373 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2374 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2375 RequiresAdjustment = true; 2376 } 2377 2378 // Merge regparm attribute. 2379 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2380 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2381 if (NewTypeInfo.getHasRegParm()) { 2382 Diag(New->getLocation(), diag::err_regparm_mismatch) 2383 << NewType->getRegParmType() 2384 << OldType->getRegParmType(); 2385 Diag(Old->getLocation(), diag::note_previous_declaration); 2386 return true; 2387 } 2388 2389 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2390 RequiresAdjustment = true; 2391 } 2392 2393 // Merge ns_returns_retained attribute. 2394 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2395 if (NewTypeInfo.getProducesResult()) { 2396 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2397 Diag(Old->getLocation(), diag::note_previous_declaration); 2398 return true; 2399 } 2400 2401 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2402 RequiresAdjustment = true; 2403 } 2404 2405 if (RequiresAdjustment) { 2406 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 2407 New->setType(QualType(NewType, 0)); 2408 NewQType = Context.getCanonicalType(New->getType()); 2409 } 2410 2411 // If this redeclaration makes the function inline, we may need to add it to 2412 // UndefinedButUsed. 2413 if (!Old->isInlined() && New->isInlined() && 2414 !New->hasAttr<GNUInlineAttr>() && 2415 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2416 Old->isUsed(false) && 2417 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2418 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2419 SourceLocation())); 2420 2421 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2422 // about it. 2423 if (New->hasAttr<GNUInlineAttr>() && 2424 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2425 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2426 } 2427 2428 if (getLangOpts().CPlusPlus) { 2429 // (C++98 13.1p2): 2430 // Certain function declarations cannot be overloaded: 2431 // -- Function declarations that differ only in the return type 2432 // cannot be overloaded. 2433 QualType OldReturnType = OldType->getResultType(); 2434 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 2435 QualType ResQT; 2436 if (OldReturnType != NewReturnType) { 2437 if (NewReturnType->isObjCObjectPointerType() 2438 && OldReturnType->isObjCObjectPointerType()) 2439 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2440 if (ResQT.isNull()) { 2441 if (New->isCXXClassMember() && New->isOutOfLine()) 2442 Diag(New->getLocation(), 2443 diag::err_member_def_does_not_match_ret_type) << New; 2444 else 2445 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2446 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2447 return true; 2448 } 2449 else 2450 NewQType = ResQT; 2451 } 2452 2453 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 2454 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 2455 if (OldMethod && NewMethod) { 2456 // Preserve triviality. 2457 NewMethod->setTrivial(OldMethod->isTrivial()); 2458 2459 // MSVC allows explicit template specialization at class scope: 2460 // 2 CXMethodDecls referring to the same function will be injected. 2461 // We don't want a redeclartion error. 2462 bool IsClassScopeExplicitSpecialization = 2463 OldMethod->isFunctionTemplateSpecialization() && 2464 NewMethod->isFunctionTemplateSpecialization(); 2465 bool isFriend = NewMethod->getFriendObjectKind(); 2466 2467 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2468 !IsClassScopeExplicitSpecialization) { 2469 // -- Member function declarations with the same name and the 2470 // same parameter types cannot be overloaded if any of them 2471 // is a static member function declaration. 2472 if (OldMethod->isStatic() || NewMethod->isStatic()) { 2473 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2474 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2475 return true; 2476 } 2477 2478 // C++ [class.mem]p1: 2479 // [...] A member shall not be declared twice in the 2480 // member-specification, except that a nested class or member 2481 // class template can be declared and then later defined. 2482 if (ActiveTemplateInstantiations.empty()) { 2483 unsigned NewDiag; 2484 if (isa<CXXConstructorDecl>(OldMethod)) 2485 NewDiag = diag::err_constructor_redeclared; 2486 else if (isa<CXXDestructorDecl>(NewMethod)) 2487 NewDiag = diag::err_destructor_redeclared; 2488 else if (isa<CXXConversionDecl>(NewMethod)) 2489 NewDiag = diag::err_conv_function_redeclared; 2490 else 2491 NewDiag = diag::err_member_redeclared; 2492 2493 Diag(New->getLocation(), NewDiag); 2494 } else { 2495 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2496 << New << New->getType(); 2497 } 2498 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2499 2500 // Complain if this is an explicit declaration of a special 2501 // member that was initially declared implicitly. 2502 // 2503 // As an exception, it's okay to befriend such methods in order 2504 // to permit the implicit constructor/destructor/operator calls. 2505 } else if (OldMethod->isImplicit()) { 2506 if (isFriend) { 2507 NewMethod->setImplicit(); 2508 } else { 2509 Diag(NewMethod->getLocation(), 2510 diag::err_definition_of_implicitly_declared_member) 2511 << New << getSpecialMember(OldMethod); 2512 return true; 2513 } 2514 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2515 Diag(NewMethod->getLocation(), 2516 diag::err_definition_of_explicitly_defaulted_member) 2517 << getSpecialMember(OldMethod); 2518 return true; 2519 } 2520 } 2521 2522 // C++11 [dcl.attr.noreturn]p1: 2523 // The first declaration of a function shall specify the noreturn 2524 // attribute if any declaration of that function specifies the noreturn 2525 // attribute. 2526 if (New->hasAttr<CXX11NoReturnAttr>() && 2527 !Old->hasAttr<CXX11NoReturnAttr>()) { 2528 Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(), 2529 diag::err_noreturn_missing_on_first_decl); 2530 Diag(Old->getFirstDeclaration()->getLocation(), 2531 diag::note_noreturn_missing_first_decl); 2532 } 2533 2534 // C++11 [dcl.attr.depend]p2: 2535 // The first declaration of a function shall specify the 2536 // carries_dependency attribute for its declarator-id if any declaration 2537 // of the function specifies the carries_dependency attribute. 2538 if (New->hasAttr<CarriesDependencyAttr>() && 2539 !Old->hasAttr<CarriesDependencyAttr>()) { 2540 Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(), 2541 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2542 Diag(Old->getFirstDeclaration()->getLocation(), 2543 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2544 } 2545 2546 // (C++98 8.3.5p3): 2547 // All declarations for a function shall agree exactly in both the 2548 // return type and the parameter-type-list. 2549 // We also want to respect all the extended bits except noreturn. 2550 2551 // noreturn should now match unless the old type info didn't have it. 2552 QualType OldQTypeForComparison = OldQType; 2553 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2554 assert(OldQType == QualType(OldType, 0)); 2555 const FunctionType *OldTypeForComparison 2556 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2557 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2558 assert(OldQTypeForComparison.isCanonical()); 2559 } 2560 2561 if (haveIncompatibleLanguageLinkages(Old, New)) { 2562 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2563 Diag(Old->getLocation(), PrevDiag); 2564 return true; 2565 } 2566 2567 if (OldQTypeForComparison == NewQType) 2568 return MergeCompatibleFunctionDecls(New, Old, S); 2569 2570 // Fall through for conflicting redeclarations and redefinitions. 2571 } 2572 2573 // C: Function types need to be compatible, not identical. This handles 2574 // duplicate function decls like "void f(int); void f(enum X);" properly. 2575 if (!getLangOpts().CPlusPlus && 2576 Context.typesAreCompatible(OldQType, NewQType)) { 2577 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2578 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2579 const FunctionProtoType *OldProto = 0; 2580 if (isa<FunctionNoProtoType>(NewFuncType) && 2581 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2582 // The old declaration provided a function prototype, but the 2583 // new declaration does not. Merge in the prototype. 2584 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2585 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 2586 OldProto->arg_type_end()); 2587 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 2588 ParamTypes, 2589 OldProto->getExtProtoInfo()); 2590 New->setType(NewQType); 2591 New->setHasInheritedPrototype(); 2592 2593 // Synthesize a parameter for each argument type. 2594 SmallVector<ParmVarDecl*, 16> Params; 2595 for (FunctionProtoType::arg_type_iterator 2596 ParamType = OldProto->arg_type_begin(), 2597 ParamEnd = OldProto->arg_type_end(); 2598 ParamType != ParamEnd; ++ParamType) { 2599 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 2600 SourceLocation(), 2601 SourceLocation(), 0, 2602 *ParamType, /*TInfo=*/0, 2603 SC_None, SC_None, 2604 0); 2605 Param->setScopeInfo(0, Params.size()); 2606 Param->setImplicit(); 2607 Params.push_back(Param); 2608 } 2609 2610 New->setParams(Params); 2611 } 2612 2613 return MergeCompatibleFunctionDecls(New, Old, S); 2614 } 2615 2616 // GNU C permits a K&R definition to follow a prototype declaration 2617 // if the declared types of the parameters in the K&R definition 2618 // match the types in the prototype declaration, even when the 2619 // promoted types of the parameters from the K&R definition differ 2620 // from the types in the prototype. GCC then keeps the types from 2621 // the prototype. 2622 // 2623 // If a variadic prototype is followed by a non-variadic K&R definition, 2624 // the K&R definition becomes variadic. This is sort of an edge case, but 2625 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2626 // C99 6.9.1p8. 2627 if (!getLangOpts().CPlusPlus && 2628 Old->hasPrototype() && !New->hasPrototype() && 2629 New->getType()->getAs<FunctionProtoType>() && 2630 Old->getNumParams() == New->getNumParams()) { 2631 SmallVector<QualType, 16> ArgTypes; 2632 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2633 const FunctionProtoType *OldProto 2634 = Old->getType()->getAs<FunctionProtoType>(); 2635 const FunctionProtoType *NewProto 2636 = New->getType()->getAs<FunctionProtoType>(); 2637 2638 // Determine whether this is the GNU C extension. 2639 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 2640 NewProto->getResultType()); 2641 bool LooseCompatible = !MergedReturn.isNull(); 2642 for (unsigned Idx = 0, End = Old->getNumParams(); 2643 LooseCompatible && Idx != End; ++Idx) { 2644 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2645 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2646 if (Context.typesAreCompatible(OldParm->getType(), 2647 NewProto->getArgType(Idx))) { 2648 ArgTypes.push_back(NewParm->getType()); 2649 } else if (Context.typesAreCompatible(OldParm->getType(), 2650 NewParm->getType(), 2651 /*CompareUnqualified=*/true)) { 2652 GNUCompatibleParamWarning Warn 2653 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 2654 Warnings.push_back(Warn); 2655 ArgTypes.push_back(NewParm->getType()); 2656 } else 2657 LooseCompatible = false; 2658 } 2659 2660 if (LooseCompatible) { 2661 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2662 Diag(Warnings[Warn].NewParm->getLocation(), 2663 diag::ext_param_promoted_not_compatible_with_prototype) 2664 << Warnings[Warn].PromotedType 2665 << Warnings[Warn].OldParm->getType(); 2666 if (Warnings[Warn].OldParm->getLocation().isValid()) 2667 Diag(Warnings[Warn].OldParm->getLocation(), 2668 diag::note_previous_declaration); 2669 } 2670 2671 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2672 OldProto->getExtProtoInfo())); 2673 return MergeCompatibleFunctionDecls(New, Old, S); 2674 } 2675 2676 // Fall through to diagnose conflicting types. 2677 } 2678 2679 // A function that has already been declared has been redeclared or defined 2680 // with a different type- show appropriate diagnostic 2681 if (unsigned BuiltinID = Old->getBuiltinID()) { 2682 // The user has declared a builtin function with an incompatible 2683 // signature. 2684 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2685 // The function the user is redeclaring is a library-defined 2686 // function like 'malloc' or 'printf'. Warn about the 2687 // redeclaration, then pretend that we don't know about this 2688 // library built-in. 2689 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2690 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 2691 << Old << Old->getType(); 2692 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2693 Old->setInvalidDecl(); 2694 return false; 2695 } 2696 2697 PrevDiag = diag::note_previous_builtin_declaration; 2698 } 2699 2700 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2701 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 2702 return true; 2703} 2704 2705/// \brief Completes the merge of two function declarations that are 2706/// known to be compatible. 2707/// 2708/// This routine handles the merging of attributes and other 2709/// properties of function declarations form the old declaration to 2710/// the new declaration, once we know that New is in fact a 2711/// redeclaration of Old. 2712/// 2713/// \returns false 2714bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2715 Scope *S) { 2716 // Merge the attributes 2717 mergeDeclAttributes(New, Old); 2718 2719 // Merge the storage class. 2720 if (Old->getStorageClass() != SC_Extern && 2721 Old->getStorageClass() != SC_None) 2722 New->setStorageClass(Old->getStorageClass()); 2723 2724 // Merge "pure" flag. 2725 if (Old->isPure()) 2726 New->setPure(); 2727 2728 // Merge "used" flag. 2729 if (Old->isUsed(false)) 2730 New->setUsed(); 2731 2732 // Merge attributes from the parameters. These can mismatch with K&R 2733 // declarations. 2734 if (New->getNumParams() == Old->getNumParams()) 2735 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2736 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2737 *this); 2738 2739 if (getLangOpts().CPlusPlus) 2740 return MergeCXXFunctionDecl(New, Old, S); 2741 2742 // Merge the function types so the we get the composite types for the return 2743 // and argument types. 2744 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2745 if (!Merged.isNull()) 2746 New->setType(Merged); 2747 2748 return false; 2749} 2750 2751 2752void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2753 ObjCMethodDecl *oldMethod) { 2754 2755 // Merge the attributes, including deprecated/unavailable 2756 mergeDeclAttributes(newMethod, oldMethod, AMK_Override); 2757 2758 // Merge attributes from the parameters. 2759 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2760 oe = oldMethod->param_end(); 2761 for (ObjCMethodDecl::param_iterator 2762 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2763 ni != ne && oi != oe; ++ni, ++oi) 2764 mergeParamDeclAttributes(*ni, *oi, *this); 2765 2766 CheckObjCMethodOverride(newMethod, oldMethod); 2767} 2768 2769/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2770/// scope as a previous declaration 'Old'. Figure out how to merge their types, 2771/// emitting diagnostics as appropriate. 2772/// 2773/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2774/// to here in AddInitializerToDecl. We can't check them before the initializer 2775/// is attached. 2776void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 2777 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2778 return; 2779 2780 QualType MergedT; 2781 if (getLangOpts().CPlusPlus) { 2782 AutoType *AT = New->getType()->getContainedAutoType(); 2783 if (AT && !AT->isDeduced()) { 2784 // We don't know what the new type is until the initializer is attached. 2785 return; 2786 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2787 // These could still be something that needs exception specs checked. 2788 return MergeVarDeclExceptionSpecs(New, Old); 2789 } 2790 // C++ [basic.link]p10: 2791 // [...] the types specified by all declarations referring to a given 2792 // object or function shall be identical, except that declarations for an 2793 // array object can specify array types that differ by the presence or 2794 // absence of a major array bound (8.3.4). 2795 else if (Old->getType()->isIncompleteArrayType() && 2796 New->getType()->isArrayType()) { 2797 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2798 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2799 if (Context.hasSameType(OldArray->getElementType(), 2800 NewArray->getElementType())) 2801 MergedT = New->getType(); 2802 } else if (Old->getType()->isArrayType() && 2803 New->getType()->isIncompleteArrayType()) { 2804 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2805 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2806 if (Context.hasSameType(OldArray->getElementType(), 2807 NewArray->getElementType())) 2808 MergedT = Old->getType(); 2809 } else if (New->getType()->isObjCObjectPointerType() 2810 && Old->getType()->isObjCObjectPointerType()) { 2811 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2812 Old->getType()); 2813 } 2814 } else { 2815 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2816 } 2817 if (MergedT.isNull()) { 2818 Diag(New->getLocation(), diag::err_redefinition_different_type) 2819 << New->getDeclName() << New->getType() << Old->getType(); 2820 Diag(Old->getLocation(), diag::note_previous_definition); 2821 return New->setInvalidDecl(); 2822 } 2823 New->setType(MergedT); 2824} 2825 2826/// MergeVarDecl - We just parsed a variable 'New' which has the same name 2827/// and scope as a previous declaration 'Old'. Figure out how to resolve this 2828/// situation, merging decls or emitting diagnostics as appropriate. 2829/// 2830/// Tentative definition rules (C99 6.9.2p2) are checked by 2831/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2832/// definitions here, since the initializer hasn't been attached. 2833/// 2834void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2835 // If the new decl is already invalid, don't do any other checking. 2836 if (New->isInvalidDecl()) 2837 return; 2838 2839 // Verify the old decl was also a variable. 2840 VarDecl *Old = 0; 2841 if (!Previous.isSingleResult() || 2842 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 2843 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2844 << New->getDeclName(); 2845 Diag(Previous.getRepresentativeDecl()->getLocation(), 2846 diag::note_previous_definition); 2847 return New->setInvalidDecl(); 2848 } 2849 2850 // C++ [class.mem]p1: 2851 // A member shall not be declared twice in the member-specification [...] 2852 // 2853 // Here, we need only consider static data members. 2854 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 2855 Diag(New->getLocation(), diag::err_duplicate_member) 2856 << New->getIdentifier(); 2857 Diag(Old->getLocation(), diag::note_previous_declaration); 2858 New->setInvalidDecl(); 2859 } 2860 2861 mergeDeclAttributes(New, Old); 2862 // Warn if an already-declared variable is made a weak_import in a subsequent 2863 // declaration 2864 if (New->getAttr<WeakImportAttr>() && 2865 Old->getStorageClass() == SC_None && 2866 !Old->getAttr<WeakImportAttr>()) { 2867 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 2868 Diag(Old->getLocation(), diag::note_previous_definition); 2869 // Remove weak_import attribute on new declaration. 2870 New->dropAttr<WeakImportAttr>(); 2871 } 2872 2873 // Merge the types. 2874 MergeVarDeclTypes(New, Old); 2875 if (New->isInvalidDecl()) 2876 return; 2877 2878 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 2879 if (New->getStorageClass() == SC_Static && 2880 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 2881 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 2882 Diag(Old->getLocation(), diag::note_previous_definition); 2883 return New->setInvalidDecl(); 2884 } 2885 // C99 6.2.2p4: 2886 // For an identifier declared with the storage-class specifier 2887 // extern in a scope in which a prior declaration of that 2888 // identifier is visible,23) if the prior declaration specifies 2889 // internal or external linkage, the linkage of the identifier at 2890 // the later declaration is the same as the linkage specified at 2891 // the prior declaration. If no prior declaration is visible, or 2892 // if the prior declaration specifies no linkage, then the 2893 // identifier has external linkage. 2894 if (New->hasExternalStorage() && Old->hasLinkage()) 2895 /* Okay */; 2896 else if (New->getStorageClass() != SC_Static && 2897 Old->getStorageClass() == SC_Static) { 2898 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 2899 Diag(Old->getLocation(), diag::note_previous_definition); 2900 return New->setInvalidDecl(); 2901 } 2902 2903 // Check if extern is followed by non-extern and vice-versa. 2904 if (New->hasExternalStorage() && 2905 !Old->hasLinkage() && Old->isLocalVarDecl()) { 2906 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 2907 Diag(Old->getLocation(), diag::note_previous_definition); 2908 return New->setInvalidDecl(); 2909 } 2910 if (Old->hasExternalStorage() && 2911 New->isLocalVarDecl() && !New->hasLinkage()) { 2912 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 2913 Diag(Old->getLocation(), diag::note_previous_definition); 2914 return New->setInvalidDecl(); 2915 } 2916 2917 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 2918 2919 // FIXME: The test for external storage here seems wrong? We still 2920 // need to check for mismatches. 2921 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 2922 // Don't complain about out-of-line definitions of static members. 2923 !(Old->getLexicalDeclContext()->isRecord() && 2924 !New->getLexicalDeclContext()->isRecord())) { 2925 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 2926 Diag(Old->getLocation(), diag::note_previous_definition); 2927 return New->setInvalidDecl(); 2928 } 2929 2930 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 2931 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 2932 Diag(Old->getLocation(), diag::note_previous_definition); 2933 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 2934 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 2935 Diag(Old->getLocation(), diag::note_previous_definition); 2936 } 2937 2938 // C++ doesn't have tentative definitions, so go right ahead and check here. 2939 const VarDecl *Def; 2940 if (getLangOpts().CPlusPlus && 2941 New->isThisDeclarationADefinition() == VarDecl::Definition && 2942 (Def = Old->getDefinition())) { 2943 Diag(New->getLocation(), diag::err_redefinition) 2944 << New->getDeclName(); 2945 Diag(Def->getLocation(), diag::note_previous_definition); 2946 New->setInvalidDecl(); 2947 return; 2948 } 2949 2950 if (haveIncompatibleLanguageLinkages(Old, New)) { 2951 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2952 Diag(Old->getLocation(), diag::note_previous_definition); 2953 New->setInvalidDecl(); 2954 return; 2955 } 2956 2957 // c99 6.2.2 P4. 2958 // For an identifier declared with the storage-class specifier extern in a 2959 // scope in which a prior declaration of that identifier is visible, if 2960 // the prior declaration specifies internal or external linkage, the linkage 2961 // of the identifier at the later declaration is the same as the linkage 2962 // specified at the prior declaration. 2963 // FIXME. revisit this code. 2964 if (New->hasExternalStorage() && 2965 Old->getLinkage() == InternalLinkage) 2966 New->setStorageClass(Old->getStorageClass()); 2967 2968 // Merge "used" flag. 2969 if (Old->isUsed(false)) 2970 New->setUsed(); 2971 2972 // Keep a chain of previous declarations. 2973 New->setPreviousDeclaration(Old); 2974 2975 // Inherit access appropriately. 2976 New->setAccess(Old->getAccess()); 2977} 2978 2979/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2980/// no declarator (e.g. "struct foo;") is parsed. 2981Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2982 DeclSpec &DS) { 2983 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 2984} 2985 2986/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 2987/// no declarator (e.g. "struct foo;") is parsed. It also accopts template 2988/// parameters to cope with template friend declarations. 2989Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2990 DeclSpec &DS, 2991 MultiTemplateParamsArg TemplateParams) { 2992 Decl *TagD = 0; 2993 TagDecl *Tag = 0; 2994 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2995 DS.getTypeSpecType() == DeclSpec::TST_struct || 2996 DS.getTypeSpecType() == DeclSpec::TST_interface || 2997 DS.getTypeSpecType() == DeclSpec::TST_union || 2998 DS.getTypeSpecType() == DeclSpec::TST_enum) { 2999 TagD = DS.getRepAsDecl(); 3000 3001 if (!TagD) // We probably had an error 3002 return 0; 3003 3004 // Note that the above type specs guarantee that the 3005 // type rep is a Decl, whereas in many of the others 3006 // it's a Type. 3007 if (isa<TagDecl>(TagD)) 3008 Tag = cast<TagDecl>(TagD); 3009 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3010 Tag = CTD->getTemplatedDecl(); 3011 } 3012 3013 if (Tag) { 3014 getASTContext().addUnnamedTag(Tag); 3015 Tag->setFreeStanding(); 3016 if (Tag->isInvalidDecl()) 3017 return Tag; 3018 } 3019 3020 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3021 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3022 // or incomplete types shall not be restrict-qualified." 3023 if (TypeQuals & DeclSpec::TQ_restrict) 3024 Diag(DS.getRestrictSpecLoc(), 3025 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3026 << DS.getSourceRange(); 3027 } 3028 3029 if (DS.isConstexprSpecified()) { 3030 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3031 // and definitions of functions and variables. 3032 if (Tag) 3033 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3034 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3035 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3036 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3037 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3038 else 3039 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3040 // Don't emit warnings after this error. 3041 return TagD; 3042 } 3043 3044 if (DS.isFriendSpecified()) { 3045 // If we're dealing with a decl but not a TagDecl, assume that 3046 // whatever routines created it handled the friendship aspect. 3047 if (TagD && !Tag) 3048 return 0; 3049 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3050 } 3051 3052 // Track whether we warned about the fact that there aren't any 3053 // declarators. 3054 bool emittedWarning = false; 3055 3056 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3057 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3058 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3059 if (getLangOpts().CPlusPlus || 3060 Record->getDeclContext()->isRecord()) 3061 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3062 3063 Diag(DS.getLocStart(), diag::ext_no_declarators) 3064 << DS.getSourceRange(); 3065 emittedWarning = true; 3066 } 3067 } 3068 3069 // Check for Microsoft C extension: anonymous struct. 3070 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3071 CurContext->isRecord() && 3072 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3073 // Handle 2 kinds of anonymous struct: 3074 // struct STRUCT; 3075 // and 3076 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3077 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3078 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3079 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3080 DS.getRepAsType().get()->isStructureType())) { 3081 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3082 << DS.getSourceRange(); 3083 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3084 } 3085 } 3086 3087 if (getLangOpts().CPlusPlus && 3088 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3089 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3090 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3091 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 3092 Diag(Enum->getLocation(), diag::ext_no_declarators) 3093 << DS.getSourceRange(); 3094 emittedWarning = true; 3095 } 3096 3097 // Skip all the checks below if we have a type error. 3098 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 3099 3100 if (!DS.isMissingDeclaratorOk()) { 3101 // Warn about typedefs of enums without names, since this is an 3102 // extension in both Microsoft and GNU. 3103 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 3104 Tag && isa<EnumDecl>(Tag)) { 3105 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3106 << DS.getSourceRange(); 3107 return Tag; 3108 } 3109 3110 Diag(DS.getLocStart(), diag::ext_no_declarators) 3111 << DS.getSourceRange(); 3112 emittedWarning = true; 3113 } 3114 3115 // We're going to complain about a bunch of spurious specifiers; 3116 // only do this if we're declaring a tag, because otherwise we 3117 // should be getting diag::ext_no_declarators. 3118 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 3119 return TagD; 3120 3121 // Note that a linkage-specification sets a storage class, but 3122 // 'extern "C" struct foo;' is actually valid and not theoretically 3123 // useless. 3124 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 3125 if (!DS.isExternInLinkageSpec()) 3126 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 3127 << DeclSpec::getSpecifierName(scs); 3128 3129 if (DS.isThreadSpecified()) 3130 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 3131 if (DS.getTypeQualifiers()) { 3132 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3133 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 3134 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3135 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 3136 // Restrict is covered above. 3137 } 3138 if (DS.isInlineSpecified()) 3139 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 3140 if (DS.isVirtualSpecified()) 3141 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 3142 if (DS.isExplicitSpecified()) 3143 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 3144 3145 if (DS.isModulePrivateSpecified() && 3146 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3147 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3148 << Tag->getTagKind() 3149 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3150 3151 // Warn about ignored type attributes, for example: 3152 // __attribute__((aligned)) struct A; 3153 // Attributes should be placed after tag to apply to type declaration. 3154 if (!DS.getAttributes().empty()) { 3155 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3156 if (TypeSpecType == DeclSpec::TST_class || 3157 TypeSpecType == DeclSpec::TST_struct || 3158 TypeSpecType == DeclSpec::TST_interface || 3159 TypeSpecType == DeclSpec::TST_union || 3160 TypeSpecType == DeclSpec::TST_enum) { 3161 AttributeList* attrs = DS.getAttributes().getList(); 3162 while (attrs) { 3163 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3164 << attrs->getName() 3165 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3166 TypeSpecType == DeclSpec::TST_struct ? 1 : 3167 TypeSpecType == DeclSpec::TST_union ? 2 : 3168 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3169 attrs = attrs->getNext(); 3170 } 3171 } 3172 } 3173 3174 ActOnDocumentableDecl(TagD); 3175 3176 return TagD; 3177} 3178 3179/// We are trying to inject an anonymous member into the given scope; 3180/// check if there's an existing declaration that can't be overloaded. 3181/// 3182/// \return true if this is a forbidden redeclaration 3183static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3184 Scope *S, 3185 DeclContext *Owner, 3186 DeclarationName Name, 3187 SourceLocation NameLoc, 3188 unsigned diagnostic) { 3189 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3190 Sema::ForRedeclaration); 3191 if (!SemaRef.LookupName(R, S)) return false; 3192 3193 if (R.getAsSingle<TagDecl>()) 3194 return false; 3195 3196 // Pick a representative declaration. 3197 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3198 assert(PrevDecl && "Expected a non-null Decl"); 3199 3200 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3201 return false; 3202 3203 SemaRef.Diag(NameLoc, diagnostic) << Name; 3204 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3205 3206 return true; 3207} 3208 3209/// InjectAnonymousStructOrUnionMembers - Inject the members of the 3210/// anonymous struct or union AnonRecord into the owning context Owner 3211/// and scope S. This routine will be invoked just after we realize 3212/// that an unnamed union or struct is actually an anonymous union or 3213/// struct, e.g., 3214/// 3215/// @code 3216/// union { 3217/// int i; 3218/// float f; 3219/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3220/// // f into the surrounding scope.x 3221/// @endcode 3222/// 3223/// This routine is recursive, injecting the names of nested anonymous 3224/// structs/unions into the owning context and scope as well. 3225static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3226 DeclContext *Owner, 3227 RecordDecl *AnonRecord, 3228 AccessSpecifier AS, 3229 SmallVector<NamedDecl*, 2> &Chaining, 3230 bool MSAnonStruct) { 3231 unsigned diagKind 3232 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3233 : diag::err_anonymous_struct_member_redecl; 3234 3235 bool Invalid = false; 3236 3237 // Look every FieldDecl and IndirectFieldDecl with a name. 3238 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3239 DEnd = AnonRecord->decls_end(); 3240 D != DEnd; ++D) { 3241 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3242 cast<NamedDecl>(*D)->getDeclName()) { 3243 ValueDecl *VD = cast<ValueDecl>(*D); 3244 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3245 VD->getLocation(), diagKind)) { 3246 // C++ [class.union]p2: 3247 // The names of the members of an anonymous union shall be 3248 // distinct from the names of any other entity in the 3249 // scope in which the anonymous union is declared. 3250 Invalid = true; 3251 } else { 3252 // C++ [class.union]p2: 3253 // For the purpose of name lookup, after the anonymous union 3254 // definition, the members of the anonymous union are 3255 // considered to have been defined in the scope in which the 3256 // anonymous union is declared. 3257 unsigned OldChainingSize = Chaining.size(); 3258 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3259 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3260 PE = IF->chain_end(); PI != PE; ++PI) 3261 Chaining.push_back(*PI); 3262 else 3263 Chaining.push_back(VD); 3264 3265 assert(Chaining.size() >= 2); 3266 NamedDecl **NamedChain = 3267 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3268 for (unsigned i = 0; i < Chaining.size(); i++) 3269 NamedChain[i] = Chaining[i]; 3270 3271 IndirectFieldDecl* IndirectField = 3272 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3273 VD->getIdentifier(), VD->getType(), 3274 NamedChain, Chaining.size()); 3275 3276 IndirectField->setAccess(AS); 3277 IndirectField->setImplicit(); 3278 SemaRef.PushOnScopeChains(IndirectField, S); 3279 3280 // That includes picking up the appropriate access specifier. 3281 if (AS != AS_none) IndirectField->setAccess(AS); 3282 3283 Chaining.resize(OldChainingSize); 3284 } 3285 } 3286 } 3287 3288 return Invalid; 3289} 3290 3291/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3292/// a VarDecl::StorageClass. Any error reporting is up to the caller: 3293/// illegal input values are mapped to SC_None. 3294static StorageClass 3295StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3296 switch (StorageClassSpec) { 3297 case DeclSpec::SCS_unspecified: return SC_None; 3298 case DeclSpec::SCS_extern: return SC_Extern; 3299 case DeclSpec::SCS_static: return SC_Static; 3300 case DeclSpec::SCS_auto: return SC_Auto; 3301 case DeclSpec::SCS_register: return SC_Register; 3302 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3303 // Illegal SCSs map to None: error reporting is up to the caller. 3304 case DeclSpec::SCS_mutable: // Fall through. 3305 case DeclSpec::SCS_typedef: return SC_None; 3306 } 3307 llvm_unreachable("unknown storage class specifier"); 3308} 3309 3310/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 3311/// a StorageClass. Any error reporting is up to the caller: 3312/// illegal input values are mapped to SC_None. 3313static StorageClass 3314StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3315 switch (StorageClassSpec) { 3316 case DeclSpec::SCS_unspecified: return SC_None; 3317 case DeclSpec::SCS_extern: return SC_Extern; 3318 case DeclSpec::SCS_static: return SC_Static; 3319 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3320 // Illegal SCSs map to None: error reporting is up to the caller. 3321 case DeclSpec::SCS_auto: // Fall through. 3322 case DeclSpec::SCS_mutable: // Fall through. 3323 case DeclSpec::SCS_register: // Fall through. 3324 case DeclSpec::SCS_typedef: return SC_None; 3325 } 3326 llvm_unreachable("unknown storage class specifier"); 3327} 3328 3329/// BuildAnonymousStructOrUnion - Handle the declaration of an 3330/// anonymous structure or union. Anonymous unions are a C++ feature 3331/// (C++ [class.union]) and a C11 feature; anonymous structures 3332/// are a C11 feature and GNU C++ extension. 3333Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3334 AccessSpecifier AS, 3335 RecordDecl *Record) { 3336 DeclContext *Owner = Record->getDeclContext(); 3337 3338 // Diagnose whether this anonymous struct/union is an extension. 3339 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3340 Diag(Record->getLocation(), diag::ext_anonymous_union); 3341 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3342 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3343 else if (!Record->isUnion() && !getLangOpts().C11) 3344 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3345 3346 // C and C++ require different kinds of checks for anonymous 3347 // structs/unions. 3348 bool Invalid = false; 3349 if (getLangOpts().CPlusPlus) { 3350 const char* PrevSpec = 0; 3351 unsigned DiagID; 3352 if (Record->isUnion()) { 3353 // C++ [class.union]p6: 3354 // Anonymous unions declared in a named namespace or in the 3355 // global namespace shall be declared static. 3356 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3357 (isa<TranslationUnitDecl>(Owner) || 3358 (isa<NamespaceDecl>(Owner) && 3359 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3360 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3361 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3362 3363 // Recover by adding 'static'. 3364 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3365 PrevSpec, DiagID); 3366 } 3367 // C++ [class.union]p6: 3368 // A storage class is not allowed in a declaration of an 3369 // anonymous union in a class scope. 3370 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3371 isa<RecordDecl>(Owner)) { 3372 Diag(DS.getStorageClassSpecLoc(), 3373 diag::err_anonymous_union_with_storage_spec) 3374 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3375 3376 // Recover by removing the storage specifier. 3377 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3378 SourceLocation(), 3379 PrevSpec, DiagID); 3380 } 3381 } 3382 3383 // Ignore const/volatile/restrict qualifiers. 3384 if (DS.getTypeQualifiers()) { 3385 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3386 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3387 << Record->isUnion() << 0 3388 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3389 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3390 Diag(DS.getVolatileSpecLoc(), 3391 diag::ext_anonymous_struct_union_qualified) 3392 << Record->isUnion() << 1 3393 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3394 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3395 Diag(DS.getRestrictSpecLoc(), 3396 diag::ext_anonymous_struct_union_qualified) 3397 << Record->isUnion() << 2 3398 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3399 3400 DS.ClearTypeQualifiers(); 3401 } 3402 3403 // C++ [class.union]p2: 3404 // The member-specification of an anonymous union shall only 3405 // define non-static data members. [Note: nested types and 3406 // functions cannot be declared within an anonymous union. ] 3407 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3408 MemEnd = Record->decls_end(); 3409 Mem != MemEnd; ++Mem) { 3410 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3411 // C++ [class.union]p3: 3412 // An anonymous union shall not have private or protected 3413 // members (clause 11). 3414 assert(FD->getAccess() != AS_none); 3415 if (FD->getAccess() != AS_public) { 3416 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3417 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3418 Invalid = true; 3419 } 3420 3421 // C++ [class.union]p1 3422 // An object of a class with a non-trivial constructor, a non-trivial 3423 // copy constructor, a non-trivial destructor, or a non-trivial copy 3424 // assignment operator cannot be a member of a union, nor can an 3425 // array of such objects. 3426 if (CheckNontrivialField(FD)) 3427 Invalid = true; 3428 } else if ((*Mem)->isImplicit()) { 3429 // Any implicit members are fine. 3430 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3431 // This is a type that showed up in an 3432 // elaborated-type-specifier inside the anonymous struct or 3433 // union, but which actually declares a type outside of the 3434 // anonymous struct or union. It's okay. 3435 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3436 if (!MemRecord->isAnonymousStructOrUnion() && 3437 MemRecord->getDeclName()) { 3438 // Visual C++ allows type definition in anonymous struct or union. 3439 if (getLangOpts().MicrosoftExt) 3440 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3441 << (int)Record->isUnion(); 3442 else { 3443 // This is a nested type declaration. 3444 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3445 << (int)Record->isUnion(); 3446 Invalid = true; 3447 } 3448 } else { 3449 // This is an anonymous type definition within another anonymous type. 3450 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3451 // not part of standard C++. 3452 Diag(MemRecord->getLocation(), 3453 diag::ext_anonymous_record_with_anonymous_type) 3454 << (int)Record->isUnion(); 3455 } 3456 } else if (isa<AccessSpecDecl>(*Mem)) { 3457 // Any access specifier is fine. 3458 } else { 3459 // We have something that isn't a non-static data 3460 // member. Complain about it. 3461 unsigned DK = diag::err_anonymous_record_bad_member; 3462 if (isa<TypeDecl>(*Mem)) 3463 DK = diag::err_anonymous_record_with_type; 3464 else if (isa<FunctionDecl>(*Mem)) 3465 DK = diag::err_anonymous_record_with_function; 3466 else if (isa<VarDecl>(*Mem)) 3467 DK = diag::err_anonymous_record_with_static; 3468 3469 // Visual C++ allows type definition in anonymous struct or union. 3470 if (getLangOpts().MicrosoftExt && 3471 DK == diag::err_anonymous_record_with_type) 3472 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3473 << (int)Record->isUnion(); 3474 else { 3475 Diag((*Mem)->getLocation(), DK) 3476 << (int)Record->isUnion(); 3477 Invalid = true; 3478 } 3479 } 3480 } 3481 } 3482 3483 if (!Record->isUnion() && !Owner->isRecord()) { 3484 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3485 << (int)getLangOpts().CPlusPlus; 3486 Invalid = true; 3487 } 3488 3489 // Mock up a declarator. 3490 Declarator Dc(DS, Declarator::MemberContext); 3491 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3492 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3493 3494 // Create a declaration for this anonymous struct/union. 3495 NamedDecl *Anon = 0; 3496 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3497 Anon = FieldDecl::Create(Context, OwningClass, 3498 DS.getLocStart(), 3499 Record->getLocation(), 3500 /*IdentifierInfo=*/0, 3501 Context.getTypeDeclType(Record), 3502 TInfo, 3503 /*BitWidth=*/0, /*Mutable=*/false, 3504 /*InitStyle=*/ICIS_NoInit); 3505 Anon->setAccess(AS); 3506 if (getLangOpts().CPlusPlus) 3507 FieldCollector->Add(cast<FieldDecl>(Anon)); 3508 } else { 3509 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3510 assert(SCSpec != DeclSpec::SCS_typedef && 3511 "Parser allowed 'typedef' as storage class VarDecl."); 3512 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3513 if (SCSpec == DeclSpec::SCS_mutable) { 3514 // mutable can only appear on non-static class members, so it's always 3515 // an error here 3516 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3517 Invalid = true; 3518 SC = SC_None; 3519 } 3520 SCSpec = DS.getStorageClassSpecAsWritten(); 3521 VarDecl::StorageClass SCAsWritten 3522 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3523 3524 Anon = VarDecl::Create(Context, Owner, 3525 DS.getLocStart(), 3526 Record->getLocation(), /*IdentifierInfo=*/0, 3527 Context.getTypeDeclType(Record), 3528 TInfo, SC, SCAsWritten); 3529 3530 // Default-initialize the implicit variable. This initialization will be 3531 // trivial in almost all cases, except if a union member has an in-class 3532 // initializer: 3533 // union { int n = 0; }; 3534 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3535 } 3536 Anon->setImplicit(); 3537 3538 // Add the anonymous struct/union object to the current 3539 // context. We'll be referencing this object when we refer to one of 3540 // its members. 3541 Owner->addDecl(Anon); 3542 3543 // Inject the members of the anonymous struct/union into the owning 3544 // context and into the identifier resolver chain for name lookup 3545 // purposes. 3546 SmallVector<NamedDecl*, 2> Chain; 3547 Chain.push_back(Anon); 3548 3549 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3550 Chain, false)) 3551 Invalid = true; 3552 3553 // Mark this as an anonymous struct/union type. Note that we do not 3554 // do this until after we have already checked and injected the 3555 // members of this anonymous struct/union type, because otherwise 3556 // the members could be injected twice: once by DeclContext when it 3557 // builds its lookup table, and once by 3558 // InjectAnonymousStructOrUnionMembers. 3559 Record->setAnonymousStructOrUnion(true); 3560 3561 if (Invalid) 3562 Anon->setInvalidDecl(); 3563 3564 return Anon; 3565} 3566 3567/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3568/// Microsoft C anonymous structure. 3569/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3570/// Example: 3571/// 3572/// struct A { int a; }; 3573/// struct B { struct A; int b; }; 3574/// 3575/// void foo() { 3576/// B var; 3577/// var.a = 3; 3578/// } 3579/// 3580Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3581 RecordDecl *Record) { 3582 3583 // If there is no Record, get the record via the typedef. 3584 if (!Record) 3585 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3586 3587 // Mock up a declarator. 3588 Declarator Dc(DS, Declarator::TypeNameContext); 3589 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3590 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3591 3592 // Create a declaration for this anonymous struct. 3593 NamedDecl* Anon = FieldDecl::Create(Context, 3594 cast<RecordDecl>(CurContext), 3595 DS.getLocStart(), 3596 DS.getLocStart(), 3597 /*IdentifierInfo=*/0, 3598 Context.getTypeDeclType(Record), 3599 TInfo, 3600 /*BitWidth=*/0, /*Mutable=*/false, 3601 /*InitStyle=*/ICIS_NoInit); 3602 Anon->setImplicit(); 3603 3604 // Add the anonymous struct object to the current context. 3605 CurContext->addDecl(Anon); 3606 3607 // Inject the members of the anonymous struct into the current 3608 // context and into the identifier resolver chain for name lookup 3609 // purposes. 3610 SmallVector<NamedDecl*, 2> Chain; 3611 Chain.push_back(Anon); 3612 3613 RecordDecl *RecordDef = Record->getDefinition(); 3614 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3615 RecordDef, AS_none, 3616 Chain, true)) 3617 Anon->setInvalidDecl(); 3618 3619 return Anon; 3620} 3621 3622/// GetNameForDeclarator - Determine the full declaration name for the 3623/// given Declarator. 3624DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3625 return GetNameFromUnqualifiedId(D.getName()); 3626} 3627 3628/// \brief Retrieves the declaration name from a parsed unqualified-id. 3629DeclarationNameInfo 3630Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3631 DeclarationNameInfo NameInfo; 3632 NameInfo.setLoc(Name.StartLocation); 3633 3634 switch (Name.getKind()) { 3635 3636 case UnqualifiedId::IK_ImplicitSelfParam: 3637 case UnqualifiedId::IK_Identifier: 3638 NameInfo.setName(Name.Identifier); 3639 NameInfo.setLoc(Name.StartLocation); 3640 return NameInfo; 3641 3642 case UnqualifiedId::IK_OperatorFunctionId: 3643 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3644 Name.OperatorFunctionId.Operator)); 3645 NameInfo.setLoc(Name.StartLocation); 3646 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3647 = Name.OperatorFunctionId.SymbolLocations[0]; 3648 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3649 = Name.EndLocation.getRawEncoding(); 3650 return NameInfo; 3651 3652 case UnqualifiedId::IK_LiteralOperatorId: 3653 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3654 Name.Identifier)); 3655 NameInfo.setLoc(Name.StartLocation); 3656 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3657 return NameInfo; 3658 3659 case UnqualifiedId::IK_ConversionFunctionId: { 3660 TypeSourceInfo *TInfo; 3661 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3662 if (Ty.isNull()) 3663 return DeclarationNameInfo(); 3664 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3665 Context.getCanonicalType(Ty))); 3666 NameInfo.setLoc(Name.StartLocation); 3667 NameInfo.setNamedTypeInfo(TInfo); 3668 return NameInfo; 3669 } 3670 3671 case UnqualifiedId::IK_ConstructorName: { 3672 TypeSourceInfo *TInfo; 3673 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3674 if (Ty.isNull()) 3675 return DeclarationNameInfo(); 3676 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3677 Context.getCanonicalType(Ty))); 3678 NameInfo.setLoc(Name.StartLocation); 3679 NameInfo.setNamedTypeInfo(TInfo); 3680 return NameInfo; 3681 } 3682 3683 case UnqualifiedId::IK_ConstructorTemplateId: { 3684 // In well-formed code, we can only have a constructor 3685 // template-id that refers to the current context, so go there 3686 // to find the actual type being constructed. 3687 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3688 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3689 return DeclarationNameInfo(); 3690 3691 // Determine the type of the class being constructed. 3692 QualType CurClassType = Context.getTypeDeclType(CurClass); 3693 3694 // FIXME: Check two things: that the template-id names the same type as 3695 // CurClassType, and that the template-id does not occur when the name 3696 // was qualified. 3697 3698 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3699 Context.getCanonicalType(CurClassType))); 3700 NameInfo.setLoc(Name.StartLocation); 3701 // FIXME: should we retrieve TypeSourceInfo? 3702 NameInfo.setNamedTypeInfo(0); 3703 return NameInfo; 3704 } 3705 3706 case UnqualifiedId::IK_DestructorName: { 3707 TypeSourceInfo *TInfo; 3708 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3709 if (Ty.isNull()) 3710 return DeclarationNameInfo(); 3711 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3712 Context.getCanonicalType(Ty))); 3713 NameInfo.setLoc(Name.StartLocation); 3714 NameInfo.setNamedTypeInfo(TInfo); 3715 return NameInfo; 3716 } 3717 3718 case UnqualifiedId::IK_TemplateId: { 3719 TemplateName TName = Name.TemplateId->Template.get(); 3720 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3721 return Context.getNameForTemplate(TName, TNameLoc); 3722 } 3723 3724 } // switch (Name.getKind()) 3725 3726 llvm_unreachable("Unknown name kind"); 3727} 3728 3729static QualType getCoreType(QualType Ty) { 3730 do { 3731 if (Ty->isPointerType() || Ty->isReferenceType()) 3732 Ty = Ty->getPointeeType(); 3733 else if (Ty->isArrayType()) 3734 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3735 else 3736 return Ty.withoutLocalFastQualifiers(); 3737 } while (true); 3738} 3739 3740/// hasSimilarParameters - Determine whether the C++ functions Declaration 3741/// and Definition have "nearly" matching parameters. This heuristic is 3742/// used to improve diagnostics in the case where an out-of-line function 3743/// definition doesn't match any declaration within the class or namespace. 3744/// Also sets Params to the list of indices to the parameters that differ 3745/// between the declaration and the definition. If hasSimilarParameters 3746/// returns true and Params is empty, then all of the parameters match. 3747static bool hasSimilarParameters(ASTContext &Context, 3748 FunctionDecl *Declaration, 3749 FunctionDecl *Definition, 3750 SmallVectorImpl<unsigned> &Params) { 3751 Params.clear(); 3752 if (Declaration->param_size() != Definition->param_size()) 3753 return false; 3754 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3755 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3756 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3757 3758 // The parameter types are identical 3759 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3760 continue; 3761 3762 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3763 QualType DefParamBaseTy = getCoreType(DefParamTy); 3764 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3765 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3766 3767 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3768 (DeclTyName && DeclTyName == DefTyName)) 3769 Params.push_back(Idx); 3770 else // The two parameters aren't even close 3771 return false; 3772 } 3773 3774 return true; 3775} 3776 3777/// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3778/// declarator needs to be rebuilt in the current instantiation. 3779/// Any bits of declarator which appear before the name are valid for 3780/// consideration here. That's specifically the type in the decl spec 3781/// and the base type in any member-pointer chunks. 3782static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3783 DeclarationName Name) { 3784 // The types we specifically need to rebuild are: 3785 // - typenames, typeofs, and decltypes 3786 // - types which will become injected class names 3787 // Of course, we also need to rebuild any type referencing such a 3788 // type. It's safest to just say "dependent", but we call out a 3789 // few cases here. 3790 3791 DeclSpec &DS = D.getMutableDeclSpec(); 3792 switch (DS.getTypeSpecType()) { 3793 case DeclSpec::TST_typename: 3794 case DeclSpec::TST_typeofType: 3795 case DeclSpec::TST_underlyingType: 3796 case DeclSpec::TST_atomic: { 3797 // Grab the type from the parser. 3798 TypeSourceInfo *TSI = 0; 3799 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3800 if (T.isNull() || !T->isDependentType()) break; 3801 3802 // Make sure there's a type source info. This isn't really much 3803 // of a waste; most dependent types should have type source info 3804 // attached already. 3805 if (!TSI) 3806 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3807 3808 // Rebuild the type in the current instantiation. 3809 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3810 if (!TSI) return true; 3811 3812 // Store the new type back in the decl spec. 3813 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3814 DS.UpdateTypeRep(LocType); 3815 break; 3816 } 3817 3818 case DeclSpec::TST_decltype: 3819 case DeclSpec::TST_typeofExpr: { 3820 Expr *E = DS.getRepAsExpr(); 3821 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3822 if (Result.isInvalid()) return true; 3823 DS.UpdateExprRep(Result.get()); 3824 break; 3825 } 3826 3827 default: 3828 // Nothing to do for these decl specs. 3829 break; 3830 } 3831 3832 // It doesn't matter what order we do this in. 3833 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3834 DeclaratorChunk &Chunk = D.getTypeObject(I); 3835 3836 // The only type information in the declarator which can come 3837 // before the declaration name is the base type of a member 3838 // pointer. 3839 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3840 continue; 3841 3842 // Rebuild the scope specifier in-place. 3843 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3844 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3845 return true; 3846 } 3847 3848 return false; 3849} 3850 3851Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3852 D.setFunctionDefinitionKind(FDK_Declaration); 3853 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 3854 3855 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3856 Dcl && Dcl->getDeclContext()->isFileContext()) 3857 Dcl->setTopLevelDeclInObjCContainer(); 3858 3859 return Dcl; 3860} 3861 3862/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3863/// If T is the name of a class, then each of the following shall have a 3864/// name different from T: 3865/// - every static data member of class T; 3866/// - every member function of class T 3867/// - every member of class T that is itself a type; 3868/// \returns true if the declaration name violates these rules. 3869bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3870 DeclarationNameInfo NameInfo) { 3871 DeclarationName Name = NameInfo.getName(); 3872 3873 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3874 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3875 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3876 return true; 3877 } 3878 3879 return false; 3880} 3881 3882/// \brief Diagnose a declaration whose declarator-id has the given 3883/// nested-name-specifier. 3884/// 3885/// \param SS The nested-name-specifier of the declarator-id. 3886/// 3887/// \param DC The declaration context to which the nested-name-specifier 3888/// resolves. 3889/// 3890/// \param Name The name of the entity being declared. 3891/// 3892/// \param Loc The location of the name of the entity being declared. 3893/// 3894/// \returns true if we cannot safely recover from this error, false otherwise. 3895bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3896 DeclarationName Name, 3897 SourceLocation Loc) { 3898 DeclContext *Cur = CurContext; 3899 while (isa<LinkageSpecDecl>(Cur)) 3900 Cur = Cur->getParent(); 3901 3902 // C++ [dcl.meaning]p1: 3903 // A declarator-id shall not be qualified except for the definition 3904 // of a member function (9.3) or static data member (9.4) outside of 3905 // its class, the definition or explicit instantiation of a function 3906 // or variable member of a namespace outside of its namespace, or the 3907 // definition of an explicit specialization outside of its namespace, 3908 // or the declaration of a friend function that is a member of 3909 // another class or namespace (11.3). [...] 3910 3911 // The user provided a superfluous scope specifier that refers back to the 3912 // class or namespaces in which the entity is already declared. 3913 // 3914 // class X { 3915 // void X::f(); 3916 // }; 3917 if (Cur->Equals(DC)) { 3918 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 3919 : diag::err_member_extra_qualification) 3920 << Name << FixItHint::CreateRemoval(SS.getRange()); 3921 SS.clear(); 3922 return false; 3923 } 3924 3925 // Check whether the qualifying scope encloses the scope of the original 3926 // declaration. 3927 if (!Cur->Encloses(DC)) { 3928 if (Cur->isRecord()) 3929 Diag(Loc, diag::err_member_qualification) 3930 << Name << SS.getRange(); 3931 else if (isa<TranslationUnitDecl>(DC)) 3932 Diag(Loc, diag::err_invalid_declarator_global_scope) 3933 << Name << SS.getRange(); 3934 else if (isa<FunctionDecl>(Cur)) 3935 Diag(Loc, diag::err_invalid_declarator_in_function) 3936 << Name << SS.getRange(); 3937 else 3938 Diag(Loc, diag::err_invalid_declarator_scope) 3939 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3940 3941 return true; 3942 } 3943 3944 if (Cur->isRecord()) { 3945 // Cannot qualify members within a class. 3946 Diag(Loc, diag::err_member_qualification) 3947 << Name << SS.getRange(); 3948 SS.clear(); 3949 3950 // C++ constructors and destructors with incorrect scopes can break 3951 // our AST invariants by having the wrong underlying types. If 3952 // that's the case, then drop this declaration entirely. 3953 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3954 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3955 !Context.hasSameType(Name.getCXXNameType(), 3956 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3957 return true; 3958 3959 return false; 3960 } 3961 3962 // C++11 [dcl.meaning]p1: 3963 // [...] "The nested-name-specifier of the qualified declarator-id shall 3964 // not begin with a decltype-specifer" 3965 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3966 while (SpecLoc.getPrefix()) 3967 SpecLoc = SpecLoc.getPrefix(); 3968 if (dyn_cast_or_null<DecltypeType>( 3969 SpecLoc.getNestedNameSpecifier()->getAsType())) 3970 Diag(Loc, diag::err_decltype_in_declarator) 3971 << SpecLoc.getTypeLoc().getSourceRange(); 3972 3973 return false; 3974} 3975 3976NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 3977 MultiTemplateParamsArg TemplateParamLists) { 3978 // TODO: consider using NameInfo for diagnostic. 3979 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3980 DeclarationName Name = NameInfo.getName(); 3981 3982 // All of these full declarators require an identifier. If it doesn't have 3983 // one, the ParsedFreeStandingDeclSpec action should be used. 3984 if (!Name) { 3985 if (!D.isInvalidType()) // Reject this if we think it is valid. 3986 Diag(D.getDeclSpec().getLocStart(), 3987 diag::err_declarator_need_ident) 3988 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 3989 return 0; 3990 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 3991 return 0; 3992 3993 // The scope passed in may not be a decl scope. Zip up the scope tree until 3994 // we find one that is. 3995 while ((S->getFlags() & Scope::DeclScope) == 0 || 3996 (S->getFlags() & Scope::TemplateParamScope) != 0) 3997 S = S->getParent(); 3998 3999 DeclContext *DC = CurContext; 4000 if (D.getCXXScopeSpec().isInvalid()) 4001 D.setInvalidType(); 4002 else if (D.getCXXScopeSpec().isSet()) { 4003 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4004 UPPC_DeclarationQualifier)) 4005 return 0; 4006 4007 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4008 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4009 if (!DC) { 4010 // If we could not compute the declaration context, it's because the 4011 // declaration context is dependent but does not refer to a class, 4012 // class template, or class template partial specialization. Complain 4013 // and return early, to avoid the coming semantic disaster. 4014 Diag(D.getIdentifierLoc(), 4015 diag::err_template_qualified_declarator_no_match) 4016 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4017 << D.getCXXScopeSpec().getRange(); 4018 return 0; 4019 } 4020 bool IsDependentContext = DC->isDependentContext(); 4021 4022 if (!IsDependentContext && 4023 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4024 return 0; 4025 4026 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4027 Diag(D.getIdentifierLoc(), 4028 diag::err_member_def_undefined_record) 4029 << Name << DC << D.getCXXScopeSpec().getRange(); 4030 D.setInvalidType(); 4031 } else if (!D.getDeclSpec().isFriendSpecified()) { 4032 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4033 Name, D.getIdentifierLoc())) { 4034 if (DC->isRecord()) 4035 return 0; 4036 4037 D.setInvalidType(); 4038 } 4039 } 4040 4041 // Check whether we need to rebuild the type of the given 4042 // declaration in the current instantiation. 4043 if (EnteringContext && IsDependentContext && 4044 TemplateParamLists.size() != 0) { 4045 ContextRAII SavedContext(*this, DC); 4046 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4047 D.setInvalidType(); 4048 } 4049 } 4050 4051 if (DiagnoseClassNameShadow(DC, NameInfo)) 4052 // If this is a typedef, we'll end up spewing multiple diagnostics. 4053 // Just return early; it's safer. 4054 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4055 return 0; 4056 4057 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4058 QualType R = TInfo->getType(); 4059 4060 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4061 UPPC_DeclarationType)) 4062 D.setInvalidType(); 4063 4064 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4065 ForRedeclaration); 4066 4067 // See if this is a redefinition of a variable in the same scope. 4068 if (!D.getCXXScopeSpec().isSet()) { 4069 bool IsLinkageLookup = false; 4070 4071 // If the declaration we're planning to build will be a function 4072 // or object with linkage, then look for another declaration with 4073 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4074 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4075 /* Do nothing*/; 4076 else if (R->isFunctionType()) { 4077 if (CurContext->isFunctionOrMethod() || 4078 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4079 IsLinkageLookup = true; 4080 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 4081 IsLinkageLookup = true; 4082 else if (CurContext->getRedeclContext()->isTranslationUnit() && 4083 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4084 IsLinkageLookup = true; 4085 4086 if (IsLinkageLookup) 4087 Previous.clear(LookupRedeclarationWithLinkage); 4088 4089 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 4090 } else { // Something like "int foo::x;" 4091 LookupQualifiedName(Previous, DC); 4092 4093 // C++ [dcl.meaning]p1: 4094 // When the declarator-id is qualified, the declaration shall refer to a 4095 // previously declared member of the class or namespace to which the 4096 // qualifier refers (or, in the case of a namespace, of an element of the 4097 // inline namespace set of that namespace (7.3.1)) or to a specialization 4098 // thereof; [...] 4099 // 4100 // Note that we already checked the context above, and that we do not have 4101 // enough information to make sure that Previous contains the declaration 4102 // we want to match. For example, given: 4103 // 4104 // class X { 4105 // void f(); 4106 // void f(float); 4107 // }; 4108 // 4109 // void X::f(int) { } // ill-formed 4110 // 4111 // In this case, Previous will point to the overload set 4112 // containing the two f's declared in X, but neither of them 4113 // matches. 4114 4115 // C++ [dcl.meaning]p1: 4116 // [...] the member shall not merely have been introduced by a 4117 // using-declaration in the scope of the class or namespace nominated by 4118 // the nested-name-specifier of the declarator-id. 4119 RemoveUsingDecls(Previous); 4120 } 4121 4122 if (Previous.isSingleResult() && 4123 Previous.getFoundDecl()->isTemplateParameter()) { 4124 // Maybe we will complain about the shadowed template parameter. 4125 if (!D.isInvalidType()) 4126 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4127 Previous.getFoundDecl()); 4128 4129 // Just pretend that we didn't see the previous declaration. 4130 Previous.clear(); 4131 } 4132 4133 // In C++, the previous declaration we find might be a tag type 4134 // (class or enum). In this case, the new declaration will hide the 4135 // tag type. Note that this does does not apply if we're declaring a 4136 // typedef (C++ [dcl.typedef]p4). 4137 if (Previous.isSingleTagDecl() && 4138 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4139 Previous.clear(); 4140 4141 // Check that there are no default arguments other than in the parameters 4142 // of a function declaration (C++ only). 4143 if (getLangOpts().CPlusPlus) 4144 CheckExtraCXXDefaultArguments(D); 4145 4146 NamedDecl *New; 4147 4148 bool AddToScope = true; 4149 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4150 if (TemplateParamLists.size()) { 4151 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4152 return 0; 4153 } 4154 4155 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4156 } else if (R->isFunctionType()) { 4157 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4158 TemplateParamLists, 4159 AddToScope); 4160 } else { 4161 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 4162 TemplateParamLists); 4163 } 4164 4165 if (New == 0) 4166 return 0; 4167 4168 // If this has an identifier and is not an invalid redeclaration or 4169 // function template specialization, add it to the scope stack. 4170 if (New->getDeclName() && AddToScope && 4171 !(D.isRedeclaration() && New->isInvalidDecl())) 4172 PushOnScopeChains(New, S); 4173 4174 return New; 4175} 4176 4177/// Helper method to turn variable array types into constant array 4178/// types in certain situations which would otherwise be errors (for 4179/// GCC compatibility). 4180static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4181 ASTContext &Context, 4182 bool &SizeIsNegative, 4183 llvm::APSInt &Oversized) { 4184 // This method tries to turn a variable array into a constant 4185 // array even when the size isn't an ICE. This is necessary 4186 // for compatibility with code that depends on gcc's buggy 4187 // constant expression folding, like struct {char x[(int)(char*)2];} 4188 SizeIsNegative = false; 4189 Oversized = 0; 4190 4191 if (T->isDependentType()) 4192 return QualType(); 4193 4194 QualifierCollector Qs; 4195 const Type *Ty = Qs.strip(T); 4196 4197 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4198 QualType Pointee = PTy->getPointeeType(); 4199 QualType FixedType = 4200 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4201 Oversized); 4202 if (FixedType.isNull()) return FixedType; 4203 FixedType = Context.getPointerType(FixedType); 4204 return Qs.apply(Context, FixedType); 4205 } 4206 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4207 QualType Inner = PTy->getInnerType(); 4208 QualType FixedType = 4209 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4210 Oversized); 4211 if (FixedType.isNull()) return FixedType; 4212 FixedType = Context.getParenType(FixedType); 4213 return Qs.apply(Context, FixedType); 4214 } 4215 4216 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4217 if (!VLATy) 4218 return QualType(); 4219 // FIXME: We should probably handle this case 4220 if (VLATy->getElementType()->isVariablyModifiedType()) 4221 return QualType(); 4222 4223 llvm::APSInt Res; 4224 if (!VLATy->getSizeExpr() || 4225 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4226 return QualType(); 4227 4228 // Check whether the array size is negative. 4229 if (Res.isSigned() && Res.isNegative()) { 4230 SizeIsNegative = true; 4231 return QualType(); 4232 } 4233 4234 // Check whether the array is too large to be addressed. 4235 unsigned ActiveSizeBits 4236 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4237 Res); 4238 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4239 Oversized = Res; 4240 return QualType(); 4241 } 4242 4243 return Context.getConstantArrayType(VLATy->getElementType(), 4244 Res, ArrayType::Normal, 0); 4245} 4246 4247static void 4248FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4249 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4250 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4251 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4252 DstPTL.getPointeeLoc()); 4253 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4254 return; 4255 } 4256 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4257 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4258 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4259 DstPTL.getInnerLoc()); 4260 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4261 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4262 return; 4263 } 4264 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4265 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4266 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4267 TypeLoc DstElemTL = DstATL.getElementLoc(); 4268 DstElemTL.initializeFullCopy(SrcElemTL); 4269 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4270 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4271 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4272} 4273 4274/// Helper method to turn variable array types into constant array 4275/// types in certain situations which would otherwise be errors (for 4276/// GCC compatibility). 4277static TypeSourceInfo* 4278TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4279 ASTContext &Context, 4280 bool &SizeIsNegative, 4281 llvm::APSInt &Oversized) { 4282 QualType FixedTy 4283 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4284 SizeIsNegative, Oversized); 4285 if (FixedTy.isNull()) 4286 return 0; 4287 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4288 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4289 FixedTInfo->getTypeLoc()); 4290 return FixedTInfo; 4291} 4292 4293/// \brief Register the given locally-scoped extern "C" declaration so 4294/// that it can be found later for redeclarations 4295void 4296Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 4297 const LookupResult &Previous, 4298 Scope *S) { 4299 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 4300 "Decl is not a locally-scoped decl!"); 4301 // Note that we have a locally-scoped external with this name. 4302 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4303 4304 if (!Previous.isSingleResult()) 4305 return; 4306 4307 NamedDecl *PrevDecl = Previous.getFoundDecl(); 4308 4309 // If there was a previous declaration of this entity, it may be in 4310 // our identifier chain. Update the identifier chain with the new 4311 // declaration. 4312 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 4313 // The previous declaration was found on the identifer resolver 4314 // chain, so remove it from its scope. 4315 4316 if (S->isDeclScope(PrevDecl)) { 4317 // Special case for redeclarations in the SAME scope. 4318 // Because this declaration is going to be added to the identifier chain 4319 // later, we should temporarily take it OFF the chain. 4320 IdResolver.RemoveDecl(ND); 4321 4322 } else { 4323 // Find the scope for the original declaration. 4324 while (S && !S->isDeclScope(PrevDecl)) 4325 S = S->getParent(); 4326 } 4327 4328 if (S) 4329 S->RemoveDecl(PrevDecl); 4330 } 4331} 4332 4333llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 4334Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4335 if (ExternalSource) { 4336 // Load locally-scoped external decls from the external source. 4337 SmallVector<NamedDecl *, 4> Decls; 4338 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4339 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4340 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4341 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4342 if (Pos == LocallyScopedExternCDecls.end()) 4343 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4344 } 4345 } 4346 4347 return LocallyScopedExternCDecls.find(Name); 4348} 4349 4350/// \brief Diagnose function specifiers on a declaration of an identifier that 4351/// does not identify a function. 4352void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 4353 // FIXME: We should probably indicate the identifier in question to avoid 4354 // confusion for constructs like "inline int a(), b;" 4355 if (D.getDeclSpec().isInlineSpecified()) 4356 Diag(D.getDeclSpec().getInlineSpecLoc(), 4357 diag::err_inline_non_function); 4358 4359 if (D.getDeclSpec().isVirtualSpecified()) 4360 Diag(D.getDeclSpec().getVirtualSpecLoc(), 4361 diag::err_virtual_non_function); 4362 4363 if (D.getDeclSpec().isExplicitSpecified()) 4364 Diag(D.getDeclSpec().getExplicitSpecLoc(), 4365 diag::err_explicit_non_function); 4366 4367 if (D.getDeclSpec().isNoreturnSpecified()) 4368 Diag(D.getDeclSpec().getNoreturnSpecLoc(), 4369 diag::err_noreturn_non_function); 4370} 4371 4372NamedDecl* 4373Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4374 TypeSourceInfo *TInfo, LookupResult &Previous) { 4375 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4376 if (D.getCXXScopeSpec().isSet()) { 4377 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4378 << D.getCXXScopeSpec().getRange(); 4379 D.setInvalidType(); 4380 // Pretend we didn't see the scope specifier. 4381 DC = CurContext; 4382 Previous.clear(); 4383 } 4384 4385 DiagnoseFunctionSpecifiers(D); 4386 4387 if (D.getDeclSpec().isThreadSpecified()) 4388 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4389 if (D.getDeclSpec().isConstexprSpecified()) 4390 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4391 << 1; 4392 4393 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4394 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4395 << D.getName().getSourceRange(); 4396 return 0; 4397 } 4398 4399 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4400 if (!NewTD) return 0; 4401 4402 // Handle attributes prior to checking for duplicates in MergeVarDecl 4403 ProcessDeclAttributes(S, NewTD, D); 4404 4405 CheckTypedefForVariablyModifiedType(S, NewTD); 4406 4407 bool Redeclaration = D.isRedeclaration(); 4408 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4409 D.setRedeclaration(Redeclaration); 4410 return ND; 4411} 4412 4413void 4414Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4415 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4416 // then it shall have block scope. 4417 // Note that variably modified types must be fixed before merging the decl so 4418 // that redeclarations will match. 4419 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4420 QualType T = TInfo->getType(); 4421 if (T->isVariablyModifiedType()) { 4422 getCurFunction()->setHasBranchProtectedScope(); 4423 4424 if (S->getFnParent() == 0) { 4425 bool SizeIsNegative; 4426 llvm::APSInt Oversized; 4427 TypeSourceInfo *FixedTInfo = 4428 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4429 SizeIsNegative, 4430 Oversized); 4431 if (FixedTInfo) { 4432 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4433 NewTD->setTypeSourceInfo(FixedTInfo); 4434 } else { 4435 if (SizeIsNegative) 4436 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4437 else if (T->isVariableArrayType()) 4438 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4439 else if (Oversized.getBoolValue()) 4440 Diag(NewTD->getLocation(), diag::err_array_too_large) 4441 << Oversized.toString(10); 4442 else 4443 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4444 NewTD->setInvalidDecl(); 4445 } 4446 } 4447 } 4448} 4449 4450 4451/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4452/// declares a typedef-name, either using the 'typedef' type specifier or via 4453/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4454NamedDecl* 4455Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4456 LookupResult &Previous, bool &Redeclaration) { 4457 // Merge the decl with the existing one if appropriate. If the decl is 4458 // in an outer scope, it isn't the same thing. 4459 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4460 /*ExplicitInstantiationOrSpecialization=*/false); 4461 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4462 if (!Previous.empty()) { 4463 Redeclaration = true; 4464 MergeTypedefNameDecl(NewTD, Previous); 4465 } 4466 4467 // If this is the C FILE type, notify the AST context. 4468 if (IdentifierInfo *II = NewTD->getIdentifier()) 4469 if (!NewTD->isInvalidDecl() && 4470 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4471 if (II->isStr("FILE")) 4472 Context.setFILEDecl(NewTD); 4473 else if (II->isStr("jmp_buf")) 4474 Context.setjmp_bufDecl(NewTD); 4475 else if (II->isStr("sigjmp_buf")) 4476 Context.setsigjmp_bufDecl(NewTD); 4477 else if (II->isStr("ucontext_t")) 4478 Context.setucontext_tDecl(NewTD); 4479 } 4480 4481 return NewTD; 4482} 4483 4484/// \brief Determines whether the given declaration is an out-of-scope 4485/// previous declaration. 4486/// 4487/// This routine should be invoked when name lookup has found a 4488/// previous declaration (PrevDecl) that is not in the scope where a 4489/// new declaration by the same name is being introduced. If the new 4490/// declaration occurs in a local scope, previous declarations with 4491/// linkage may still be considered previous declarations (C99 4492/// 6.2.2p4-5, C++ [basic.link]p6). 4493/// 4494/// \param PrevDecl the previous declaration found by name 4495/// lookup 4496/// 4497/// \param DC the context in which the new declaration is being 4498/// declared. 4499/// 4500/// \returns true if PrevDecl is an out-of-scope previous declaration 4501/// for a new delcaration with the same name. 4502static bool 4503isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4504 ASTContext &Context) { 4505 if (!PrevDecl) 4506 return false; 4507 4508 if (!PrevDecl->hasLinkage()) 4509 return false; 4510 4511 if (Context.getLangOpts().CPlusPlus) { 4512 // C++ [basic.link]p6: 4513 // If there is a visible declaration of an entity with linkage 4514 // having the same name and type, ignoring entities declared 4515 // outside the innermost enclosing namespace scope, the block 4516 // scope declaration declares that same entity and receives the 4517 // linkage of the previous declaration. 4518 DeclContext *OuterContext = DC->getRedeclContext(); 4519 if (!OuterContext->isFunctionOrMethod()) 4520 // This rule only applies to block-scope declarations. 4521 return false; 4522 4523 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4524 if (PrevOuterContext->isRecord()) 4525 // We found a member function: ignore it. 4526 return false; 4527 4528 // Find the innermost enclosing namespace for the new and 4529 // previous declarations. 4530 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4531 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4532 4533 // The previous declaration is in a different namespace, so it 4534 // isn't the same function. 4535 if (!OuterContext->Equals(PrevOuterContext)) 4536 return false; 4537 } 4538 4539 return true; 4540} 4541 4542static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4543 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4544 if (!SS.isSet()) return; 4545 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4546} 4547 4548bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4549 QualType type = decl->getType(); 4550 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4551 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4552 // Various kinds of declaration aren't allowed to be __autoreleasing. 4553 unsigned kind = -1U; 4554 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4555 if (var->hasAttr<BlocksAttr>()) 4556 kind = 0; // __block 4557 else if (!var->hasLocalStorage()) 4558 kind = 1; // global 4559 } else if (isa<ObjCIvarDecl>(decl)) { 4560 kind = 3; // ivar 4561 } else if (isa<FieldDecl>(decl)) { 4562 kind = 2; // field 4563 } 4564 4565 if (kind != -1U) { 4566 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4567 << kind; 4568 } 4569 } else if (lifetime == Qualifiers::OCL_None) { 4570 // Try to infer lifetime. 4571 if (!type->isObjCLifetimeType()) 4572 return false; 4573 4574 lifetime = type->getObjCARCImplicitLifetime(); 4575 type = Context.getLifetimeQualifiedType(type, lifetime); 4576 decl->setType(type); 4577 } 4578 4579 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4580 // Thread-local variables cannot have lifetime. 4581 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4582 var->isThreadSpecified()) { 4583 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4584 << var->getType(); 4585 return true; 4586 } 4587 } 4588 4589 return false; 4590} 4591 4592static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4593 // 'weak' only applies to declarations with external linkage. 4594 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4595 if (ND.getLinkage() != ExternalLinkage) { 4596 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4597 ND.dropAttr<WeakAttr>(); 4598 } 4599 } 4600 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4601 if (ND.hasExternalLinkage()) { 4602 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4603 ND.dropAttr<WeakRefAttr>(); 4604 } 4605 } 4606} 4607 4608static bool shouldConsiderLinkage(const VarDecl *VD) { 4609 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4610 if (DC->isFunctionOrMethod()) 4611 return VD->hasExternalStorageAsWritten(); 4612 if (DC->isFileContext()) 4613 return true; 4614 if (DC->isRecord()) 4615 return false; 4616 llvm_unreachable("Unexpected context"); 4617} 4618 4619static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4620 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4621 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4622 return true; 4623 if (DC->isRecord()) 4624 return false; 4625 llvm_unreachable("Unexpected context"); 4626} 4627 4628NamedDecl* 4629Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4630 TypeSourceInfo *TInfo, LookupResult &Previous, 4631 MultiTemplateParamsArg TemplateParamLists) { 4632 QualType R = TInfo->getType(); 4633 DeclarationName Name = GetNameForDeclarator(D).getName(); 4634 4635 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4636 assert(SCSpec != DeclSpec::SCS_typedef && 4637 "Parser allowed 'typedef' as storage class VarDecl."); 4638 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4639 4640 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) 4641 { 4642 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4643 // half array type (unless the cl_khr_fp16 extension is enabled). 4644 if (Context.getBaseElementType(R)->isHalfType()) { 4645 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4646 D.setInvalidType(); 4647 } 4648 } 4649 4650 if (SCSpec == DeclSpec::SCS_mutable) { 4651 // mutable can only appear on non-static class members, so it's always 4652 // an error here 4653 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4654 D.setInvalidType(); 4655 SC = SC_None; 4656 } 4657 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4658 VarDecl::StorageClass SCAsWritten 4659 = StorageClassSpecToVarDeclStorageClass(SCSpec); 4660 4661 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4662 if (!II) { 4663 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4664 << Name; 4665 return 0; 4666 } 4667 4668 DiagnoseFunctionSpecifiers(D); 4669 4670 if (!DC->isRecord() && S->getFnParent() == 0) { 4671 // C99 6.9p2: The storage-class specifiers auto and register shall not 4672 // appear in the declaration specifiers in an external declaration. 4673 if (SC == SC_Auto || SC == SC_Register) { 4674 4675 // If this is a register variable with an asm label specified, then this 4676 // is a GNU extension. 4677 if (SC == SC_Register && D.getAsmLabel()) 4678 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4679 else 4680 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4681 D.setInvalidType(); 4682 } 4683 } 4684 4685 if (getLangOpts().OpenCL) { 4686 // Set up the special work-group-local storage class for variables in the 4687 // OpenCL __local address space. 4688 if (R.getAddressSpace() == LangAS::opencl_local) { 4689 SC = SC_OpenCLWorkGroupLocal; 4690 SCAsWritten = SC_OpenCLWorkGroupLocal; 4691 } 4692 4693 // OpenCL v1.2 s6.9.b p4: 4694 // The sampler type cannot be used with the __local and __global address 4695 // space qualifiers. 4696 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 4697 R.getAddressSpace() == LangAS::opencl_global)) { 4698 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 4699 } 4700 4701 // OpenCL 1.2 spec, p6.9 r: 4702 // The event type cannot be used to declare a program scope variable. 4703 // The event type cannot be used with the __local, __constant and __global 4704 // address space qualifiers. 4705 if (R->isEventT()) { 4706 if (S->getParent() == 0) { 4707 Diag(D.getLocStart(), diag::err_event_t_global_var); 4708 D.setInvalidType(); 4709 } 4710 4711 if (R.getAddressSpace()) { 4712 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 4713 D.setInvalidType(); 4714 } 4715 } 4716 } 4717 4718 bool isExplicitSpecialization = false; 4719 VarDecl *NewVD; 4720 if (!getLangOpts().CPlusPlus) { 4721 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4722 D.getIdentifierLoc(), II, 4723 R, TInfo, SC, SCAsWritten); 4724 4725 if (D.isInvalidType()) 4726 NewVD->setInvalidDecl(); 4727 } else { 4728 if (DC->isRecord() && !CurContext->isRecord()) { 4729 // This is an out-of-line definition of a static data member. 4730 if (SC == SC_Static) { 4731 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4732 diag::err_static_out_of_line) 4733 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4734 } else if (SC == SC_None) 4735 SC = SC_Static; 4736 } 4737 if (SC == SC_Static && CurContext->isRecord()) { 4738 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4739 if (RD->isLocalClass()) 4740 Diag(D.getIdentifierLoc(), 4741 diag::err_static_data_member_not_allowed_in_local_class) 4742 << Name << RD->getDeclName(); 4743 4744 // C++98 [class.union]p1: If a union contains a static data member, 4745 // the program is ill-formed. C++11 drops this restriction. 4746 if (RD->isUnion()) 4747 Diag(D.getIdentifierLoc(), 4748 getLangOpts().CPlusPlus11 4749 ? diag::warn_cxx98_compat_static_data_member_in_union 4750 : diag::ext_static_data_member_in_union) << Name; 4751 // We conservatively disallow static data members in anonymous structs. 4752 else if (!RD->getDeclName()) 4753 Diag(D.getIdentifierLoc(), 4754 diag::err_static_data_member_not_allowed_in_anon_struct) 4755 << Name << RD->isUnion(); 4756 } 4757 } 4758 4759 // Match up the template parameter lists with the scope specifier, then 4760 // determine whether we have a template or a template specialization. 4761 isExplicitSpecialization = false; 4762 bool Invalid = false; 4763 if (TemplateParameterList *TemplateParams 4764 = MatchTemplateParametersToScopeSpecifier( 4765 D.getDeclSpec().getLocStart(), 4766 D.getIdentifierLoc(), 4767 D.getCXXScopeSpec(), 4768 TemplateParamLists.data(), 4769 TemplateParamLists.size(), 4770 /*never a friend*/ false, 4771 isExplicitSpecialization, 4772 Invalid)) { 4773 if (TemplateParams->size() > 0) { 4774 // There is no such thing as a variable template. 4775 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4776 << II 4777 << SourceRange(TemplateParams->getTemplateLoc(), 4778 TemplateParams->getRAngleLoc()); 4779 return 0; 4780 } else { 4781 // There is an extraneous 'template<>' for this variable. Complain 4782 // about it, but allow the declaration of the variable. 4783 Diag(TemplateParams->getTemplateLoc(), 4784 diag::err_template_variable_noparams) 4785 << II 4786 << SourceRange(TemplateParams->getTemplateLoc(), 4787 TemplateParams->getRAngleLoc()); 4788 } 4789 } 4790 4791 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4792 D.getIdentifierLoc(), II, 4793 R, TInfo, SC, SCAsWritten); 4794 4795 // If this decl has an auto type in need of deduction, make a note of the 4796 // Decl so we can diagnose uses of it in its own initializer. 4797 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4798 R->getContainedAutoType()) 4799 ParsingInitForAutoVars.insert(NewVD); 4800 4801 if (D.isInvalidType() || Invalid) 4802 NewVD->setInvalidDecl(); 4803 4804 SetNestedNameSpecifier(NewVD, D); 4805 4806 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4807 NewVD->setTemplateParameterListsInfo(Context, 4808 TemplateParamLists.size(), 4809 TemplateParamLists.data()); 4810 } 4811 4812 if (D.getDeclSpec().isConstexprSpecified()) 4813 NewVD->setConstexpr(true); 4814 } 4815 4816 // Set the lexical context. If the declarator has a C++ scope specifier, the 4817 // lexical context will be different from the semantic context. 4818 NewVD->setLexicalDeclContext(CurContext); 4819 4820 if (D.getDeclSpec().isThreadSpecified()) { 4821 if (NewVD->hasLocalStorage()) 4822 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4823 else if (!Context.getTargetInfo().isTLSSupported()) 4824 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4825 else 4826 NewVD->setThreadSpecified(true); 4827 } 4828 4829 if (D.getDeclSpec().isModulePrivateSpecified()) { 4830 if (isExplicitSpecialization) 4831 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4832 << 2 4833 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4834 else if (NewVD->hasLocalStorage()) 4835 Diag(NewVD->getLocation(), diag::err_module_private_local) 4836 << 0 << NewVD->getDeclName() 4837 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4838 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4839 else 4840 NewVD->setModulePrivate(); 4841 } 4842 4843 // Handle attributes prior to checking for duplicates in MergeVarDecl 4844 ProcessDeclAttributes(S, NewVD, D); 4845 4846 if (NewVD->hasAttrs()) 4847 CheckAlignasUnderalignment(NewVD); 4848 4849 if (getLangOpts().CUDA) { 4850 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 4851 // storage [duration]." 4852 if (SC == SC_None && S->getFnParent() != 0 && 4853 (NewVD->hasAttr<CUDASharedAttr>() || 4854 NewVD->hasAttr<CUDAConstantAttr>())) { 4855 NewVD->setStorageClass(SC_Static); 4856 NewVD->setStorageClassAsWritten(SC_Static); 4857 } 4858 } 4859 4860 // In auto-retain/release, infer strong retension for variables of 4861 // retainable type. 4862 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4863 NewVD->setInvalidDecl(); 4864 4865 // Handle GNU asm-label extension (encoded as an attribute). 4866 if (Expr *E = (Expr*)D.getAsmLabel()) { 4867 // The parser guarantees this is a string. 4868 StringLiteral *SE = cast<StringLiteral>(E); 4869 StringRef Label = SE->getString(); 4870 if (S->getFnParent() != 0) { 4871 switch (SC) { 4872 case SC_None: 4873 case SC_Auto: 4874 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4875 break; 4876 case SC_Register: 4877 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4878 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4879 break; 4880 case SC_Static: 4881 case SC_Extern: 4882 case SC_PrivateExtern: 4883 case SC_OpenCLWorkGroupLocal: 4884 break; 4885 } 4886 } 4887 4888 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4889 Context, Label)); 4890 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4891 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 4892 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 4893 if (I != ExtnameUndeclaredIdentifiers.end()) { 4894 NewVD->addAttr(I->second); 4895 ExtnameUndeclaredIdentifiers.erase(I); 4896 } 4897 } 4898 4899 // Diagnose shadowed variables before filtering for scope. 4900 if (!D.getCXXScopeSpec().isSet()) 4901 CheckShadow(S, NewVD, Previous); 4902 4903 // Don't consider existing declarations that are in a different 4904 // scope and are out-of-semantic-context declarations (if the new 4905 // declaration has linkage). 4906 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewVD), 4907 isExplicitSpecialization); 4908 4909 if (!getLangOpts().CPlusPlus) { 4910 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4911 } else { 4912 // Merge the decl with the existing one if appropriate. 4913 if (!Previous.empty()) { 4914 if (Previous.isSingleResult() && 4915 isa<FieldDecl>(Previous.getFoundDecl()) && 4916 D.getCXXScopeSpec().isSet()) { 4917 // The user tried to define a non-static data member 4918 // out-of-line (C++ [dcl.meaning]p1). 4919 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 4920 << D.getCXXScopeSpec().getRange(); 4921 Previous.clear(); 4922 NewVD->setInvalidDecl(); 4923 } 4924 } else if (D.getCXXScopeSpec().isSet()) { 4925 // No previous declaration in the qualifying scope. 4926 Diag(D.getIdentifierLoc(), diag::err_no_member) 4927 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 4928 << D.getCXXScopeSpec().getRange(); 4929 NewVD->setInvalidDecl(); 4930 } 4931 4932 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 4933 4934 // This is an explicit specialization of a static data member. Check it. 4935 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 4936 CheckMemberSpecialization(NewVD, Previous)) 4937 NewVD->setInvalidDecl(); 4938 } 4939 4940 ProcessPragmaWeak(S, NewVD); 4941 checkAttributesAfterMerging(*this, *NewVD); 4942 4943 // If this is a locally-scoped extern C variable, update the map of 4944 // such variables. 4945 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 4946 !NewVD->isInvalidDecl()) 4947 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 4948 4949 return NewVD; 4950} 4951 4952/// \brief Diagnose variable or built-in function shadowing. Implements 4953/// -Wshadow. 4954/// 4955/// This method is called whenever a VarDecl is added to a "useful" 4956/// scope. 4957/// 4958/// \param S the scope in which the shadowing name is being declared 4959/// \param R the lookup of the name 4960/// 4961void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 4962 // Return if warning is ignored. 4963 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 4964 DiagnosticsEngine::Ignored) 4965 return; 4966 4967 // Don't diagnose declarations at file scope. 4968 if (D->hasGlobalStorage()) 4969 return; 4970 4971 DeclContext *NewDC = D->getDeclContext(); 4972 4973 // Only diagnose if we're shadowing an unambiguous field or variable. 4974 if (R.getResultKind() != LookupResult::Found) 4975 return; 4976 4977 NamedDecl* ShadowedDecl = R.getFoundDecl(); 4978 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 4979 return; 4980 4981 // Fields are not shadowed by variables in C++ static methods. 4982 if (isa<FieldDecl>(ShadowedDecl)) 4983 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 4984 if (MD->isStatic()) 4985 return; 4986 4987 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 4988 if (shadowedVar->isExternC()) { 4989 // For shadowing external vars, make sure that we point to the global 4990 // declaration, not a locally scoped extern declaration. 4991 for (VarDecl::redecl_iterator 4992 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 4993 I != E; ++I) 4994 if (I->isFileVarDecl()) { 4995 ShadowedDecl = *I; 4996 break; 4997 } 4998 } 4999 5000 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5001 5002 // Only warn about certain kinds of shadowing for class members. 5003 if (NewDC && NewDC->isRecord()) { 5004 // In particular, don't warn about shadowing non-class members. 5005 if (!OldDC->isRecord()) 5006 return; 5007 5008 // TODO: should we warn about static data members shadowing 5009 // static data members from base classes? 5010 5011 // TODO: don't diagnose for inaccessible shadowed members. 5012 // This is hard to do perfectly because we might friend the 5013 // shadowing context, but that's just a false negative. 5014 } 5015 5016 // Determine what kind of declaration we're shadowing. 5017 unsigned Kind; 5018 if (isa<RecordDecl>(OldDC)) { 5019 if (isa<FieldDecl>(ShadowedDecl)) 5020 Kind = 3; // field 5021 else 5022 Kind = 2; // static data member 5023 } else if (OldDC->isFileContext()) 5024 Kind = 1; // global 5025 else 5026 Kind = 0; // local 5027 5028 DeclarationName Name = R.getLookupName(); 5029 5030 // Emit warning and note. 5031 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5032 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5033} 5034 5035/// \brief Check -Wshadow without the advantage of a previous lookup. 5036void Sema::CheckShadow(Scope *S, VarDecl *D) { 5037 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5038 DiagnosticsEngine::Ignored) 5039 return; 5040 5041 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5042 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5043 LookupName(R, S); 5044 CheckShadow(S, D, R); 5045} 5046 5047template<typename T> 5048static bool mayConflictWithNonVisibleExternC(const T *ND) { 5049 const DeclContext *DC = ND->getDeclContext(); 5050 if (DC->getRedeclContext()->isTranslationUnit()) 5051 return true; 5052 5053 // We know that is the first decl we see, other than function local 5054 // extern C ones. If this is C++ and the decl is not in a extern C context 5055 // it cannot have C language linkage. Avoid calling isExternC in that case. 5056 // We need to this because of code like 5057 // 5058 // namespace { struct bar {}; } 5059 // auto foo = bar(); 5060 // 5061 // This code runs before the init of foo is set, and therefore before 5062 // the type of foo is known. Not knowing the type we cannot know its linkage 5063 // unless it is in an extern C block. 5064 if (!DC->isExternCContext()) { 5065 const ASTContext &Context = ND->getASTContext(); 5066 if (Context.getLangOpts().CPlusPlus) 5067 return false; 5068 } 5069 5070 return ND->isExternC(); 5071} 5072 5073/// \brief Perform semantic checking on a newly-created variable 5074/// declaration. 5075/// 5076/// This routine performs all of the type-checking required for a 5077/// variable declaration once it has been built. It is used both to 5078/// check variables after they have been parsed and their declarators 5079/// have been translated into a declaration, and to check variables 5080/// that have been instantiated from a template. 5081/// 5082/// Sets NewVD->isInvalidDecl() if an error was encountered. 5083/// 5084/// Returns true if the variable declaration is a redeclaration. 5085bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 5086 LookupResult &Previous) { 5087 // If the decl is already known invalid, don't check it. 5088 if (NewVD->isInvalidDecl()) 5089 return false; 5090 5091 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5092 QualType T = TInfo->getType(); 5093 5094 if (T->isObjCObjectType()) { 5095 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5096 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5097 T = Context.getObjCObjectPointerType(T); 5098 NewVD->setType(T); 5099 } 5100 5101 // Emit an error if an address space was applied to decl with local storage. 5102 // This includes arrays of objects with address space qualifiers, but not 5103 // automatic variables that point to other address spaces. 5104 // ISO/IEC TR 18037 S5.1.2 5105 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5106 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5107 NewVD->setInvalidDecl(); 5108 return false; 5109 } 5110 5111 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5112 // scope. 5113 if ((getLangOpts().OpenCLVersion >= 120) 5114 && NewVD->isStaticLocal()) { 5115 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5116 NewVD->setInvalidDecl(); 5117 return false; 5118 } 5119 5120 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5121 && !NewVD->hasAttr<BlocksAttr>()) { 5122 if (getLangOpts().getGC() != LangOptions::NonGC) 5123 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5124 else { 5125 assert(!getLangOpts().ObjCAutoRefCount); 5126 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5127 } 5128 } 5129 5130 bool isVM = T->isVariablyModifiedType(); 5131 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5132 NewVD->hasAttr<BlocksAttr>()) 5133 getCurFunction()->setHasBranchProtectedScope(); 5134 5135 if ((isVM && NewVD->hasLinkage()) || 5136 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5137 bool SizeIsNegative; 5138 llvm::APSInt Oversized; 5139 TypeSourceInfo *FixedTInfo = 5140 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5141 SizeIsNegative, Oversized); 5142 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5143 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5144 // FIXME: This won't give the correct result for 5145 // int a[10][n]; 5146 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5147 5148 if (NewVD->isFileVarDecl()) 5149 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5150 << SizeRange; 5151 else if (NewVD->getStorageClass() == SC_Static) 5152 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5153 << SizeRange; 5154 else 5155 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5156 << SizeRange; 5157 NewVD->setInvalidDecl(); 5158 return false; 5159 } 5160 5161 if (FixedTInfo == 0) { 5162 if (NewVD->isFileVarDecl()) 5163 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5164 else 5165 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5166 NewVD->setInvalidDecl(); 5167 return false; 5168 } 5169 5170 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5171 NewVD->setType(FixedTInfo->getType()); 5172 NewVD->setTypeSourceInfo(FixedTInfo); 5173 } 5174 5175 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewVD)) { 5176 // Since we did not find anything by this name, look for a non-visible 5177 // extern "C" declaration with the same name. 5178 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 5179 = findLocallyScopedExternCDecl(NewVD->getDeclName()); 5180 if (Pos != LocallyScopedExternCDecls.end()) 5181 Previous.addDecl(Pos->second); 5182 } 5183 5184 // Filter out any non-conflicting previous declarations. 5185 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5186 5187 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 5188 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5189 << T; 5190 NewVD->setInvalidDecl(); 5191 return false; 5192 } 5193 5194 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5195 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5196 NewVD->setInvalidDecl(); 5197 return false; 5198 } 5199 5200 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5201 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5202 NewVD->setInvalidDecl(); 5203 return false; 5204 } 5205 5206 if (NewVD->isConstexpr() && !T->isDependentType() && 5207 RequireLiteralType(NewVD->getLocation(), T, 5208 diag::err_constexpr_var_non_literal)) { 5209 NewVD->setInvalidDecl(); 5210 return false; 5211 } 5212 5213 if (!Previous.empty()) { 5214 MergeVarDecl(NewVD, Previous); 5215 return true; 5216 } 5217 return false; 5218} 5219 5220/// \brief Data used with FindOverriddenMethod 5221struct FindOverriddenMethodData { 5222 Sema *S; 5223 CXXMethodDecl *Method; 5224}; 5225 5226/// \brief Member lookup function that determines whether a given C++ 5227/// method overrides a method in a base class, to be used with 5228/// CXXRecordDecl::lookupInBases(). 5229static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5230 CXXBasePath &Path, 5231 void *UserData) { 5232 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5233 5234 FindOverriddenMethodData *Data 5235 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5236 5237 DeclarationName Name = Data->Method->getDeclName(); 5238 5239 // FIXME: Do we care about other names here too? 5240 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5241 // We really want to find the base class destructor here. 5242 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5243 CanQualType CT = Data->S->Context.getCanonicalType(T); 5244 5245 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5246 } 5247 5248 for (Path.Decls = BaseRecord->lookup(Name); 5249 !Path.Decls.empty(); 5250 Path.Decls = Path.Decls.slice(1)) { 5251 NamedDecl *D = Path.Decls.front(); 5252 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5253 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5254 return true; 5255 } 5256 } 5257 5258 return false; 5259} 5260 5261namespace { 5262 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5263} 5264/// \brief Report an error regarding overriding, along with any relevant 5265/// overriden methods. 5266/// 5267/// \param DiagID the primary error to report. 5268/// \param MD the overriding method. 5269/// \param OEK which overrides to include as notes. 5270static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 5271 OverrideErrorKind OEK = OEK_All) { 5272 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 5273 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5274 E = MD->end_overridden_methods(); 5275 I != E; ++I) { 5276 // This check (& the OEK parameter) could be replaced by a predicate, but 5277 // without lambdas that would be overkill. This is still nicer than writing 5278 // out the diag loop 3 times. 5279 if ((OEK == OEK_All) || 5280 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 5281 (OEK == OEK_Deleted && (*I)->isDeleted())) 5282 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 5283 } 5284} 5285 5286/// AddOverriddenMethods - See if a method overrides any in the base classes, 5287/// and if so, check that it's a valid override and remember it. 5288bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5289 // Look for virtual methods in base classes that this method might override. 5290 CXXBasePaths Paths; 5291 FindOverriddenMethodData Data; 5292 Data.Method = MD; 5293 Data.S = this; 5294 bool hasDeletedOverridenMethods = false; 5295 bool hasNonDeletedOverridenMethods = false; 5296 bool AddedAny = false; 5297 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 5298 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 5299 E = Paths.found_decls_end(); I != E; ++I) { 5300 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 5301 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 5302 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 5303 !CheckOverridingFunctionAttributes(MD, OldMD) && 5304 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 5305 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 5306 hasDeletedOverridenMethods |= OldMD->isDeleted(); 5307 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 5308 AddedAny = true; 5309 } 5310 } 5311 } 5312 } 5313 5314 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 5315 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 5316 } 5317 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 5318 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 5319 } 5320 5321 return AddedAny; 5322} 5323 5324namespace { 5325 // Struct for holding all of the extra arguments needed by 5326 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 5327 struct ActOnFDArgs { 5328 Scope *S; 5329 Declarator &D; 5330 MultiTemplateParamsArg TemplateParamLists; 5331 bool AddToScope; 5332 }; 5333} 5334 5335namespace { 5336 5337// Callback to only accept typo corrections that have a non-zero edit distance. 5338// Also only accept corrections that have the same parent decl. 5339class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 5340 public: 5341 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 5342 CXXRecordDecl *Parent) 5343 : Context(Context), OriginalFD(TypoFD), 5344 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 5345 5346 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5347 if (candidate.getEditDistance() == 0) 5348 return false; 5349 5350 SmallVector<unsigned, 1> MismatchedParams; 5351 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 5352 CDeclEnd = candidate.end(); 5353 CDecl != CDeclEnd; ++CDecl) { 5354 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5355 5356 if (FD && !FD->hasBody() && 5357 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 5358 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5359 CXXRecordDecl *Parent = MD->getParent(); 5360 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 5361 return true; 5362 } else if (!ExpectedParent) { 5363 return true; 5364 } 5365 } 5366 } 5367 5368 return false; 5369 } 5370 5371 private: 5372 ASTContext &Context; 5373 FunctionDecl *OriginalFD; 5374 CXXRecordDecl *ExpectedParent; 5375}; 5376 5377} 5378 5379/// \brief Generate diagnostics for an invalid function redeclaration. 5380/// 5381/// This routine handles generating the diagnostic messages for an invalid 5382/// function redeclaration, including finding possible similar declarations 5383/// or performing typo correction if there are no previous declarations with 5384/// the same name. 5385/// 5386/// Returns a NamedDecl iff typo correction was performed and substituting in 5387/// the new declaration name does not cause new errors. 5388static NamedDecl* DiagnoseInvalidRedeclaration( 5389 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 5390 ActOnFDArgs &ExtraArgs) { 5391 NamedDecl *Result = NULL; 5392 DeclarationName Name = NewFD->getDeclName(); 5393 DeclContext *NewDC = NewFD->getDeclContext(); 5394 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 5395 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5396 SmallVector<unsigned, 1> MismatchedParams; 5397 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 5398 TypoCorrection Correction; 5399 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 5400 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 5401 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 5402 : diag::err_member_def_does_not_match; 5403 5404 NewFD->setInvalidDecl(); 5405 SemaRef.LookupQualifiedName(Prev, NewDC); 5406 assert(!Prev.isAmbiguous() && 5407 "Cannot have an ambiguity in previous-declaration lookup"); 5408 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 5409 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 5410 MD ? MD->getParent() : 0); 5411 if (!Prev.empty()) { 5412 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 5413 Func != FuncEnd; ++Func) { 5414 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 5415 if (FD && 5416 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5417 // Add 1 to the index so that 0 can mean the mismatch didn't 5418 // involve a parameter 5419 unsigned ParamNum = 5420 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 5421 NearMatches.push_back(std::make_pair(FD, ParamNum)); 5422 } 5423 } 5424 // If the qualified name lookup yielded nothing, try typo correction 5425 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 5426 Prev.getLookupKind(), 0, 0, 5427 Validator, NewDC))) { 5428 // Trap errors. 5429 Sema::SFINAETrap Trap(SemaRef); 5430 5431 // Set up everything for the call to ActOnFunctionDeclarator 5432 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 5433 ExtraArgs.D.getIdentifierLoc()); 5434 Previous.clear(); 5435 Previous.setLookupName(Correction.getCorrection()); 5436 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 5437 CDeclEnd = Correction.end(); 5438 CDecl != CDeclEnd; ++CDecl) { 5439 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 5440 if (FD && !FD->hasBody() && 5441 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 5442 Previous.addDecl(FD); 5443 } 5444 } 5445 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 5446 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 5447 // pieces need to verify the typo-corrected C++ declaraction and hopefully 5448 // eliminate the need for the parameter pack ExtraArgs. 5449 Result = SemaRef.ActOnFunctionDeclarator( 5450 ExtraArgs.S, ExtraArgs.D, 5451 Correction.getCorrectionDecl()->getDeclContext(), 5452 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 5453 ExtraArgs.AddToScope); 5454 if (Trap.hasErrorOccurred()) { 5455 // Pretend the typo correction never occurred 5456 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 5457 ExtraArgs.D.getIdentifierLoc()); 5458 ExtraArgs.D.setRedeclaration(wasRedeclaration); 5459 Previous.clear(); 5460 Previous.setLookupName(Name); 5461 Result = NULL; 5462 } else { 5463 for (LookupResult::iterator Func = Previous.begin(), 5464 FuncEnd = Previous.end(); 5465 Func != FuncEnd; ++Func) { 5466 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 5467 NearMatches.push_back(std::make_pair(FD, 0)); 5468 } 5469 } 5470 if (NearMatches.empty()) { 5471 // Ignore the correction if it didn't yield any close FunctionDecl matches 5472 Correction = TypoCorrection(); 5473 } else { 5474 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 5475 : diag::err_member_def_does_not_match_suggest; 5476 } 5477 } 5478 5479 if (Correction) { 5480 // FIXME: use Correction.getCorrectionRange() instead of computing the range 5481 // here. This requires passing in the CXXScopeSpec to CorrectTypo which in 5482 // turn causes the correction to fully qualify the name. If we fix 5483 // CorrectTypo to minimally qualify then this change should be good. 5484 SourceRange FixItLoc(NewFD->getLocation()); 5485 CXXScopeSpec &SS = ExtraArgs.D.getCXXScopeSpec(); 5486 if (Correction.getCorrectionSpecifier() && SS.isValid()) 5487 FixItLoc.setBegin(SS.getBeginLoc()); 5488 SemaRef.Diag(NewFD->getLocStart(), DiagMsg) 5489 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 5490 << FixItHint::CreateReplacement( 5491 FixItLoc, Correction.getAsString(SemaRef.getLangOpts())); 5492 } else { 5493 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 5494 << Name << NewDC << NewFD->getLocation(); 5495 } 5496 5497 bool NewFDisConst = false; 5498 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 5499 NewFDisConst = NewMD->isConst(); 5500 5501 for (SmallVector<std::pair<FunctionDecl *, unsigned>, 1>::iterator 5502 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 5503 NearMatch != NearMatchEnd; ++NearMatch) { 5504 FunctionDecl *FD = NearMatch->first; 5505 bool FDisConst = false; 5506 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 5507 FDisConst = MD->isConst(); 5508 5509 if (unsigned Idx = NearMatch->second) { 5510 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 5511 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 5512 if (Loc.isInvalid()) Loc = FD->getLocation(); 5513 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 5514 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 5515 } else if (Correction) { 5516 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 5517 << Correction.getQuoted(SemaRef.getLangOpts()); 5518 } else if (FDisConst != NewFDisConst) { 5519 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 5520 << NewFDisConst << FD->getSourceRange().getEnd(); 5521 } else 5522 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 5523 } 5524 return Result; 5525} 5526 5527static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 5528 Declarator &D) { 5529 switch (D.getDeclSpec().getStorageClassSpec()) { 5530 default: llvm_unreachable("Unknown storage class!"); 5531 case DeclSpec::SCS_auto: 5532 case DeclSpec::SCS_register: 5533 case DeclSpec::SCS_mutable: 5534 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5535 diag::err_typecheck_sclass_func); 5536 D.setInvalidType(); 5537 break; 5538 case DeclSpec::SCS_unspecified: break; 5539 case DeclSpec::SCS_extern: return SC_Extern; 5540 case DeclSpec::SCS_static: { 5541 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 5542 // C99 6.7.1p5: 5543 // The declaration of an identifier for a function that has 5544 // block scope shall have no explicit storage-class specifier 5545 // other than extern 5546 // See also (C++ [dcl.stc]p4). 5547 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5548 diag::err_static_block_func); 5549 break; 5550 } else 5551 return SC_Static; 5552 } 5553 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5554 } 5555 5556 // No explicit storage class has already been returned 5557 return SC_None; 5558} 5559 5560static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 5561 DeclContext *DC, QualType &R, 5562 TypeSourceInfo *TInfo, 5563 FunctionDecl::StorageClass SC, 5564 bool &IsVirtualOkay) { 5565 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 5566 DeclarationName Name = NameInfo.getName(); 5567 5568 FunctionDecl *NewFD = 0; 5569 bool isInline = D.getDeclSpec().isInlineSpecified(); 5570 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 5571 FunctionDecl::StorageClass SCAsWritten 5572 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 5573 5574 if (!SemaRef.getLangOpts().CPlusPlus) { 5575 // Determine whether the function was written with a 5576 // prototype. This true when: 5577 // - there is a prototype in the declarator, or 5578 // - the type R of the function is some kind of typedef or other reference 5579 // to a type name (which eventually refers to a function type). 5580 bool HasPrototype = 5581 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 5582 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 5583 5584 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 5585 D.getLocStart(), NameInfo, R, 5586 TInfo, SC, SCAsWritten, isInline, 5587 HasPrototype); 5588 if (D.isInvalidType()) 5589 NewFD->setInvalidDecl(); 5590 5591 // Set the lexical context. 5592 NewFD->setLexicalDeclContext(SemaRef.CurContext); 5593 5594 return NewFD; 5595 } 5596 5597 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5598 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5599 5600 // Check that the return type is not an abstract class type. 5601 // For record types, this is done by the AbstractClassUsageDiagnoser once 5602 // the class has been completely parsed. 5603 if (!DC->isRecord() && 5604 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 5605 R->getAs<FunctionType>()->getResultType(), 5606 diag::err_abstract_type_in_decl, 5607 SemaRef.AbstractReturnType)) 5608 D.setInvalidType(); 5609 5610 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 5611 // This is a C++ constructor declaration. 5612 assert(DC->isRecord() && 5613 "Constructors can only be declared in a member context"); 5614 5615 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 5616 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5617 D.getLocStart(), NameInfo, 5618 R, TInfo, isExplicit, isInline, 5619 /*isImplicitlyDeclared=*/false, 5620 isConstexpr); 5621 5622 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5623 // This is a C++ destructor declaration. 5624 if (DC->isRecord()) { 5625 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 5626 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 5627 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 5628 SemaRef.Context, Record, 5629 D.getLocStart(), 5630 NameInfo, R, TInfo, isInline, 5631 /*isImplicitlyDeclared=*/false); 5632 5633 // If the class is complete, then we now create the implicit exception 5634 // specification. If the class is incomplete or dependent, we can't do 5635 // it yet. 5636 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 5637 Record->getDefinition() && !Record->isBeingDefined() && 5638 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 5639 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 5640 } 5641 5642 IsVirtualOkay = true; 5643 return NewDD; 5644 5645 } else { 5646 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 5647 D.setInvalidType(); 5648 5649 // Create a FunctionDecl to satisfy the function definition parsing 5650 // code path. 5651 return FunctionDecl::Create(SemaRef.Context, DC, 5652 D.getLocStart(), 5653 D.getIdentifierLoc(), Name, R, TInfo, 5654 SC, SCAsWritten, isInline, 5655 /*hasPrototype=*/true, isConstexpr); 5656 } 5657 5658 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 5659 if (!DC->isRecord()) { 5660 SemaRef.Diag(D.getIdentifierLoc(), 5661 diag::err_conv_function_not_member); 5662 return 0; 5663 } 5664 5665 SemaRef.CheckConversionDeclarator(D, R, SC); 5666 IsVirtualOkay = true; 5667 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5668 D.getLocStart(), NameInfo, 5669 R, TInfo, isInline, isExplicit, 5670 isConstexpr, SourceLocation()); 5671 5672 } else if (DC->isRecord()) { 5673 // If the name of the function is the same as the name of the record, 5674 // then this must be an invalid constructor that has a return type. 5675 // (The parser checks for a return type and makes the declarator a 5676 // constructor if it has no return type). 5677 if (Name.getAsIdentifierInfo() && 5678 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 5679 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 5680 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5681 << SourceRange(D.getIdentifierLoc()); 5682 return 0; 5683 } 5684 5685 bool isStatic = SC == SC_Static; 5686 5687 // [class.free]p1: 5688 // Any allocation function for a class T is a static member 5689 // (even if not explicitly declared static). 5690 if (Name.getCXXOverloadedOperator() == OO_New || 5691 Name.getCXXOverloadedOperator() == OO_Array_New) 5692 isStatic = true; 5693 5694 // [class.free]p6 Any deallocation function for a class X is a static member 5695 // (even if not explicitly declared static). 5696 if (Name.getCXXOverloadedOperator() == OO_Delete || 5697 Name.getCXXOverloadedOperator() == OO_Array_Delete) 5698 isStatic = true; 5699 5700 IsVirtualOkay = !isStatic; 5701 5702 // This is a C++ method declaration. 5703 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 5704 D.getLocStart(), NameInfo, R, 5705 TInfo, isStatic, SCAsWritten, isInline, 5706 isConstexpr, SourceLocation()); 5707 5708 } else { 5709 // Determine whether the function was written with a 5710 // prototype. This true when: 5711 // - we're in C++ (where every function has a prototype), 5712 return FunctionDecl::Create(SemaRef.Context, DC, 5713 D.getLocStart(), 5714 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 5715 true/*HasPrototype*/, isConstexpr); 5716 } 5717} 5718 5719void Sema::checkVoidParamDecl(ParmVarDecl *Param) { 5720 // In C++, the empty parameter-type-list must be spelled "void"; a 5721 // typedef of void is not permitted. 5722 if (getLangOpts().CPlusPlus && 5723 Param->getType().getUnqualifiedType() != Context.VoidTy) { 5724 bool IsTypeAlias = false; 5725 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 5726 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 5727 else if (const TemplateSpecializationType *TST = 5728 Param->getType()->getAs<TemplateSpecializationType>()) 5729 IsTypeAlias = TST->isTypeAlias(); 5730 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 5731 << IsTypeAlias; 5732 } 5733} 5734 5735NamedDecl* 5736Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5737 TypeSourceInfo *TInfo, LookupResult &Previous, 5738 MultiTemplateParamsArg TemplateParamLists, 5739 bool &AddToScope) { 5740 QualType R = TInfo->getType(); 5741 5742 assert(R.getTypePtr()->isFunctionType()); 5743 5744 // TODO: consider using NameInfo for diagnostic. 5745 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5746 DeclarationName Name = NameInfo.getName(); 5747 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 5748 5749 if (D.getDeclSpec().isThreadSpecified()) 5750 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5751 5752 // Do not allow returning a objc interface by-value. 5753 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 5754 Diag(D.getIdentifierLoc(), 5755 diag::err_object_cannot_be_passed_returned_by_value) << 0 5756 << R->getAs<FunctionType>()->getResultType() 5757 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 5758 5759 QualType T = R->getAs<FunctionType>()->getResultType(); 5760 T = Context.getObjCObjectPointerType(T); 5761 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 5762 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 5763 R = Context.getFunctionType(T, 5764 ArrayRef<QualType>(FPT->arg_type_begin(), 5765 FPT->getNumArgs()), 5766 EPI); 5767 } 5768 else if (isa<FunctionNoProtoType>(R)) 5769 R = Context.getFunctionNoProtoType(T); 5770 } 5771 5772 bool isFriend = false; 5773 FunctionTemplateDecl *FunctionTemplate = 0; 5774 bool isExplicitSpecialization = false; 5775 bool isFunctionTemplateSpecialization = false; 5776 5777 bool isDependentClassScopeExplicitSpecialization = false; 5778 bool HasExplicitTemplateArgs = false; 5779 TemplateArgumentListInfo TemplateArgs; 5780 5781 bool isVirtualOkay = false; 5782 5783 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 5784 isVirtualOkay); 5785 if (!NewFD) return 0; 5786 5787 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 5788 NewFD->setTopLevelDeclInObjCContainer(); 5789 5790 if (getLangOpts().CPlusPlus) { 5791 bool isInline = D.getDeclSpec().isInlineSpecified(); 5792 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5793 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 5794 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 5795 isFriend = D.getDeclSpec().isFriendSpecified(); 5796 if (isFriend && !isInline && D.isFunctionDefinition()) { 5797 // C++ [class.friend]p5 5798 // A function can be defined in a friend declaration of a 5799 // class . . . . Such a function is implicitly inline. 5800 NewFD->setImplicitlyInline(); 5801 } 5802 5803 // If this is a method defined in an __interface, and is not a constructor 5804 // or an overloaded operator, then set the pure flag (isVirtual will already 5805 // return true). 5806 if (const CXXRecordDecl *Parent = 5807 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 5808 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 5809 NewFD->setPure(true); 5810 } 5811 5812 SetNestedNameSpecifier(NewFD, D); 5813 isExplicitSpecialization = false; 5814 isFunctionTemplateSpecialization = false; 5815 if (D.isInvalidType()) 5816 NewFD->setInvalidDecl(); 5817 5818 // Set the lexical context. If the declarator has a C++ 5819 // scope specifier, or is the object of a friend declaration, the 5820 // lexical context will be different from the semantic context. 5821 NewFD->setLexicalDeclContext(CurContext); 5822 5823 // Match up the template parameter lists with the scope specifier, then 5824 // determine whether we have a template or a template specialization. 5825 bool Invalid = false; 5826 if (TemplateParameterList *TemplateParams 5827 = MatchTemplateParametersToScopeSpecifier( 5828 D.getDeclSpec().getLocStart(), 5829 D.getIdentifierLoc(), 5830 D.getCXXScopeSpec(), 5831 TemplateParamLists.data(), 5832 TemplateParamLists.size(), 5833 isFriend, 5834 isExplicitSpecialization, 5835 Invalid)) { 5836 if (TemplateParams->size() > 0) { 5837 // This is a function template 5838 5839 // Check that we can declare a template here. 5840 if (CheckTemplateDeclScope(S, TemplateParams)) 5841 return 0; 5842 5843 // A destructor cannot be a template. 5844 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5845 Diag(NewFD->getLocation(), diag::err_destructor_template); 5846 return 0; 5847 } 5848 5849 // If we're adding a template to a dependent context, we may need to 5850 // rebuilding some of the types used within the template parameter list, 5851 // now that we know what the current instantiation is. 5852 if (DC->isDependentContext()) { 5853 ContextRAII SavedContext(*this, DC); 5854 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 5855 Invalid = true; 5856 } 5857 5858 5859 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 5860 NewFD->getLocation(), 5861 Name, TemplateParams, 5862 NewFD); 5863 FunctionTemplate->setLexicalDeclContext(CurContext); 5864 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 5865 5866 // For source fidelity, store the other template param lists. 5867 if (TemplateParamLists.size() > 1) { 5868 NewFD->setTemplateParameterListsInfo(Context, 5869 TemplateParamLists.size() - 1, 5870 TemplateParamLists.data()); 5871 } 5872 } else { 5873 // This is a function template specialization. 5874 isFunctionTemplateSpecialization = true; 5875 // For source fidelity, store all the template param lists. 5876 NewFD->setTemplateParameterListsInfo(Context, 5877 TemplateParamLists.size(), 5878 TemplateParamLists.data()); 5879 5880 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 5881 if (isFriend) { 5882 // We want to remove the "template<>", found here. 5883 SourceRange RemoveRange = TemplateParams->getSourceRange(); 5884 5885 // If we remove the template<> and the name is not a 5886 // template-id, we're actually silently creating a problem: 5887 // the friend declaration will refer to an untemplated decl, 5888 // and clearly the user wants a template specialization. So 5889 // we need to insert '<>' after the name. 5890 SourceLocation InsertLoc; 5891 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5892 InsertLoc = D.getName().getSourceRange().getEnd(); 5893 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 5894 } 5895 5896 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 5897 << Name << RemoveRange 5898 << FixItHint::CreateRemoval(RemoveRange) 5899 << FixItHint::CreateInsertion(InsertLoc, "<>"); 5900 } 5901 } 5902 } 5903 else { 5904 // All template param lists were matched against the scope specifier: 5905 // this is NOT (an explicit specialization of) a template. 5906 if (TemplateParamLists.size() > 0) 5907 // For source fidelity, store all the template param lists. 5908 NewFD->setTemplateParameterListsInfo(Context, 5909 TemplateParamLists.size(), 5910 TemplateParamLists.data()); 5911 } 5912 5913 if (Invalid) { 5914 NewFD->setInvalidDecl(); 5915 if (FunctionTemplate) 5916 FunctionTemplate->setInvalidDecl(); 5917 } 5918 5919 // C++ [dcl.fct.spec]p5: 5920 // The virtual specifier shall only be used in declarations of 5921 // nonstatic class member functions that appear within a 5922 // member-specification of a class declaration; see 10.3. 5923 // 5924 if (isVirtual && !NewFD->isInvalidDecl()) { 5925 if (!isVirtualOkay) { 5926 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5927 diag::err_virtual_non_function); 5928 } else if (!CurContext->isRecord()) { 5929 // 'virtual' was specified outside of the class. 5930 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5931 diag::err_virtual_out_of_class) 5932 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5933 } else if (NewFD->getDescribedFunctionTemplate()) { 5934 // C++ [temp.mem]p3: 5935 // A member function template shall not be virtual. 5936 Diag(D.getDeclSpec().getVirtualSpecLoc(), 5937 diag::err_virtual_member_function_template) 5938 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 5939 } else { 5940 // Okay: Add virtual to the method. 5941 NewFD->setVirtualAsWritten(true); 5942 } 5943 } 5944 5945 // C++ [dcl.fct.spec]p3: 5946 // The inline specifier shall not appear on a block scope function 5947 // declaration. 5948 if (isInline && !NewFD->isInvalidDecl()) { 5949 if (CurContext->isFunctionOrMethod()) { 5950 // 'inline' is not allowed on block scope function declaration. 5951 Diag(D.getDeclSpec().getInlineSpecLoc(), 5952 diag::err_inline_declaration_block_scope) << Name 5953 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5954 } 5955 } 5956 5957 // C++ [dcl.fct.spec]p6: 5958 // The explicit specifier shall be used only in the declaration of a 5959 // constructor or conversion function within its class definition; 5960 // see 12.3.1 and 12.3.2. 5961 if (isExplicit && !NewFD->isInvalidDecl()) { 5962 if (!CurContext->isRecord()) { 5963 // 'explicit' was specified outside of the class. 5964 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5965 diag::err_explicit_out_of_class) 5966 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5967 } else if (!isa<CXXConstructorDecl>(NewFD) && 5968 !isa<CXXConversionDecl>(NewFD)) { 5969 // 'explicit' was specified on a function that wasn't a constructor 5970 // or conversion function. 5971 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5972 diag::err_explicit_non_ctor_or_conv_function) 5973 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 5974 } 5975 } 5976 5977 if (isConstexpr) { 5978 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 5979 // are implicitly inline. 5980 NewFD->setImplicitlyInline(); 5981 5982 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 5983 // be either constructors or to return a literal type. Therefore, 5984 // destructors cannot be declared constexpr. 5985 if (isa<CXXDestructorDecl>(NewFD)) 5986 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 5987 } 5988 5989 // If __module_private__ was specified, mark the function accordingly. 5990 if (D.getDeclSpec().isModulePrivateSpecified()) { 5991 if (isFunctionTemplateSpecialization) { 5992 SourceLocation ModulePrivateLoc 5993 = D.getDeclSpec().getModulePrivateSpecLoc(); 5994 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 5995 << 0 5996 << FixItHint::CreateRemoval(ModulePrivateLoc); 5997 } else { 5998 NewFD->setModulePrivate(); 5999 if (FunctionTemplate) 6000 FunctionTemplate->setModulePrivate(); 6001 } 6002 } 6003 6004 if (isFriend) { 6005 // For now, claim that the objects have no previous declaration. 6006 if (FunctionTemplate) { 6007 FunctionTemplate->setObjectOfFriendDecl(false); 6008 FunctionTemplate->setAccess(AS_public); 6009 } 6010 NewFD->setObjectOfFriendDecl(false); 6011 NewFD->setAccess(AS_public); 6012 } 6013 6014 // If a function is defined as defaulted or deleted, mark it as such now. 6015 switch (D.getFunctionDefinitionKind()) { 6016 case FDK_Declaration: 6017 case FDK_Definition: 6018 break; 6019 6020 case FDK_Defaulted: 6021 NewFD->setDefaulted(); 6022 break; 6023 6024 case FDK_Deleted: 6025 NewFD->setDeletedAsWritten(); 6026 break; 6027 } 6028 6029 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6030 D.isFunctionDefinition()) { 6031 // C++ [class.mfct]p2: 6032 // A member function may be defined (8.4) in its class definition, in 6033 // which case it is an inline member function (7.1.2) 6034 NewFD->setImplicitlyInline(); 6035 } 6036 6037 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6038 !CurContext->isRecord()) { 6039 // C++ [class.static]p1: 6040 // A data or function member of a class may be declared static 6041 // in a class definition, in which case it is a static member of 6042 // the class. 6043 6044 // Complain about the 'static' specifier if it's on an out-of-line 6045 // member function definition. 6046 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6047 diag::err_static_out_of_line) 6048 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6049 } 6050 6051 // C++11 [except.spec]p15: 6052 // A deallocation function with no exception-specification is treated 6053 // as if it were specified with noexcept(true). 6054 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6055 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6056 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6057 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6058 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6059 EPI.ExceptionSpecType = EST_BasicNoexcept; 6060 NewFD->setType(Context.getFunctionType(FPT->getResultType(), 6061 ArrayRef<QualType>(FPT->arg_type_begin(), 6062 FPT->getNumArgs()), 6063 EPI)); 6064 } 6065 } 6066 6067 // Filter out previous declarations that don't match the scope. 6068 FilterLookupForScope(Previous, DC, S, shouldConsiderLinkage(NewFD), 6069 isExplicitSpecialization || 6070 isFunctionTemplateSpecialization); 6071 6072 // Handle GNU asm-label extension (encoded as an attribute). 6073 if (Expr *E = (Expr*) D.getAsmLabel()) { 6074 // The parser guarantees this is a string. 6075 StringLiteral *SE = cast<StringLiteral>(E); 6076 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6077 SE->getString())); 6078 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6079 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6080 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6081 if (I != ExtnameUndeclaredIdentifiers.end()) { 6082 NewFD->addAttr(I->second); 6083 ExtnameUndeclaredIdentifiers.erase(I); 6084 } 6085 } 6086 6087 // Copy the parameter declarations from the declarator D to the function 6088 // declaration NewFD, if they are available. First scavenge them into Params. 6089 SmallVector<ParmVarDecl*, 16> Params; 6090 if (D.isFunctionDeclarator()) { 6091 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6092 6093 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6094 // function that takes no arguments, not a function that takes a 6095 // single void argument. 6096 // We let through "const void" here because Sema::GetTypeForDeclarator 6097 // already checks for that case. 6098 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6099 FTI.ArgInfo[0].Param && 6100 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 6101 // Empty arg list, don't push any params. 6102 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param)); 6103 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 6104 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 6105 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 6106 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6107 Param->setDeclContext(NewFD); 6108 Params.push_back(Param); 6109 6110 if (Param->isInvalidDecl()) 6111 NewFD->setInvalidDecl(); 6112 } 6113 } 6114 6115 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 6116 // When we're declaring a function with a typedef, typeof, etc as in the 6117 // following example, we'll need to synthesize (unnamed) 6118 // parameters for use in the declaration. 6119 // 6120 // @code 6121 // typedef void fn(int); 6122 // fn f; 6123 // @endcode 6124 6125 // Synthesize a parameter for each argument type. 6126 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 6127 AE = FT->arg_type_end(); AI != AE; ++AI) { 6128 ParmVarDecl *Param = 6129 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 6130 Param->setScopeInfo(0, Params.size()); 6131 Params.push_back(Param); 6132 } 6133 } else { 6134 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 6135 "Should not need args for typedef of non-prototype fn"); 6136 } 6137 6138 // Finally, we know we have the right number of parameters, install them. 6139 NewFD->setParams(Params); 6140 6141 // Find all anonymous symbols defined during the declaration of this function 6142 // and add to NewFD. This lets us track decls such 'enum Y' in: 6143 // 6144 // void f(enum Y {AA} x) {} 6145 // 6146 // which would otherwise incorrectly end up in the translation unit scope. 6147 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 6148 DeclsInPrototypeScope.clear(); 6149 6150 if (D.getDeclSpec().isNoreturnSpecified()) 6151 NewFD->addAttr( 6152 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 6153 Context)); 6154 6155 // Process the non-inheritable attributes on this declaration. 6156 ProcessDeclAttributes(S, NewFD, D, 6157 /*NonInheritable=*/true, /*Inheritable=*/false); 6158 6159 // Functions returning a variably modified type violate C99 6.7.5.2p2 6160 // because all functions have linkage. 6161 if (!NewFD->isInvalidDecl() && 6162 NewFD->getResultType()->isVariablyModifiedType()) { 6163 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 6164 NewFD->setInvalidDecl(); 6165 } 6166 6167 // Handle attributes. 6168 ProcessDeclAttributes(S, NewFD, D, 6169 /*NonInheritable=*/false, /*Inheritable=*/true); 6170 6171 QualType RetType = NewFD->getResultType(); 6172 const CXXRecordDecl *Ret = RetType->isRecordType() ? 6173 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 6174 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 6175 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 6176 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6177 if (!(MD && MD->getCorrespondingMethodInClass(Ret, true))) { 6178 NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(), 6179 Context)); 6180 } 6181 } 6182 6183 if (!getLangOpts().CPlusPlus) { 6184 // Perform semantic checking on the function declaration. 6185 bool isExplicitSpecialization=false; 6186 if (!NewFD->isInvalidDecl()) { 6187 if (NewFD->isMain()) 6188 CheckMain(NewFD, D.getDeclSpec()); 6189 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6190 isExplicitSpecialization)); 6191 } 6192 // Make graceful recovery from an invalid redeclaration. 6193 else if (!Previous.empty()) 6194 D.setRedeclaration(true); 6195 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6196 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6197 "previous declaration set still overloaded"); 6198 } else { 6199 // If the declarator is a template-id, translate the parser's template 6200 // argument list into our AST format. 6201 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6202 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 6203 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 6204 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 6205 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 6206 TemplateId->NumArgs); 6207 translateTemplateArguments(TemplateArgsPtr, 6208 TemplateArgs); 6209 6210 HasExplicitTemplateArgs = true; 6211 6212 if (NewFD->isInvalidDecl()) { 6213 HasExplicitTemplateArgs = false; 6214 } else if (FunctionTemplate) { 6215 // Function template with explicit template arguments. 6216 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 6217 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 6218 6219 HasExplicitTemplateArgs = false; 6220 } else if (!isFunctionTemplateSpecialization && 6221 !D.getDeclSpec().isFriendSpecified()) { 6222 // We have encountered something that the user meant to be a 6223 // specialization (because it has explicitly-specified template 6224 // arguments) but that was not introduced with a "template<>" (or had 6225 // too few of them). 6226 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 6227 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 6228 << FixItHint::CreateInsertion( 6229 D.getDeclSpec().getLocStart(), 6230 "template<> "); 6231 isFunctionTemplateSpecialization = true; 6232 } else { 6233 // "friend void foo<>(int);" is an implicit specialization decl. 6234 isFunctionTemplateSpecialization = true; 6235 } 6236 } else if (isFriend && isFunctionTemplateSpecialization) { 6237 // This combination is only possible in a recovery case; the user 6238 // wrote something like: 6239 // template <> friend void foo(int); 6240 // which we're recovering from as if the user had written: 6241 // friend void foo<>(int); 6242 // Go ahead and fake up a template id. 6243 HasExplicitTemplateArgs = true; 6244 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 6245 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 6246 } 6247 6248 // If it's a friend (and only if it's a friend), it's possible 6249 // that either the specialized function type or the specialized 6250 // template is dependent, and therefore matching will fail. In 6251 // this case, don't check the specialization yet. 6252 bool InstantiationDependent = false; 6253 if (isFunctionTemplateSpecialization && isFriend && 6254 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 6255 TemplateSpecializationType::anyDependentTemplateArguments( 6256 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 6257 InstantiationDependent))) { 6258 assert(HasExplicitTemplateArgs && 6259 "friend function specialization without template args"); 6260 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 6261 Previous)) 6262 NewFD->setInvalidDecl(); 6263 } else if (isFunctionTemplateSpecialization) { 6264 if (CurContext->isDependentContext() && CurContext->isRecord() 6265 && !isFriend) { 6266 isDependentClassScopeExplicitSpecialization = true; 6267 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 6268 diag::ext_function_specialization_in_class : 6269 diag::err_function_specialization_in_class) 6270 << NewFD->getDeclName(); 6271 } else if (CheckFunctionTemplateSpecialization(NewFD, 6272 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 6273 Previous)) 6274 NewFD->setInvalidDecl(); 6275 6276 // C++ [dcl.stc]p1: 6277 // A storage-class-specifier shall not be specified in an explicit 6278 // specialization (14.7.3) 6279 if (SC != SC_None) { 6280 if (SC != NewFD->getStorageClass()) 6281 Diag(NewFD->getLocation(), 6282 diag::err_explicit_specialization_inconsistent_storage_class) 6283 << SC 6284 << FixItHint::CreateRemoval( 6285 D.getDeclSpec().getStorageClassSpecLoc()); 6286 6287 else 6288 Diag(NewFD->getLocation(), 6289 diag::ext_explicit_specialization_storage_class) 6290 << FixItHint::CreateRemoval( 6291 D.getDeclSpec().getStorageClassSpecLoc()); 6292 } 6293 6294 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 6295 if (CheckMemberSpecialization(NewFD, Previous)) 6296 NewFD->setInvalidDecl(); 6297 } 6298 6299 // Perform semantic checking on the function declaration. 6300 if (!isDependentClassScopeExplicitSpecialization) { 6301 if (NewFD->isInvalidDecl()) { 6302 // If this is a class member, mark the class invalid immediately. 6303 // This avoids some consistency errors later. 6304 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 6305 methodDecl->getParent()->setInvalidDecl(); 6306 } else { 6307 if (NewFD->isMain()) 6308 CheckMain(NewFD, D.getDeclSpec()); 6309 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 6310 isExplicitSpecialization)); 6311 } 6312 } 6313 6314 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 6315 Previous.getResultKind() != LookupResult::FoundOverloaded) && 6316 "previous declaration set still overloaded"); 6317 6318 NamedDecl *PrincipalDecl = (FunctionTemplate 6319 ? cast<NamedDecl>(FunctionTemplate) 6320 : NewFD); 6321 6322 if (isFriend && D.isRedeclaration()) { 6323 AccessSpecifier Access = AS_public; 6324 if (!NewFD->isInvalidDecl()) 6325 Access = NewFD->getPreviousDecl()->getAccess(); 6326 6327 NewFD->setAccess(Access); 6328 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 6329 6330 PrincipalDecl->setObjectOfFriendDecl(true); 6331 } 6332 6333 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 6334 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 6335 PrincipalDecl->setNonMemberOperator(); 6336 6337 // If we have a function template, check the template parameter 6338 // list. This will check and merge default template arguments. 6339 if (FunctionTemplate) { 6340 FunctionTemplateDecl *PrevTemplate = 6341 FunctionTemplate->getPreviousDecl(); 6342 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 6343 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 6344 D.getDeclSpec().isFriendSpecified() 6345 ? (D.isFunctionDefinition() 6346 ? TPC_FriendFunctionTemplateDefinition 6347 : TPC_FriendFunctionTemplate) 6348 : (D.getCXXScopeSpec().isSet() && 6349 DC && DC->isRecord() && 6350 DC->isDependentContext()) 6351 ? TPC_ClassTemplateMember 6352 : TPC_FunctionTemplate); 6353 } 6354 6355 if (NewFD->isInvalidDecl()) { 6356 // Ignore all the rest of this. 6357 } else if (!D.isRedeclaration()) { 6358 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 6359 AddToScope }; 6360 // Fake up an access specifier if it's supposed to be a class member. 6361 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 6362 NewFD->setAccess(AS_public); 6363 6364 // Qualified decls generally require a previous declaration. 6365 if (D.getCXXScopeSpec().isSet()) { 6366 // ...with the major exception of templated-scope or 6367 // dependent-scope friend declarations. 6368 6369 // TODO: we currently also suppress this check in dependent 6370 // contexts because (1) the parameter depth will be off when 6371 // matching friend templates and (2) we might actually be 6372 // selecting a friend based on a dependent factor. But there 6373 // are situations where these conditions don't apply and we 6374 // can actually do this check immediately. 6375 if (isFriend && 6376 (TemplateParamLists.size() || 6377 D.getCXXScopeSpec().getScopeRep()->isDependent() || 6378 CurContext->isDependentContext())) { 6379 // ignore these 6380 } else { 6381 // The user tried to provide an out-of-line definition for a 6382 // function that is a member of a class or namespace, but there 6383 // was no such member function declared (C++ [class.mfct]p2, 6384 // C++ [namespace.memdef]p2). For example: 6385 // 6386 // class X { 6387 // void f() const; 6388 // }; 6389 // 6390 // void X::f() { } // ill-formed 6391 // 6392 // Complain about this problem, and attempt to suggest close 6393 // matches (e.g., those that differ only in cv-qualifiers and 6394 // whether the parameter types are references). 6395 6396 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6397 NewFD, 6398 ExtraArgs)) { 6399 AddToScope = ExtraArgs.AddToScope; 6400 return Result; 6401 } 6402 } 6403 6404 // Unqualified local friend declarations are required to resolve 6405 // to something. 6406 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 6407 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 6408 NewFD, 6409 ExtraArgs)) { 6410 AddToScope = ExtraArgs.AddToScope; 6411 return Result; 6412 } 6413 } 6414 6415 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 6416 !isFriend && !isFunctionTemplateSpecialization && 6417 !isExplicitSpecialization) { 6418 // An out-of-line member function declaration must also be a 6419 // definition (C++ [dcl.meaning]p1). 6420 // Note that this is not the case for explicit specializations of 6421 // function templates or member functions of class templates, per 6422 // C++ [temp.expl.spec]p2. We also allow these declarations as an 6423 // extension for compatibility with old SWIG code which likes to 6424 // generate them. 6425 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 6426 << D.getCXXScopeSpec().getRange(); 6427 } 6428 } 6429 6430 ProcessPragmaWeak(S, NewFD); 6431 checkAttributesAfterMerging(*this, *NewFD); 6432 6433 AddKnownFunctionAttributes(NewFD); 6434 6435 if (NewFD->hasAttr<OverloadableAttr>() && 6436 !NewFD->getType()->getAs<FunctionProtoType>()) { 6437 Diag(NewFD->getLocation(), 6438 diag::err_attribute_overloadable_no_prototype) 6439 << NewFD; 6440 6441 // Turn this into a variadic function with no parameters. 6442 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 6443 FunctionProtoType::ExtProtoInfo EPI; 6444 EPI.Variadic = true; 6445 EPI.ExtInfo = FT->getExtInfo(); 6446 6447 QualType R = Context.getFunctionType(FT->getResultType(), 6448 ArrayRef<QualType>(), 6449 EPI); 6450 NewFD->setType(R); 6451 } 6452 6453 // If there's a #pragma GCC visibility in scope, and this isn't a class 6454 // member, set the visibility of this function. 6455 if (!DC->isRecord() && NewFD->hasExternalLinkage()) 6456 AddPushedVisibilityAttribute(NewFD); 6457 6458 // If there's a #pragma clang arc_cf_code_audited in scope, consider 6459 // marking the function. 6460 AddCFAuditedAttribute(NewFD); 6461 6462 // If this is a locally-scoped extern C function, update the 6463 // map of such names. 6464 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 6465 && !NewFD->isInvalidDecl()) 6466 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 6467 6468 // Set this FunctionDecl's range up to the right paren. 6469 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 6470 6471 if (getLangOpts().CPlusPlus) { 6472 if (FunctionTemplate) { 6473 if (NewFD->isInvalidDecl()) 6474 FunctionTemplate->setInvalidDecl(); 6475 return FunctionTemplate; 6476 } 6477 } 6478 6479 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 6480 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 6481 if ((getLangOpts().OpenCLVersion >= 120) 6482 && (SC == SC_Static)) { 6483 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 6484 D.setInvalidType(); 6485 } 6486 6487 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 6488 if (!NewFD->getResultType()->isVoidType()) { 6489 Diag(D.getIdentifierLoc(), 6490 diag::err_expected_kernel_void_return_type); 6491 D.setInvalidType(); 6492 } 6493 6494 for (FunctionDecl::param_iterator PI = NewFD->param_begin(), 6495 PE = NewFD->param_end(); PI != PE; ++PI) { 6496 ParmVarDecl *Param = *PI; 6497 QualType PT = Param->getType(); 6498 6499 // OpenCL v1.2 s6.9.a: 6500 // A kernel function argument cannot be declared as a 6501 // pointer to a pointer type. 6502 if (PT->isPointerType() && PT->getPointeeType()->isPointerType()) { 6503 Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_arg); 6504 D.setInvalidType(); 6505 } 6506 6507 // OpenCL v1.2 s6.8 n: 6508 // A kernel function argument cannot be declared 6509 // of event_t type. 6510 if (PT->isEventT()) { 6511 Diag(Param->getLocation(), diag::err_event_t_kernel_arg); 6512 D.setInvalidType(); 6513 } 6514 } 6515 } 6516 6517 MarkUnusedFileScopedDecl(NewFD); 6518 6519 if (getLangOpts().CUDA) 6520 if (IdentifierInfo *II = NewFD->getIdentifier()) 6521 if (!NewFD->isInvalidDecl() && 6522 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6523 if (II->isStr("cudaConfigureCall")) { 6524 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 6525 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 6526 6527 Context.setcudaConfigureCallDecl(NewFD); 6528 } 6529 } 6530 6531 // Here we have an function template explicit specialization at class scope. 6532 // The actually specialization will be postponed to template instatiation 6533 // time via the ClassScopeFunctionSpecializationDecl node. 6534 if (isDependentClassScopeExplicitSpecialization) { 6535 ClassScopeFunctionSpecializationDecl *NewSpec = 6536 ClassScopeFunctionSpecializationDecl::Create( 6537 Context, CurContext, SourceLocation(), 6538 cast<CXXMethodDecl>(NewFD), 6539 HasExplicitTemplateArgs, TemplateArgs); 6540 CurContext->addDecl(NewSpec); 6541 AddToScope = false; 6542 } 6543 6544 return NewFD; 6545} 6546 6547/// \brief Perform semantic checking of a new function declaration. 6548/// 6549/// Performs semantic analysis of the new function declaration 6550/// NewFD. This routine performs all semantic checking that does not 6551/// require the actual declarator involved in the declaration, and is 6552/// used both for the declaration of functions as they are parsed 6553/// (called via ActOnDeclarator) and for the declaration of functions 6554/// that have been instantiated via C++ template instantiation (called 6555/// via InstantiateDecl). 6556/// 6557/// \param IsExplicitSpecialization whether this new function declaration is 6558/// an explicit specialization of the previous declaration. 6559/// 6560/// This sets NewFD->isInvalidDecl() to true if there was an error. 6561/// 6562/// \returns true if the function declaration is a redeclaration. 6563bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 6564 LookupResult &Previous, 6565 bool IsExplicitSpecialization) { 6566 assert(!NewFD->getResultType()->isVariablyModifiedType() 6567 && "Variably modified return types are not handled here"); 6568 6569 // Check for a previous declaration of this name. 6570 if (Previous.empty() && mayConflictWithNonVisibleExternC(NewFD)) { 6571 // Since we did not find anything by this name, look for a non-visible 6572 // extern "C" declaration with the same name. 6573 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 6574 = findLocallyScopedExternCDecl(NewFD->getDeclName()); 6575 if (Pos != LocallyScopedExternCDecls.end()) 6576 Previous.addDecl(Pos->second); 6577 } 6578 6579 // Filter out any non-conflicting previous declarations. 6580 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 6581 6582 bool Redeclaration = false; 6583 NamedDecl *OldDecl = 0; 6584 6585 // Merge or overload the declaration with an existing declaration of 6586 // the same name, if appropriate. 6587 if (!Previous.empty()) { 6588 // Determine whether NewFD is an overload of PrevDecl or 6589 // a declaration that requires merging. If it's an overload, 6590 // there's no more work to do here; we'll just add the new 6591 // function to the scope. 6592 if (!AllowOverloadingOfFunction(Previous, Context)) { 6593 Redeclaration = true; 6594 OldDecl = Previous.getFoundDecl(); 6595 } else { 6596 switch (CheckOverload(S, NewFD, Previous, OldDecl, 6597 /*NewIsUsingDecl*/ false)) { 6598 case Ovl_Match: 6599 Redeclaration = true; 6600 break; 6601 6602 case Ovl_NonFunction: 6603 Redeclaration = true; 6604 break; 6605 6606 case Ovl_Overload: 6607 Redeclaration = false; 6608 break; 6609 } 6610 6611 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 6612 // If a function name is overloadable in C, then every function 6613 // with that name must be marked "overloadable". 6614 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 6615 << Redeclaration << NewFD; 6616 NamedDecl *OverloadedDecl = 0; 6617 if (Redeclaration) 6618 OverloadedDecl = OldDecl; 6619 else if (!Previous.empty()) 6620 OverloadedDecl = Previous.getRepresentativeDecl(); 6621 if (OverloadedDecl) 6622 Diag(OverloadedDecl->getLocation(), 6623 diag::note_attribute_overloadable_prev_overload); 6624 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 6625 Context)); 6626 } 6627 } 6628 } 6629 6630 // C++11 [dcl.constexpr]p8: 6631 // A constexpr specifier for a non-static member function that is not 6632 // a constructor declares that member function to be const. 6633 // 6634 // This needs to be delayed until we know whether this is an out-of-line 6635 // definition of a static member function. 6636 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6637 if (MD && MD->isConstexpr() && !MD->isStatic() && 6638 !isa<CXXConstructorDecl>(MD) && 6639 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 6640 CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl); 6641 if (FunctionTemplateDecl *OldTD = 6642 dyn_cast_or_null<FunctionTemplateDecl>(OldDecl)) 6643 OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl()); 6644 if (!OldMD || !OldMD->isStatic()) { 6645 const FunctionProtoType *FPT = 6646 MD->getType()->castAs<FunctionProtoType>(); 6647 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6648 EPI.TypeQuals |= Qualifiers::Const; 6649 MD->setType(Context.getFunctionType(FPT->getResultType(), 6650 ArrayRef<QualType>(FPT->arg_type_begin(), 6651 FPT->getNumArgs()), 6652 EPI)); 6653 } 6654 } 6655 6656 if (Redeclaration) { 6657 // NewFD and OldDecl represent declarations that need to be 6658 // merged. 6659 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 6660 NewFD->setInvalidDecl(); 6661 return Redeclaration; 6662 } 6663 6664 Previous.clear(); 6665 Previous.addDecl(OldDecl); 6666 6667 if (FunctionTemplateDecl *OldTemplateDecl 6668 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 6669 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 6670 FunctionTemplateDecl *NewTemplateDecl 6671 = NewFD->getDescribedFunctionTemplate(); 6672 assert(NewTemplateDecl && "Template/non-template mismatch"); 6673 if (CXXMethodDecl *Method 6674 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 6675 Method->setAccess(OldTemplateDecl->getAccess()); 6676 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 6677 } 6678 6679 // If this is an explicit specialization of a member that is a function 6680 // template, mark it as a member specialization. 6681 if (IsExplicitSpecialization && 6682 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 6683 NewTemplateDecl->setMemberSpecialization(); 6684 assert(OldTemplateDecl->isMemberSpecialization()); 6685 } 6686 6687 } else { 6688 // This needs to happen first so that 'inline' propagates. 6689 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 6690 6691 if (isa<CXXMethodDecl>(NewFD)) { 6692 // A valid redeclaration of a C++ method must be out-of-line, 6693 // but (unfortunately) it's not necessarily a definition 6694 // because of templates, which means that the previous 6695 // declaration is not necessarily from the class definition. 6696 6697 // For just setting the access, that doesn't matter. 6698 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 6699 NewFD->setAccess(oldMethod->getAccess()); 6700 6701 // Update the key-function state if necessary for this ABI. 6702 if (NewFD->isInlined() && 6703 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 6704 // setNonKeyFunction needs to work with the original 6705 // declaration from the class definition, and isVirtual() is 6706 // just faster in that case, so map back to that now. 6707 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDeclaration()); 6708 if (oldMethod->isVirtual()) { 6709 Context.setNonKeyFunction(oldMethod); 6710 } 6711 } 6712 } 6713 } 6714 } 6715 6716 // Semantic checking for this function declaration (in isolation). 6717 if (getLangOpts().CPlusPlus) { 6718 // C++-specific checks. 6719 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 6720 CheckConstructor(Constructor); 6721 } else if (CXXDestructorDecl *Destructor = 6722 dyn_cast<CXXDestructorDecl>(NewFD)) { 6723 CXXRecordDecl *Record = Destructor->getParent(); 6724 QualType ClassType = Context.getTypeDeclType(Record); 6725 6726 // FIXME: Shouldn't we be able to perform this check even when the class 6727 // type is dependent? Both gcc and edg can handle that. 6728 if (!ClassType->isDependentType()) { 6729 DeclarationName Name 6730 = Context.DeclarationNames.getCXXDestructorName( 6731 Context.getCanonicalType(ClassType)); 6732 if (NewFD->getDeclName() != Name) { 6733 Diag(NewFD->getLocation(), diag::err_destructor_name); 6734 NewFD->setInvalidDecl(); 6735 return Redeclaration; 6736 } 6737 } 6738 } else if (CXXConversionDecl *Conversion 6739 = dyn_cast<CXXConversionDecl>(NewFD)) { 6740 ActOnConversionDeclarator(Conversion); 6741 } 6742 6743 // Find any virtual functions that this function overrides. 6744 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 6745 if (!Method->isFunctionTemplateSpecialization() && 6746 !Method->getDescribedFunctionTemplate() && 6747 Method->isCanonicalDecl()) { 6748 if (AddOverriddenMethods(Method->getParent(), Method)) { 6749 // If the function was marked as "static", we have a problem. 6750 if (NewFD->getStorageClass() == SC_Static) { 6751 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 6752 } 6753 } 6754 } 6755 6756 if (Method->isStatic()) 6757 checkThisInStaticMemberFunctionType(Method); 6758 } 6759 6760 // Extra checking for C++ overloaded operators (C++ [over.oper]). 6761 if (NewFD->isOverloadedOperator() && 6762 CheckOverloadedOperatorDeclaration(NewFD)) { 6763 NewFD->setInvalidDecl(); 6764 return Redeclaration; 6765 } 6766 6767 // Extra checking for C++0x literal operators (C++0x [over.literal]). 6768 if (NewFD->getLiteralIdentifier() && 6769 CheckLiteralOperatorDeclaration(NewFD)) { 6770 NewFD->setInvalidDecl(); 6771 return Redeclaration; 6772 } 6773 6774 // In C++, check default arguments now that we have merged decls. Unless 6775 // the lexical context is the class, because in this case this is done 6776 // during delayed parsing anyway. 6777 if (!CurContext->isRecord()) 6778 CheckCXXDefaultArguments(NewFD); 6779 6780 // If this function declares a builtin function, check the type of this 6781 // declaration against the expected type for the builtin. 6782 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 6783 ASTContext::GetBuiltinTypeError Error; 6784 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 6785 QualType T = Context.GetBuiltinType(BuiltinID, Error); 6786 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 6787 // The type of this function differs from the type of the builtin, 6788 // so forget about the builtin entirely. 6789 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 6790 } 6791 } 6792 6793 // If this function is declared as being extern "C", then check to see if 6794 // the function returns a UDT (class, struct, or union type) that is not C 6795 // compatible, and if it does, warn the user. 6796 // But, issue any diagnostic on the first declaration only. 6797 if (NewFD->isExternC() && Previous.empty()) { 6798 QualType R = NewFD->getResultType(); 6799 if (R->isIncompleteType() && !R->isVoidType()) 6800 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 6801 << NewFD << R; 6802 else if (!R.isPODType(Context) && !R->isVoidType() && 6803 !R->isObjCObjectPointerType()) 6804 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 6805 } 6806 } 6807 return Redeclaration; 6808} 6809 6810static SourceRange getResultSourceRange(const FunctionDecl *FD) { 6811 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 6812 if (!TSI) 6813 return SourceRange(); 6814 6815 TypeLoc TL = TSI->getTypeLoc(); 6816 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 6817 if (!FunctionTL) 6818 return SourceRange(); 6819 6820 TypeLoc ResultTL = FunctionTL.getResultLoc(); 6821 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 6822 return ResultTL.getSourceRange(); 6823 6824 return SourceRange(); 6825} 6826 6827void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 6828 // C++11 [basic.start.main]p3: A program that declares main to be inline, 6829 // static or constexpr is ill-formed. 6830 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 6831 // appear in a declaration of main. 6832 // static main is not an error under C99, but we should warn about it. 6833 // We accept _Noreturn main as an extension. 6834 if (FD->getStorageClass() == SC_Static) 6835 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 6836 ? diag::err_static_main : diag::warn_static_main) 6837 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 6838 if (FD->isInlineSpecified()) 6839 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 6840 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 6841 if (DS.isNoreturnSpecified()) { 6842 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 6843 SourceRange NoreturnRange(NoreturnLoc, 6844 PP.getLocForEndOfToken(NoreturnLoc)); 6845 Diag(NoreturnLoc, diag::ext_noreturn_main); 6846 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 6847 << FixItHint::CreateRemoval(NoreturnRange); 6848 } 6849 if (FD->isConstexpr()) { 6850 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 6851 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 6852 FD->setConstexpr(false); 6853 } 6854 6855 QualType T = FD->getType(); 6856 assert(T->isFunctionType() && "function decl is not of function type"); 6857 const FunctionType* FT = T->castAs<FunctionType>(); 6858 6859 // All the standards say that main() should should return 'int'. 6860 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 6861 // In C and C++, main magically returns 0 if you fall off the end; 6862 // set the flag which tells us that. 6863 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 6864 FD->setHasImplicitReturnZero(true); 6865 6866 // In C with GNU extensions we allow main() to have non-integer return 6867 // type, but we should warn about the extension, and we disable the 6868 // implicit-return-zero rule. 6869 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 6870 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 6871 6872 SourceRange ResultRange = getResultSourceRange(FD); 6873 if (ResultRange.isValid()) 6874 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 6875 << FixItHint::CreateReplacement(ResultRange, "int"); 6876 6877 // Otherwise, this is just a flat-out error. 6878 } else { 6879 SourceRange ResultRange = getResultSourceRange(FD); 6880 if (ResultRange.isValid()) 6881 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 6882 << FixItHint::CreateReplacement(ResultRange, "int"); 6883 else 6884 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 6885 6886 FD->setInvalidDecl(true); 6887 } 6888 6889 // Treat protoless main() as nullary. 6890 if (isa<FunctionNoProtoType>(FT)) return; 6891 6892 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 6893 unsigned nparams = FTP->getNumArgs(); 6894 assert(FD->getNumParams() == nparams); 6895 6896 bool HasExtraParameters = (nparams > 3); 6897 6898 // Darwin passes an undocumented fourth argument of type char**. If 6899 // other platforms start sprouting these, the logic below will start 6900 // getting shifty. 6901 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 6902 HasExtraParameters = false; 6903 6904 if (HasExtraParameters) { 6905 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 6906 FD->setInvalidDecl(true); 6907 nparams = 3; 6908 } 6909 6910 // FIXME: a lot of the following diagnostics would be improved 6911 // if we had some location information about types. 6912 6913 QualType CharPP = 6914 Context.getPointerType(Context.getPointerType(Context.CharTy)); 6915 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 6916 6917 for (unsigned i = 0; i < nparams; ++i) { 6918 QualType AT = FTP->getArgType(i); 6919 6920 bool mismatch = true; 6921 6922 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 6923 mismatch = false; 6924 else if (Expected[i] == CharPP) { 6925 // As an extension, the following forms are okay: 6926 // char const ** 6927 // char const * const * 6928 // char * const * 6929 6930 QualifierCollector qs; 6931 const PointerType* PT; 6932 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 6933 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 6934 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 6935 Context.CharTy)) { 6936 qs.removeConst(); 6937 mismatch = !qs.empty(); 6938 } 6939 } 6940 6941 if (mismatch) { 6942 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 6943 // TODO: suggest replacing given type with expected type 6944 FD->setInvalidDecl(true); 6945 } 6946 } 6947 6948 if (nparams == 1 && !FD->isInvalidDecl()) { 6949 Diag(FD->getLocation(), diag::warn_main_one_arg); 6950 } 6951 6952 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 6953 Diag(FD->getLocation(), diag::err_main_template_decl); 6954 FD->setInvalidDecl(); 6955 } 6956} 6957 6958bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 6959 // FIXME: Need strict checking. In C89, we need to check for 6960 // any assignment, increment, decrement, function-calls, or 6961 // commas outside of a sizeof. In C99, it's the same list, 6962 // except that the aforementioned are allowed in unevaluated 6963 // expressions. Everything else falls under the 6964 // "may accept other forms of constant expressions" exception. 6965 // (We never end up here for C++, so the constant expression 6966 // rules there don't matter.) 6967 if (Init->isConstantInitializer(Context, false)) 6968 return false; 6969 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 6970 << Init->getSourceRange(); 6971 return true; 6972} 6973 6974namespace { 6975 // Visits an initialization expression to see if OrigDecl is evaluated in 6976 // its own initialization and throws a warning if it does. 6977 class SelfReferenceChecker 6978 : public EvaluatedExprVisitor<SelfReferenceChecker> { 6979 Sema &S; 6980 Decl *OrigDecl; 6981 bool isRecordType; 6982 bool isPODType; 6983 bool isReferenceType; 6984 6985 public: 6986 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 6987 6988 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 6989 S(S), OrigDecl(OrigDecl) { 6990 isPODType = false; 6991 isRecordType = false; 6992 isReferenceType = false; 6993 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 6994 isPODType = VD->getType().isPODType(S.Context); 6995 isRecordType = VD->getType()->isRecordType(); 6996 isReferenceType = VD->getType()->isReferenceType(); 6997 } 6998 } 6999 7000 // For most expressions, the cast is directly above the DeclRefExpr. 7001 // For conditional operators, the cast can be outside the conditional 7002 // operator if both expressions are DeclRefExpr's. 7003 void HandleValue(Expr *E) { 7004 if (isReferenceType) 7005 return; 7006 E = E->IgnoreParenImpCasts(); 7007 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7008 HandleDeclRefExpr(DRE); 7009 return; 7010 } 7011 7012 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7013 HandleValue(CO->getTrueExpr()); 7014 HandleValue(CO->getFalseExpr()); 7015 return; 7016 } 7017 7018 if (isa<MemberExpr>(E)) { 7019 Expr *Base = E->IgnoreParenImpCasts(); 7020 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7021 // Check for static member variables and don't warn on them. 7022 if (!isa<FieldDecl>(ME->getMemberDecl())) 7023 return; 7024 Base = ME->getBase()->IgnoreParenImpCasts(); 7025 } 7026 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7027 HandleDeclRefExpr(DRE); 7028 return; 7029 } 7030 } 7031 7032 // Reference types are handled here since all uses of references are 7033 // bad, not just r-value uses. 7034 void VisitDeclRefExpr(DeclRefExpr *E) { 7035 if (isReferenceType) 7036 HandleDeclRefExpr(E); 7037 } 7038 7039 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 7040 if (E->getCastKind() == CK_LValueToRValue || 7041 (isRecordType && E->getCastKind() == CK_NoOp)) 7042 HandleValue(E->getSubExpr()); 7043 7044 Inherited::VisitImplicitCastExpr(E); 7045 } 7046 7047 void VisitMemberExpr(MemberExpr *E) { 7048 // Don't warn on arrays since they can be treated as pointers. 7049 if (E->getType()->canDecayToPointerType()) return; 7050 7051 // Warn when a non-static method call is followed by non-static member 7052 // field accesses, which is followed by a DeclRefExpr. 7053 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 7054 bool Warn = (MD && !MD->isStatic()); 7055 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 7056 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7057 if (!isa<FieldDecl>(ME->getMemberDecl())) 7058 Warn = false; 7059 Base = ME->getBase()->IgnoreParenImpCasts(); 7060 } 7061 7062 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 7063 if (Warn) 7064 HandleDeclRefExpr(DRE); 7065 return; 7066 } 7067 7068 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 7069 // Visit that expression. 7070 Visit(Base); 7071 } 7072 7073 void VisitUnaryOperator(UnaryOperator *E) { 7074 // For POD record types, addresses of its own members are well-defined. 7075 if (E->getOpcode() == UO_AddrOf && isRecordType && 7076 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 7077 if (!isPODType) 7078 HandleValue(E->getSubExpr()); 7079 return; 7080 } 7081 Inherited::VisitUnaryOperator(E); 7082 } 7083 7084 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 7085 7086 void HandleDeclRefExpr(DeclRefExpr *DRE) { 7087 Decl* ReferenceDecl = DRE->getDecl(); 7088 if (OrigDecl != ReferenceDecl) return; 7089 unsigned diag; 7090 if (isReferenceType) { 7091 diag = diag::warn_uninit_self_reference_in_reference_init; 7092 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 7093 diag = diag::warn_static_self_reference_in_init; 7094 } else { 7095 diag = diag::warn_uninit_self_reference_in_init; 7096 } 7097 7098 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 7099 S.PDiag(diag) 7100 << DRE->getNameInfo().getName() 7101 << OrigDecl->getLocation() 7102 << DRE->getSourceRange()); 7103 } 7104 }; 7105 7106 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 7107 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 7108 bool DirectInit) { 7109 // Parameters arguments are occassionially constructed with itself, 7110 // for instance, in recursive functions. Skip them. 7111 if (isa<ParmVarDecl>(OrigDecl)) 7112 return; 7113 7114 E = E->IgnoreParens(); 7115 7116 // Skip checking T a = a where T is not a record or reference type. 7117 // Doing so is a way to silence uninitialized warnings. 7118 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 7119 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 7120 if (ICE->getCastKind() == CK_LValueToRValue) 7121 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 7122 if (DRE->getDecl() == OrigDecl) 7123 return; 7124 7125 SelfReferenceChecker(S, OrigDecl).Visit(E); 7126 } 7127} 7128 7129/// AddInitializerToDecl - Adds the initializer Init to the 7130/// declaration dcl. If DirectInit is true, this is C++ direct 7131/// initialization rather than copy initialization. 7132void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 7133 bool DirectInit, bool TypeMayContainAuto) { 7134 // If there is no declaration, there was an error parsing it. Just ignore 7135 // the initializer. 7136 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 7137 return; 7138 7139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 7140 // With declarators parsed the way they are, the parser cannot 7141 // distinguish between a normal initializer and a pure-specifier. 7142 // Thus this grotesque test. 7143 IntegerLiteral *IL; 7144 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 7145 Context.getCanonicalType(IL->getType()) == Context.IntTy) 7146 CheckPureMethod(Method, Init->getSourceRange()); 7147 else { 7148 Diag(Method->getLocation(), diag::err_member_function_initialization) 7149 << Method->getDeclName() << Init->getSourceRange(); 7150 Method->setInvalidDecl(); 7151 } 7152 return; 7153 } 7154 7155 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 7156 if (!VDecl) { 7157 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 7158 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 7159 RealDecl->setInvalidDecl(); 7160 return; 7161 } 7162 7163 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 7164 7165 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 7166 AutoType *Auto = 0; 7167 if (TypeMayContainAuto && 7168 (Auto = VDecl->getType()->getContainedAutoType()) && 7169 !Auto->isDeduced()) { 7170 Expr *DeduceInit = Init; 7171 // Initializer could be a C++ direct-initializer. Deduction only works if it 7172 // contains exactly one expression. 7173 if (CXXDirectInit) { 7174 if (CXXDirectInit->getNumExprs() == 0) { 7175 // It isn't possible to write this directly, but it is possible to 7176 // end up in this situation with "auto x(some_pack...);" 7177 Diag(CXXDirectInit->getLocStart(), 7178 diag::err_auto_var_init_no_expression) 7179 << VDecl->getDeclName() << VDecl->getType() 7180 << VDecl->getSourceRange(); 7181 RealDecl->setInvalidDecl(); 7182 return; 7183 } else if (CXXDirectInit->getNumExprs() > 1) { 7184 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 7185 diag::err_auto_var_init_multiple_expressions) 7186 << VDecl->getDeclName() << VDecl->getType() 7187 << VDecl->getSourceRange(); 7188 RealDecl->setInvalidDecl(); 7189 return; 7190 } else { 7191 DeduceInit = CXXDirectInit->getExpr(0); 7192 } 7193 } 7194 7195 // Expressions default to 'id' when we're in a debugger. 7196 bool DefaultedToAuto = false; 7197 if (getLangOpts().DebuggerCastResultToId && 7198 Init->getType() == Context.UnknownAnyTy) { 7199 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 7200 if (Result.isInvalid()) { 7201 VDecl->setInvalidDecl(); 7202 return; 7203 } 7204 Init = Result.take(); 7205 DefaultedToAuto = true; 7206 } 7207 7208 TypeSourceInfo *DeducedType = 0; 7209 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 7210 DAR_Failed) 7211 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 7212 if (!DeducedType) { 7213 RealDecl->setInvalidDecl(); 7214 return; 7215 } 7216 VDecl->setTypeSourceInfo(DeducedType); 7217 VDecl->setType(DeducedType->getType()); 7218 assert(VDecl->isLinkageValid()); 7219 7220 // In ARC, infer lifetime. 7221 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 7222 VDecl->setInvalidDecl(); 7223 7224 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 7225 // 'id' instead of a specific object type prevents most of our usual checks. 7226 // We only want to warn outside of template instantiations, though: 7227 // inside a template, the 'id' could have come from a parameter. 7228 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 7229 DeducedType->getType()->isObjCIdType()) { 7230 SourceLocation Loc = DeducedType->getTypeLoc().getBeginLoc(); 7231 Diag(Loc, diag::warn_auto_var_is_id) 7232 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 7233 } 7234 7235 // If this is a redeclaration, check that the type we just deduced matches 7236 // the previously declared type. 7237 if (VarDecl *Old = VDecl->getPreviousDecl()) 7238 MergeVarDeclTypes(VDecl, Old); 7239 } 7240 7241 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 7242 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 7243 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 7244 VDecl->setInvalidDecl(); 7245 return; 7246 } 7247 7248 if (!VDecl->getType()->isDependentType()) { 7249 // A definition must end up with a complete type, which means it must be 7250 // complete with the restriction that an array type might be completed by 7251 // the initializer; note that later code assumes this restriction. 7252 QualType BaseDeclType = VDecl->getType(); 7253 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 7254 BaseDeclType = Array->getElementType(); 7255 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 7256 diag::err_typecheck_decl_incomplete_type)) { 7257 RealDecl->setInvalidDecl(); 7258 return; 7259 } 7260 7261 // The variable can not have an abstract class type. 7262 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 7263 diag::err_abstract_type_in_decl, 7264 AbstractVariableType)) 7265 VDecl->setInvalidDecl(); 7266 } 7267 7268 const VarDecl *Def; 7269 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 7270 Diag(VDecl->getLocation(), diag::err_redefinition) 7271 << VDecl->getDeclName(); 7272 Diag(Def->getLocation(), diag::note_previous_definition); 7273 VDecl->setInvalidDecl(); 7274 return; 7275 } 7276 7277 const VarDecl* PrevInit = 0; 7278 if (getLangOpts().CPlusPlus) { 7279 // C++ [class.static.data]p4 7280 // If a static data member is of const integral or const 7281 // enumeration type, its declaration in the class definition can 7282 // specify a constant-initializer which shall be an integral 7283 // constant expression (5.19). In that case, the member can appear 7284 // in integral constant expressions. The member shall still be 7285 // defined in a namespace scope if it is used in the program and the 7286 // namespace scope definition shall not contain an initializer. 7287 // 7288 // We already performed a redefinition check above, but for static 7289 // data members we also need to check whether there was an in-class 7290 // declaration with an initializer. 7291 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 7292 Diag(VDecl->getLocation(), diag::err_redefinition) 7293 << VDecl->getDeclName(); 7294 Diag(PrevInit->getLocation(), diag::note_previous_definition); 7295 return; 7296 } 7297 7298 if (VDecl->hasLocalStorage()) 7299 getCurFunction()->setHasBranchProtectedScope(); 7300 7301 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 7302 VDecl->setInvalidDecl(); 7303 return; 7304 } 7305 } 7306 7307 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 7308 // a kernel function cannot be initialized." 7309 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 7310 Diag(VDecl->getLocation(), diag::err_local_cant_init); 7311 VDecl->setInvalidDecl(); 7312 return; 7313 } 7314 7315 // Get the decls type and save a reference for later, since 7316 // CheckInitializerTypes may change it. 7317 QualType DclT = VDecl->getType(), SavT = DclT; 7318 7319 // Expressions default to 'id' when we're in a debugger 7320 // and we are assigning it to a variable of Objective-C pointer type. 7321 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 7322 Init->getType() == Context.UnknownAnyTy) { 7323 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 7324 if (Result.isInvalid()) { 7325 VDecl->setInvalidDecl(); 7326 return; 7327 } 7328 Init = Result.take(); 7329 } 7330 7331 // Perform the initialization. 7332 if (!VDecl->isInvalidDecl()) { 7333 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 7334 InitializationKind Kind 7335 = DirectInit ? 7336 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 7337 Init->getLocStart(), 7338 Init->getLocEnd()) 7339 : InitializationKind::CreateDirectList( 7340 VDecl->getLocation()) 7341 : InitializationKind::CreateCopy(VDecl->getLocation(), 7342 Init->getLocStart()); 7343 7344 Expr **Args = &Init; 7345 unsigned NumArgs = 1; 7346 if (CXXDirectInit) { 7347 Args = CXXDirectInit->getExprs(); 7348 NumArgs = CXXDirectInit->getNumExprs(); 7349 } 7350 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 7351 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 7352 MultiExprArg(Args, NumArgs), &DclT); 7353 if (Result.isInvalid()) { 7354 VDecl->setInvalidDecl(); 7355 return; 7356 } 7357 7358 Init = Result.takeAs<Expr>(); 7359 } 7360 7361 // Check for self-references within variable initializers. 7362 // Variables declared within a function/method body (except for references) 7363 // are handled by a dataflow analysis. 7364 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 7365 VDecl->getType()->isReferenceType()) { 7366 CheckSelfReference(*this, RealDecl, Init, DirectInit); 7367 } 7368 7369 // If the type changed, it means we had an incomplete type that was 7370 // completed by the initializer. For example: 7371 // int ary[] = { 1, 3, 5 }; 7372 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 7373 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 7374 VDecl->setType(DclT); 7375 7376 if (!VDecl->isInvalidDecl()) { 7377 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 7378 7379 if (VDecl->hasAttr<BlocksAttr>()) 7380 checkRetainCycles(VDecl, Init); 7381 7382 // It is safe to assign a weak reference into a strong variable. 7383 // Although this code can still have problems: 7384 // id x = self.weakProp; 7385 // id y = self.weakProp; 7386 // we do not warn to warn spuriously when 'x' and 'y' are on separate 7387 // paths through the function. This should be revisited if 7388 // -Wrepeated-use-of-weak is made flow-sensitive. 7389 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 7390 DiagnosticsEngine::Level Level = 7391 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 7392 Init->getLocStart()); 7393 if (Level != DiagnosticsEngine::Ignored) 7394 getCurFunction()->markSafeWeakUse(Init); 7395 } 7396 } 7397 7398 // The initialization is usually a full-expression. 7399 // 7400 // FIXME: If this is a braced initialization of an aggregate, it is not 7401 // an expression, and each individual field initializer is a separate 7402 // full-expression. For instance, in: 7403 // 7404 // struct Temp { ~Temp(); }; 7405 // struct S { S(Temp); }; 7406 // struct T { S a, b; } t = { Temp(), Temp() } 7407 // 7408 // we should destroy the first Temp before constructing the second. 7409 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 7410 false, 7411 VDecl->isConstexpr()); 7412 if (Result.isInvalid()) { 7413 VDecl->setInvalidDecl(); 7414 return; 7415 } 7416 Init = Result.take(); 7417 7418 // Attach the initializer to the decl. 7419 VDecl->setInit(Init); 7420 7421 if (VDecl->isLocalVarDecl()) { 7422 // C99 6.7.8p4: All the expressions in an initializer for an object that has 7423 // static storage duration shall be constant expressions or string literals. 7424 // C++ does not have this restriction. 7425 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 7426 VDecl->getStorageClass() == SC_Static) 7427 CheckForConstantInitializer(Init, DclT); 7428 } else if (VDecl->isStaticDataMember() && 7429 VDecl->getLexicalDeclContext()->isRecord()) { 7430 // This is an in-class initialization for a static data member, e.g., 7431 // 7432 // struct S { 7433 // static const int value = 17; 7434 // }; 7435 7436 // C++ [class.mem]p4: 7437 // A member-declarator can contain a constant-initializer only 7438 // if it declares a static member (9.4) of const integral or 7439 // const enumeration type, see 9.4.2. 7440 // 7441 // C++11 [class.static.data]p3: 7442 // If a non-volatile const static data member is of integral or 7443 // enumeration type, its declaration in the class definition can 7444 // specify a brace-or-equal-initializer in which every initalizer-clause 7445 // that is an assignment-expression is a constant expression. A static 7446 // data member of literal type can be declared in the class definition 7447 // with the constexpr specifier; if so, its declaration shall specify a 7448 // brace-or-equal-initializer in which every initializer-clause that is 7449 // an assignment-expression is a constant expression. 7450 7451 // Do nothing on dependent types. 7452 if (DclT->isDependentType()) { 7453 7454 // Allow any 'static constexpr' members, whether or not they are of literal 7455 // type. We separately check that every constexpr variable is of literal 7456 // type. 7457 } else if (VDecl->isConstexpr()) { 7458 7459 // Require constness. 7460 } else if (!DclT.isConstQualified()) { 7461 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 7462 << Init->getSourceRange(); 7463 VDecl->setInvalidDecl(); 7464 7465 // We allow integer constant expressions in all cases. 7466 } else if (DclT->isIntegralOrEnumerationType()) { 7467 // Check whether the expression is a constant expression. 7468 SourceLocation Loc; 7469 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 7470 // In C++11, a non-constexpr const static data member with an 7471 // in-class initializer cannot be volatile. 7472 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 7473 else if (Init->isValueDependent()) 7474 ; // Nothing to check. 7475 else if (Init->isIntegerConstantExpr(Context, &Loc)) 7476 ; // Ok, it's an ICE! 7477 else if (Init->isEvaluatable(Context)) { 7478 // If we can constant fold the initializer through heroics, accept it, 7479 // but report this as a use of an extension for -pedantic. 7480 Diag(Loc, diag::ext_in_class_initializer_non_constant) 7481 << Init->getSourceRange(); 7482 } else { 7483 // Otherwise, this is some crazy unknown case. Report the issue at the 7484 // location provided by the isIntegerConstantExpr failed check. 7485 Diag(Loc, diag::err_in_class_initializer_non_constant) 7486 << Init->getSourceRange(); 7487 VDecl->setInvalidDecl(); 7488 } 7489 7490 // We allow foldable floating-point constants as an extension. 7491 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 7492 // In C++98, this is a GNU extension. In C++11, it is not, but we support 7493 // it anyway and provide a fixit to add the 'constexpr'. 7494 if (getLangOpts().CPlusPlus11) { 7495 Diag(VDecl->getLocation(), 7496 diag::ext_in_class_initializer_float_type_cxx11) 7497 << DclT << Init->getSourceRange(); 7498 Diag(VDecl->getLocStart(), 7499 diag::note_in_class_initializer_float_type_cxx11) 7500 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7501 } else { 7502 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 7503 << DclT << Init->getSourceRange(); 7504 7505 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 7506 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 7507 << Init->getSourceRange(); 7508 VDecl->setInvalidDecl(); 7509 } 7510 } 7511 7512 // Suggest adding 'constexpr' in C++11 for literal types. 7513 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType()) { 7514 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 7515 << DclT << Init->getSourceRange() 7516 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 7517 VDecl->setConstexpr(true); 7518 7519 } else { 7520 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 7521 << DclT << Init->getSourceRange(); 7522 VDecl->setInvalidDecl(); 7523 } 7524 } else if (VDecl->isFileVarDecl()) { 7525 if (VDecl->getStorageClassAsWritten() == SC_Extern && 7526 (!getLangOpts().CPlusPlus || 7527 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 7528 Diag(VDecl->getLocation(), diag::warn_extern_init); 7529 7530 // C99 6.7.8p4. All file scoped initializers need to be constant. 7531 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 7532 CheckForConstantInitializer(Init, DclT); 7533 } 7534 7535 // We will represent direct-initialization similarly to copy-initialization: 7536 // int x(1); -as-> int x = 1; 7537 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 7538 // 7539 // Clients that want to distinguish between the two forms, can check for 7540 // direct initializer using VarDecl::getInitStyle(). 7541 // A major benefit is that clients that don't particularly care about which 7542 // exactly form was it (like the CodeGen) can handle both cases without 7543 // special case code. 7544 7545 // C++ 8.5p11: 7546 // The form of initialization (using parentheses or '=') is generally 7547 // insignificant, but does matter when the entity being initialized has a 7548 // class type. 7549 if (CXXDirectInit) { 7550 assert(DirectInit && "Call-style initializer must be direct init."); 7551 VDecl->setInitStyle(VarDecl::CallInit); 7552 } else if (DirectInit) { 7553 // This must be list-initialization. No other way is direct-initialization. 7554 VDecl->setInitStyle(VarDecl::ListInit); 7555 } 7556 7557 CheckCompleteVariableDeclaration(VDecl); 7558} 7559 7560/// ActOnInitializerError - Given that there was an error parsing an 7561/// initializer for the given declaration, try to return to some form 7562/// of sanity. 7563void Sema::ActOnInitializerError(Decl *D) { 7564 // Our main concern here is re-establishing invariants like "a 7565 // variable's type is either dependent or complete". 7566 if (!D || D->isInvalidDecl()) return; 7567 7568 VarDecl *VD = dyn_cast<VarDecl>(D); 7569 if (!VD) return; 7570 7571 // Auto types are meaningless if we can't make sense of the initializer. 7572 if (ParsingInitForAutoVars.count(D)) { 7573 D->setInvalidDecl(); 7574 return; 7575 } 7576 7577 QualType Ty = VD->getType(); 7578 if (Ty->isDependentType()) return; 7579 7580 // Require a complete type. 7581 if (RequireCompleteType(VD->getLocation(), 7582 Context.getBaseElementType(Ty), 7583 diag::err_typecheck_decl_incomplete_type)) { 7584 VD->setInvalidDecl(); 7585 return; 7586 } 7587 7588 // Require an abstract type. 7589 if (RequireNonAbstractType(VD->getLocation(), Ty, 7590 diag::err_abstract_type_in_decl, 7591 AbstractVariableType)) { 7592 VD->setInvalidDecl(); 7593 return; 7594 } 7595 7596 // Don't bother complaining about constructors or destructors, 7597 // though. 7598} 7599 7600void Sema::ActOnUninitializedDecl(Decl *RealDecl, 7601 bool TypeMayContainAuto) { 7602 // If there is no declaration, there was an error parsing it. Just ignore it. 7603 if (RealDecl == 0) 7604 return; 7605 7606 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 7607 QualType Type = Var->getType(); 7608 7609 // C++11 [dcl.spec.auto]p3 7610 if (TypeMayContainAuto && Type->getContainedAutoType()) { 7611 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 7612 << Var->getDeclName() << Type; 7613 Var->setInvalidDecl(); 7614 return; 7615 } 7616 7617 // C++11 [class.static.data]p3: A static data member can be declared with 7618 // the constexpr specifier; if so, its declaration shall specify 7619 // a brace-or-equal-initializer. 7620 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 7621 // the definition of a variable [...] or the declaration of a static data 7622 // member. 7623 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 7624 if (Var->isStaticDataMember()) 7625 Diag(Var->getLocation(), 7626 diag::err_constexpr_static_mem_var_requires_init) 7627 << Var->getDeclName(); 7628 else 7629 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 7630 Var->setInvalidDecl(); 7631 return; 7632 } 7633 7634 switch (Var->isThisDeclarationADefinition()) { 7635 case VarDecl::Definition: 7636 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 7637 break; 7638 7639 // We have an out-of-line definition of a static data member 7640 // that has an in-class initializer, so we type-check this like 7641 // a declaration. 7642 // 7643 // Fall through 7644 7645 case VarDecl::DeclarationOnly: 7646 // It's only a declaration. 7647 7648 // Block scope. C99 6.7p7: If an identifier for an object is 7649 // declared with no linkage (C99 6.2.2p6), the type for the 7650 // object shall be complete. 7651 if (!Type->isDependentType() && Var->isLocalVarDecl() && 7652 !Var->getLinkage() && !Var->isInvalidDecl() && 7653 RequireCompleteType(Var->getLocation(), Type, 7654 diag::err_typecheck_decl_incomplete_type)) 7655 Var->setInvalidDecl(); 7656 7657 // Make sure that the type is not abstract. 7658 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7659 RequireNonAbstractType(Var->getLocation(), Type, 7660 diag::err_abstract_type_in_decl, 7661 AbstractVariableType)) 7662 Var->setInvalidDecl(); 7663 if (!Type->isDependentType() && !Var->isInvalidDecl() && 7664 Var->getStorageClass() == SC_PrivateExtern) { 7665 Diag(Var->getLocation(), diag::warn_private_extern); 7666 Diag(Var->getLocation(), diag::note_private_extern); 7667 } 7668 7669 return; 7670 7671 case VarDecl::TentativeDefinition: 7672 // File scope. C99 6.9.2p2: A declaration of an identifier for an 7673 // object that has file scope without an initializer, and without a 7674 // storage-class specifier or with the storage-class specifier "static", 7675 // constitutes a tentative definition. Note: A tentative definition with 7676 // external linkage is valid (C99 6.2.2p5). 7677 if (!Var->isInvalidDecl()) { 7678 if (const IncompleteArrayType *ArrayT 7679 = Context.getAsIncompleteArrayType(Type)) { 7680 if (RequireCompleteType(Var->getLocation(), 7681 ArrayT->getElementType(), 7682 diag::err_illegal_decl_array_incomplete_type)) 7683 Var->setInvalidDecl(); 7684 } else if (Var->getStorageClass() == SC_Static) { 7685 // C99 6.9.2p3: If the declaration of an identifier for an object is 7686 // a tentative definition and has internal linkage (C99 6.2.2p3), the 7687 // declared type shall not be an incomplete type. 7688 // NOTE: code such as the following 7689 // static struct s; 7690 // struct s { int a; }; 7691 // is accepted by gcc. Hence here we issue a warning instead of 7692 // an error and we do not invalidate the static declaration. 7693 // NOTE: to avoid multiple warnings, only check the first declaration. 7694 if (Var->getPreviousDecl() == 0) 7695 RequireCompleteType(Var->getLocation(), Type, 7696 diag::ext_typecheck_decl_incomplete_type); 7697 } 7698 } 7699 7700 // Record the tentative definition; we're done. 7701 if (!Var->isInvalidDecl()) 7702 TentativeDefinitions.push_back(Var); 7703 return; 7704 } 7705 7706 // Provide a specific diagnostic for uninitialized variable 7707 // definitions with incomplete array type. 7708 if (Type->isIncompleteArrayType()) { 7709 Diag(Var->getLocation(), 7710 diag::err_typecheck_incomplete_array_needs_initializer); 7711 Var->setInvalidDecl(); 7712 return; 7713 } 7714 7715 // Provide a specific diagnostic for uninitialized variable 7716 // definitions with reference type. 7717 if (Type->isReferenceType()) { 7718 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 7719 << Var->getDeclName() 7720 << SourceRange(Var->getLocation(), Var->getLocation()); 7721 Var->setInvalidDecl(); 7722 return; 7723 } 7724 7725 // Do not attempt to type-check the default initializer for a 7726 // variable with dependent type. 7727 if (Type->isDependentType()) 7728 return; 7729 7730 if (Var->isInvalidDecl()) 7731 return; 7732 7733 if (RequireCompleteType(Var->getLocation(), 7734 Context.getBaseElementType(Type), 7735 diag::err_typecheck_decl_incomplete_type)) { 7736 Var->setInvalidDecl(); 7737 return; 7738 } 7739 7740 // The variable can not have an abstract class type. 7741 if (RequireNonAbstractType(Var->getLocation(), Type, 7742 diag::err_abstract_type_in_decl, 7743 AbstractVariableType)) { 7744 Var->setInvalidDecl(); 7745 return; 7746 } 7747 7748 // Check for jumps past the implicit initializer. C++0x 7749 // clarifies that this applies to a "variable with automatic 7750 // storage duration", not a "local variable". 7751 // C++11 [stmt.dcl]p3 7752 // A program that jumps from a point where a variable with automatic 7753 // storage duration is not in scope to a point where it is in scope is 7754 // ill-formed unless the variable has scalar type, class type with a 7755 // trivial default constructor and a trivial destructor, a cv-qualified 7756 // version of one of these types, or an array of one of the preceding 7757 // types and is declared without an initializer. 7758 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 7759 if (const RecordType *Record 7760 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 7761 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 7762 // Mark the function for further checking even if the looser rules of 7763 // C++11 do not require such checks, so that we can diagnose 7764 // incompatibilities with C++98. 7765 if (!CXXRecord->isPOD()) 7766 getCurFunction()->setHasBranchProtectedScope(); 7767 } 7768 } 7769 7770 // C++03 [dcl.init]p9: 7771 // If no initializer is specified for an object, and the 7772 // object is of (possibly cv-qualified) non-POD class type (or 7773 // array thereof), the object shall be default-initialized; if 7774 // the object is of const-qualified type, the underlying class 7775 // type shall have a user-declared default 7776 // constructor. Otherwise, if no initializer is specified for 7777 // a non- static object, the object and its subobjects, if 7778 // any, have an indeterminate initial value); if the object 7779 // or any of its subobjects are of const-qualified type, the 7780 // program is ill-formed. 7781 // C++0x [dcl.init]p11: 7782 // If no initializer is specified for an object, the object is 7783 // default-initialized; [...]. 7784 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 7785 InitializationKind Kind 7786 = InitializationKind::CreateDefault(Var->getLocation()); 7787 7788 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 7789 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, MultiExprArg()); 7790 if (Init.isInvalid()) 7791 Var->setInvalidDecl(); 7792 else if (Init.get()) { 7793 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 7794 // This is important for template substitution. 7795 Var->setInitStyle(VarDecl::CallInit); 7796 } 7797 7798 CheckCompleteVariableDeclaration(Var); 7799 } 7800} 7801 7802void Sema::ActOnCXXForRangeDecl(Decl *D) { 7803 VarDecl *VD = dyn_cast<VarDecl>(D); 7804 if (!VD) { 7805 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 7806 D->setInvalidDecl(); 7807 return; 7808 } 7809 7810 VD->setCXXForRangeDecl(true); 7811 7812 // for-range-declaration cannot be given a storage class specifier. 7813 int Error = -1; 7814 switch (VD->getStorageClassAsWritten()) { 7815 case SC_None: 7816 break; 7817 case SC_Extern: 7818 Error = 0; 7819 break; 7820 case SC_Static: 7821 Error = 1; 7822 break; 7823 case SC_PrivateExtern: 7824 Error = 2; 7825 break; 7826 case SC_Auto: 7827 Error = 3; 7828 break; 7829 case SC_Register: 7830 Error = 4; 7831 break; 7832 case SC_OpenCLWorkGroupLocal: 7833 llvm_unreachable("Unexpected storage class"); 7834 } 7835 if (VD->isConstexpr()) 7836 Error = 5; 7837 if (Error != -1) { 7838 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 7839 << VD->getDeclName() << Error; 7840 D->setInvalidDecl(); 7841 } 7842} 7843 7844void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 7845 if (var->isInvalidDecl()) return; 7846 7847 // In ARC, don't allow jumps past the implicit initialization of a 7848 // local retaining variable. 7849 if (getLangOpts().ObjCAutoRefCount && 7850 var->hasLocalStorage()) { 7851 switch (var->getType().getObjCLifetime()) { 7852 case Qualifiers::OCL_None: 7853 case Qualifiers::OCL_ExplicitNone: 7854 case Qualifiers::OCL_Autoreleasing: 7855 break; 7856 7857 case Qualifiers::OCL_Weak: 7858 case Qualifiers::OCL_Strong: 7859 getCurFunction()->setHasBranchProtectedScope(); 7860 break; 7861 } 7862 } 7863 7864 if (var->isThisDeclarationADefinition() && 7865 var->hasExternalLinkage() && 7866 getDiagnostics().getDiagnosticLevel( 7867 diag::warn_missing_variable_declarations, 7868 var->getLocation())) { 7869 // Find a previous declaration that's not a definition. 7870 VarDecl *prev = var->getPreviousDecl(); 7871 while (prev && prev->isThisDeclarationADefinition()) 7872 prev = prev->getPreviousDecl(); 7873 7874 if (!prev) 7875 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 7876 } 7877 7878 // All the following checks are C++ only. 7879 if (!getLangOpts().CPlusPlus) return; 7880 7881 QualType type = var->getType(); 7882 if (type->isDependentType()) return; 7883 7884 // __block variables might require us to capture a copy-initializer. 7885 if (var->hasAttr<BlocksAttr>()) { 7886 // It's currently invalid to ever have a __block variable with an 7887 // array type; should we diagnose that here? 7888 7889 // Regardless, we don't want to ignore array nesting when 7890 // constructing this copy. 7891 if (type->isStructureOrClassType()) { 7892 SourceLocation poi = var->getLocation(); 7893 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 7894 ExprResult result 7895 = PerformMoveOrCopyInitialization( 7896 InitializedEntity::InitializeBlock(poi, type, false), 7897 var, var->getType(), varRef, /*AllowNRVO=*/true); 7898 if (!result.isInvalid()) { 7899 result = MaybeCreateExprWithCleanups(result); 7900 Expr *init = result.takeAs<Expr>(); 7901 Context.setBlockVarCopyInits(var, init); 7902 } 7903 } 7904 } 7905 7906 Expr *Init = var->getInit(); 7907 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 7908 QualType baseType = Context.getBaseElementType(type); 7909 7910 if (!var->getDeclContext()->isDependentContext() && 7911 Init && !Init->isValueDependent()) { 7912 if (IsGlobal && !var->isConstexpr() && 7913 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 7914 var->getLocation()) 7915 != DiagnosticsEngine::Ignored && 7916 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 7917 Diag(var->getLocation(), diag::warn_global_constructor) 7918 << Init->getSourceRange(); 7919 7920 if (var->isConstexpr()) { 7921 SmallVector<PartialDiagnosticAt, 8> Notes; 7922 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 7923 SourceLocation DiagLoc = var->getLocation(); 7924 // If the note doesn't add any useful information other than a source 7925 // location, fold it into the primary diagnostic. 7926 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 7927 diag::note_invalid_subexpr_in_const_expr) { 7928 DiagLoc = Notes[0].first; 7929 Notes.clear(); 7930 } 7931 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 7932 << var << Init->getSourceRange(); 7933 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 7934 Diag(Notes[I].first, Notes[I].second); 7935 } 7936 } else if (var->isUsableInConstantExpressions(Context)) { 7937 // Check whether the initializer of a const variable of integral or 7938 // enumeration type is an ICE now, since we can't tell whether it was 7939 // initialized by a constant expression if we check later. 7940 var->checkInitIsICE(); 7941 } 7942 } 7943 7944 // Require the destructor. 7945 if (const RecordType *recordType = baseType->getAs<RecordType>()) 7946 FinalizeVarWithDestructor(var, recordType); 7947} 7948 7949/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 7950/// any semantic actions necessary after any initializer has been attached. 7951void 7952Sema::FinalizeDeclaration(Decl *ThisDecl) { 7953 // Note that we are no longer parsing the initializer for this declaration. 7954 ParsingInitForAutoVars.erase(ThisDecl); 7955 7956 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 7957 if (!VD) 7958 return; 7959 7960 const DeclContext *DC = VD->getDeclContext(); 7961 // If there's a #pragma GCC visibility in scope, and this isn't a class 7962 // member, set the visibility of this variable. 7963 if (!DC->isRecord() && VD->hasExternalLinkage()) 7964 AddPushedVisibilityAttribute(VD); 7965 7966 if (VD->isFileVarDecl()) 7967 MarkUnusedFileScopedDecl(VD); 7968 7969 // Now we have parsed the initializer and can update the table of magic 7970 // tag values. 7971 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 7972 !VD->getType()->isIntegralOrEnumerationType()) 7973 return; 7974 7975 for (specific_attr_iterator<TypeTagForDatatypeAttr> 7976 I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(), 7977 E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>(); 7978 I != E; ++I) { 7979 const Expr *MagicValueExpr = VD->getInit(); 7980 if (!MagicValueExpr) { 7981 continue; 7982 } 7983 llvm::APSInt MagicValueInt; 7984 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 7985 Diag(I->getRange().getBegin(), 7986 diag::err_type_tag_for_datatype_not_ice) 7987 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7988 continue; 7989 } 7990 if (MagicValueInt.getActiveBits() > 64) { 7991 Diag(I->getRange().getBegin(), 7992 diag::err_type_tag_for_datatype_too_large) 7993 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 7994 continue; 7995 } 7996 uint64_t MagicValue = MagicValueInt.getZExtValue(); 7997 RegisterTypeTagForDatatype(I->getArgumentKind(), 7998 MagicValue, 7999 I->getMatchingCType(), 8000 I->getLayoutCompatible(), 8001 I->getMustBeNull()); 8002 } 8003} 8004 8005Sema::DeclGroupPtrTy 8006Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 8007 Decl **Group, unsigned NumDecls) { 8008 SmallVector<Decl*, 8> Decls; 8009 8010 if (DS.isTypeSpecOwned()) 8011 Decls.push_back(DS.getRepAsDecl()); 8012 8013 for (unsigned i = 0; i != NumDecls; ++i) 8014 if (Decl *D = Group[i]) 8015 Decls.push_back(D); 8016 8017 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) 8018 if (const TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) 8019 getASTContext().addUnnamedTag(Tag); 8020 8021 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 8022 DS.getTypeSpecType() == DeclSpec::TST_auto); 8023} 8024 8025/// BuildDeclaratorGroup - convert a list of declarations into a declaration 8026/// group, performing any necessary semantic checking. 8027Sema::DeclGroupPtrTy 8028Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 8029 bool TypeMayContainAuto) { 8030 // C++0x [dcl.spec.auto]p7: 8031 // If the type deduced for the template parameter U is not the same in each 8032 // deduction, the program is ill-formed. 8033 // FIXME: When initializer-list support is added, a distinction is needed 8034 // between the deduced type U and the deduced type which 'auto' stands for. 8035 // auto a = 0, b = { 1, 2, 3 }; 8036 // is legal because the deduced type U is 'int' in both cases. 8037 if (TypeMayContainAuto && NumDecls > 1) { 8038 QualType Deduced; 8039 CanQualType DeducedCanon; 8040 VarDecl *DeducedDecl = 0; 8041 for (unsigned i = 0; i != NumDecls; ++i) { 8042 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 8043 AutoType *AT = D->getType()->getContainedAutoType(); 8044 // Don't reissue diagnostics when instantiating a template. 8045 if (AT && D->isInvalidDecl()) 8046 break; 8047 if (AT && AT->isDeduced()) { 8048 QualType U = AT->getDeducedType(); 8049 CanQualType UCanon = Context.getCanonicalType(U); 8050 if (Deduced.isNull()) { 8051 Deduced = U; 8052 DeducedCanon = UCanon; 8053 DeducedDecl = D; 8054 } else if (DeducedCanon != UCanon) { 8055 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 8056 diag::err_auto_different_deductions) 8057 << Deduced << DeducedDecl->getDeclName() 8058 << U << D->getDeclName() 8059 << DeducedDecl->getInit()->getSourceRange() 8060 << D->getInit()->getSourceRange(); 8061 D->setInvalidDecl(); 8062 break; 8063 } 8064 } 8065 } 8066 } 8067 } 8068 8069 ActOnDocumentableDecls(Group, NumDecls); 8070 8071 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 8072} 8073 8074void Sema::ActOnDocumentableDecl(Decl *D) { 8075 ActOnDocumentableDecls(&D, 1); 8076} 8077 8078void Sema::ActOnDocumentableDecls(Decl **Group, unsigned NumDecls) { 8079 // Don't parse the comment if Doxygen diagnostics are ignored. 8080 if (NumDecls == 0 || !Group[0]) 8081 return; 8082 8083 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 8084 Group[0]->getLocation()) 8085 == DiagnosticsEngine::Ignored) 8086 return; 8087 8088 if (NumDecls >= 2) { 8089 // This is a decl group. Normally it will contain only declarations 8090 // procuded from declarator list. But in case we have any definitions or 8091 // additional declaration references: 8092 // 'typedef struct S {} S;' 8093 // 'typedef struct S *S;' 8094 // 'struct S *pS;' 8095 // FinalizeDeclaratorGroup adds these as separate declarations. 8096 Decl *MaybeTagDecl = Group[0]; 8097 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 8098 Group++; 8099 NumDecls--; 8100 } 8101 } 8102 8103 // See if there are any new comments that are not attached to a decl. 8104 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 8105 if (!Comments.empty() && 8106 !Comments.back()->isAttached()) { 8107 // There is at least one comment that not attached to a decl. 8108 // Maybe it should be attached to one of these decls? 8109 // 8110 // Note that this way we pick up not only comments that precede the 8111 // declaration, but also comments that *follow* the declaration -- thanks to 8112 // the lookahead in the lexer: we've consumed the semicolon and looked 8113 // ahead through comments. 8114 for (unsigned i = 0; i != NumDecls; ++i) 8115 Context.getCommentForDecl(Group[i], &PP); 8116 } 8117} 8118 8119/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 8120/// to introduce parameters into function prototype scope. 8121Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 8122 const DeclSpec &DS = D.getDeclSpec(); 8123 8124 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 8125 // C++03 [dcl.stc]p2 also permits 'auto'. 8126 VarDecl::StorageClass StorageClass = SC_None; 8127 VarDecl::StorageClass StorageClassAsWritten = SC_None; 8128 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 8129 StorageClass = SC_Register; 8130 StorageClassAsWritten = SC_Register; 8131 } else if (getLangOpts().CPlusPlus && 8132 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 8133 StorageClass = SC_Auto; 8134 StorageClassAsWritten = SC_Auto; 8135 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 8136 Diag(DS.getStorageClassSpecLoc(), 8137 diag::err_invalid_storage_class_in_func_decl); 8138 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8139 } 8140 8141 if (D.getDeclSpec().isThreadSpecified()) 8142 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 8143 if (D.getDeclSpec().isConstexprSpecified()) 8144 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 8145 << 0; 8146 8147 DiagnoseFunctionSpecifiers(D); 8148 8149 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 8150 QualType parmDeclType = TInfo->getType(); 8151 8152 if (getLangOpts().CPlusPlus) { 8153 // Check that there are no default arguments inside the type of this 8154 // parameter. 8155 CheckExtraCXXDefaultArguments(D); 8156 8157 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 8158 if (D.getCXXScopeSpec().isSet()) { 8159 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 8160 << D.getCXXScopeSpec().getRange(); 8161 D.getCXXScopeSpec().clear(); 8162 } 8163 } 8164 8165 // Ensure we have a valid name 8166 IdentifierInfo *II = 0; 8167 if (D.hasName()) { 8168 II = D.getIdentifier(); 8169 if (!II) { 8170 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 8171 << GetNameForDeclarator(D).getName().getAsString(); 8172 D.setInvalidType(true); 8173 } 8174 } 8175 8176 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 8177 if (II) { 8178 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 8179 ForRedeclaration); 8180 LookupName(R, S); 8181 if (R.isSingleResult()) { 8182 NamedDecl *PrevDecl = R.getFoundDecl(); 8183 if (PrevDecl->isTemplateParameter()) { 8184 // Maybe we will complain about the shadowed template parameter. 8185 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 8186 // Just pretend that we didn't see the previous declaration. 8187 PrevDecl = 0; 8188 } else if (S->isDeclScope(PrevDecl)) { 8189 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 8190 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 8191 8192 // Recover by removing the name 8193 II = 0; 8194 D.SetIdentifier(0, D.getIdentifierLoc()); 8195 D.setInvalidType(true); 8196 } 8197 } 8198 } 8199 8200 // Temporarily put parameter variables in the translation unit, not 8201 // the enclosing context. This prevents them from accidentally 8202 // looking like class members in C++. 8203 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 8204 D.getLocStart(), 8205 D.getIdentifierLoc(), II, 8206 parmDeclType, TInfo, 8207 StorageClass, StorageClassAsWritten); 8208 8209 if (D.isInvalidType()) 8210 New->setInvalidDecl(); 8211 8212 assert(S->isFunctionPrototypeScope()); 8213 assert(S->getFunctionPrototypeDepth() >= 1); 8214 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 8215 S->getNextFunctionPrototypeIndex()); 8216 8217 // Add the parameter declaration into this scope. 8218 S->AddDecl(New); 8219 if (II) 8220 IdResolver.AddDecl(New); 8221 8222 ProcessDeclAttributes(S, New, D); 8223 8224 if (D.getDeclSpec().isModulePrivateSpecified()) 8225 Diag(New->getLocation(), diag::err_module_private_local) 8226 << 1 << New->getDeclName() 8227 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 8228 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 8229 8230 if (New->hasAttr<BlocksAttr>()) { 8231 Diag(New->getLocation(), diag::err_block_on_nonlocal); 8232 } 8233 return New; 8234} 8235 8236/// \brief Synthesizes a variable for a parameter arising from a 8237/// typedef. 8238ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 8239 SourceLocation Loc, 8240 QualType T) { 8241 /* FIXME: setting StartLoc == Loc. 8242 Would it be worth to modify callers so as to provide proper source 8243 location for the unnamed parameters, embedding the parameter's type? */ 8244 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 8245 T, Context.getTrivialTypeSourceInfo(T, Loc), 8246 SC_None, SC_None, 0); 8247 Param->setImplicit(); 8248 return Param; 8249} 8250 8251void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 8252 ParmVarDecl * const *ParamEnd) { 8253 // Don't diagnose unused-parameter errors in template instantiations; we 8254 // will already have done so in the template itself. 8255 if (!ActiveTemplateInstantiations.empty()) 8256 return; 8257 8258 for (; Param != ParamEnd; ++Param) { 8259 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 8260 !(*Param)->hasAttr<UnusedAttr>()) { 8261 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 8262 << (*Param)->getDeclName(); 8263 } 8264 } 8265} 8266 8267void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 8268 ParmVarDecl * const *ParamEnd, 8269 QualType ReturnTy, 8270 NamedDecl *D) { 8271 if (LangOpts.NumLargeByValueCopy == 0) // No check. 8272 return; 8273 8274 // Warn if the return value is pass-by-value and larger than the specified 8275 // threshold. 8276 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 8277 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 8278 if (Size > LangOpts.NumLargeByValueCopy) 8279 Diag(D->getLocation(), diag::warn_return_value_size) 8280 << D->getDeclName() << Size; 8281 } 8282 8283 // Warn if any parameter is pass-by-value and larger than the specified 8284 // threshold. 8285 for (; Param != ParamEnd; ++Param) { 8286 QualType T = (*Param)->getType(); 8287 if (T->isDependentType() || !T.isPODType(Context)) 8288 continue; 8289 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 8290 if (Size > LangOpts.NumLargeByValueCopy) 8291 Diag((*Param)->getLocation(), diag::warn_parameter_size) 8292 << (*Param)->getDeclName() << Size; 8293 } 8294} 8295 8296ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 8297 SourceLocation NameLoc, IdentifierInfo *Name, 8298 QualType T, TypeSourceInfo *TSInfo, 8299 VarDecl::StorageClass StorageClass, 8300 VarDecl::StorageClass StorageClassAsWritten) { 8301 // In ARC, infer a lifetime qualifier for appropriate parameter types. 8302 if (getLangOpts().ObjCAutoRefCount && 8303 T.getObjCLifetime() == Qualifiers::OCL_None && 8304 T->isObjCLifetimeType()) { 8305 8306 Qualifiers::ObjCLifetime lifetime; 8307 8308 // Special cases for arrays: 8309 // - if it's const, use __unsafe_unretained 8310 // - otherwise, it's an error 8311 if (T->isArrayType()) { 8312 if (!T.isConstQualified()) { 8313 DelayedDiagnostics.add( 8314 sema::DelayedDiagnostic::makeForbiddenType( 8315 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 8316 } 8317 lifetime = Qualifiers::OCL_ExplicitNone; 8318 } else { 8319 lifetime = T->getObjCARCImplicitLifetime(); 8320 } 8321 T = Context.getLifetimeQualifiedType(T, lifetime); 8322 } 8323 8324 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 8325 Context.getAdjustedParameterType(T), 8326 TSInfo, 8327 StorageClass, StorageClassAsWritten, 8328 0); 8329 8330 // Parameters can not be abstract class types. 8331 // For record types, this is done by the AbstractClassUsageDiagnoser once 8332 // the class has been completely parsed. 8333 if (!CurContext->isRecord() && 8334 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 8335 AbstractParamType)) 8336 New->setInvalidDecl(); 8337 8338 // Parameter declarators cannot be interface types. All ObjC objects are 8339 // passed by reference. 8340 if (T->isObjCObjectType()) { 8341 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 8342 Diag(NameLoc, 8343 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 8344 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 8345 T = Context.getObjCObjectPointerType(T); 8346 New->setType(T); 8347 } 8348 8349 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 8350 // duration shall not be qualified by an address-space qualifier." 8351 // Since all parameters have automatic store duration, they can not have 8352 // an address space. 8353 if (T.getAddressSpace() != 0) { 8354 Diag(NameLoc, diag::err_arg_with_address_space); 8355 New->setInvalidDecl(); 8356 } 8357 8358 return New; 8359} 8360 8361void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 8362 SourceLocation LocAfterDecls) { 8363 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8364 8365 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 8366 // for a K&R function. 8367 if (!FTI.hasPrototype) { 8368 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 8369 --i; 8370 if (FTI.ArgInfo[i].Param == 0) { 8371 SmallString<256> Code; 8372 llvm::raw_svector_ostream(Code) << " int " 8373 << FTI.ArgInfo[i].Ident->getName() 8374 << ";\n"; 8375 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 8376 << FTI.ArgInfo[i].Ident 8377 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 8378 8379 // Implicitly declare the argument as type 'int' for lack of a better 8380 // type. 8381 AttributeFactory attrs; 8382 DeclSpec DS(attrs); 8383 const char* PrevSpec; // unused 8384 unsigned DiagID; // unused 8385 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 8386 PrevSpec, DiagID); 8387 // Use the identifier location for the type source range. 8388 DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc); 8389 DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc); 8390 Declarator ParamD(DS, Declarator::KNRTypeListContext); 8391 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 8392 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 8393 } 8394 } 8395 } 8396} 8397 8398Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 8399 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 8400 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 8401 Scope *ParentScope = FnBodyScope->getParent(); 8402 8403 D.setFunctionDefinitionKind(FDK_Definition); 8404 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 8405 return ActOnStartOfFunctionDef(FnBodyScope, DP); 8406} 8407 8408static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 8409 const FunctionDecl*& PossibleZeroParamPrototype) { 8410 // Don't warn about invalid declarations. 8411 if (FD->isInvalidDecl()) 8412 return false; 8413 8414 // Or declarations that aren't global. 8415 if (!FD->isGlobal()) 8416 return false; 8417 8418 // Don't warn about C++ member functions. 8419 if (isa<CXXMethodDecl>(FD)) 8420 return false; 8421 8422 // Don't warn about 'main'. 8423 if (FD->isMain()) 8424 return false; 8425 8426 // Don't warn about inline functions. 8427 if (FD->isInlined()) 8428 return false; 8429 8430 // Don't warn about function templates. 8431 if (FD->getDescribedFunctionTemplate()) 8432 return false; 8433 8434 // Don't warn about function template specializations. 8435 if (FD->isFunctionTemplateSpecialization()) 8436 return false; 8437 8438 // Don't warn for OpenCL kernels. 8439 if (FD->hasAttr<OpenCLKernelAttr>()) 8440 return false; 8441 8442 bool MissingPrototype = true; 8443 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 8444 Prev; Prev = Prev->getPreviousDecl()) { 8445 // Ignore any declarations that occur in function or method 8446 // scope, because they aren't visible from the header. 8447 if (Prev->getDeclContext()->isFunctionOrMethod()) 8448 continue; 8449 8450 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 8451 if (FD->getNumParams() == 0) 8452 PossibleZeroParamPrototype = Prev; 8453 break; 8454 } 8455 8456 return MissingPrototype; 8457} 8458 8459void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 8460 // Don't complain if we're in GNU89 mode and the previous definition 8461 // was an extern inline function. 8462 const FunctionDecl *Definition; 8463 if (FD->isDefined(Definition) && 8464 !canRedefineFunction(Definition, getLangOpts())) { 8465 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 8466 Definition->getStorageClass() == SC_Extern) 8467 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 8468 << FD->getDeclName() << getLangOpts().CPlusPlus; 8469 else 8470 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 8471 Diag(Definition->getLocation(), diag::note_previous_definition); 8472 FD->setInvalidDecl(); 8473 } 8474} 8475 8476Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 8477 // Clear the last template instantiation error context. 8478 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 8479 8480 if (!D) 8481 return D; 8482 FunctionDecl *FD = 0; 8483 8484 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 8485 FD = FunTmpl->getTemplatedDecl(); 8486 else 8487 FD = cast<FunctionDecl>(D); 8488 8489 // Enter a new function scope 8490 PushFunctionScope(); 8491 8492 // See if this is a redefinition. 8493 if (!FD->isLateTemplateParsed()) 8494 CheckForFunctionRedefinition(FD); 8495 8496 // Builtin functions cannot be defined. 8497 if (unsigned BuiltinID = FD->getBuiltinID()) { 8498 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 8499 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 8500 FD->setInvalidDecl(); 8501 } 8502 } 8503 8504 // The return type of a function definition must be complete 8505 // (C99 6.9.1p3, C++ [dcl.fct]p6). 8506 QualType ResultType = FD->getResultType(); 8507 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 8508 !FD->isInvalidDecl() && 8509 RequireCompleteType(FD->getLocation(), ResultType, 8510 diag::err_func_def_incomplete_result)) 8511 FD->setInvalidDecl(); 8512 8513 // GNU warning -Wmissing-prototypes: 8514 // Warn if a global function is defined without a previous 8515 // prototype declaration. This warning is issued even if the 8516 // definition itself provides a prototype. The aim is to detect 8517 // global functions that fail to be declared in header files. 8518 const FunctionDecl *PossibleZeroParamPrototype = 0; 8519 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 8520 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 8521 8522 if (PossibleZeroParamPrototype) { 8523 // We found a declaration that is not a prototype, 8524 // but that could be a zero-parameter prototype 8525 TypeSourceInfo* TI = PossibleZeroParamPrototype->getTypeSourceInfo(); 8526 TypeLoc TL = TI->getTypeLoc(); 8527 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 8528 Diag(PossibleZeroParamPrototype->getLocation(), 8529 diag::note_declaration_not_a_prototype) 8530 << PossibleZeroParamPrototype 8531 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 8532 } 8533 } 8534 8535 if (FnBodyScope) 8536 PushDeclContext(FnBodyScope, FD); 8537 8538 // Check the validity of our function parameters 8539 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 8540 /*CheckParameterNames=*/true); 8541 8542 // Introduce our parameters into the function scope 8543 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 8544 ParmVarDecl *Param = FD->getParamDecl(p); 8545 Param->setOwningFunction(FD); 8546 8547 // If this has an identifier, add it to the scope stack. 8548 if (Param->getIdentifier() && FnBodyScope) { 8549 CheckShadow(FnBodyScope, Param); 8550 8551 PushOnScopeChains(Param, FnBodyScope); 8552 } 8553 } 8554 8555 // If we had any tags defined in the function prototype, 8556 // introduce them into the function scope. 8557 if (FnBodyScope) { 8558 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 8559 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 8560 NamedDecl *D = *I; 8561 8562 // Some of these decls (like enums) may have been pinned to the translation unit 8563 // for lack of a real context earlier. If so, remove from the translation unit 8564 // and reattach to the current context. 8565 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 8566 // Is the decl actually in the context? 8567 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 8568 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 8569 if (*DI == D) { 8570 Context.getTranslationUnitDecl()->removeDecl(D); 8571 break; 8572 } 8573 } 8574 // Either way, reassign the lexical decl context to our FunctionDecl. 8575 D->setLexicalDeclContext(CurContext); 8576 } 8577 8578 // If the decl has a non-null name, make accessible in the current scope. 8579 if (!D->getName().empty()) 8580 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 8581 8582 // Similarly, dive into enums and fish their constants out, making them 8583 // accessible in this scope. 8584 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 8585 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 8586 EE = ED->enumerator_end(); EI != EE; ++EI) 8587 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false); 8588 } 8589 } 8590 } 8591 8592 // Ensure that the function's exception specification is instantiated. 8593 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 8594 ResolveExceptionSpec(D->getLocation(), FPT); 8595 8596 // Checking attributes of current function definition 8597 // dllimport attribute. 8598 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 8599 if (DA && (!FD->getAttr<DLLExportAttr>())) { 8600 // dllimport attribute cannot be directly applied to definition. 8601 // Microsoft accepts dllimport for functions defined within class scope. 8602 if (!DA->isInherited() && 8603 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 8604 Diag(FD->getLocation(), 8605 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 8606 << "dllimport"; 8607 FD->setInvalidDecl(); 8608 return D; 8609 } 8610 8611 // Visual C++ appears to not think this is an issue, so only issue 8612 // a warning when Microsoft extensions are disabled. 8613 if (!LangOpts.MicrosoftExt) { 8614 // If a symbol previously declared dllimport is later defined, the 8615 // attribute is ignored in subsequent references, and a warning is 8616 // emitted. 8617 Diag(FD->getLocation(), 8618 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 8619 << FD->getName() << "dllimport"; 8620 } 8621 } 8622 // We want to attach documentation to original Decl (which might be 8623 // a function template). 8624 ActOnDocumentableDecl(D); 8625 return D; 8626} 8627 8628/// \brief Given the set of return statements within a function body, 8629/// compute the variables that are subject to the named return value 8630/// optimization. 8631/// 8632/// Each of the variables that is subject to the named return value 8633/// optimization will be marked as NRVO variables in the AST, and any 8634/// return statement that has a marked NRVO variable as its NRVO candidate can 8635/// use the named return value optimization. 8636/// 8637/// This function applies a very simplistic algorithm for NRVO: if every return 8638/// statement in the function has the same NRVO candidate, that candidate is 8639/// the NRVO variable. 8640/// 8641/// FIXME: Employ a smarter algorithm that accounts for multiple return 8642/// statements and the lifetimes of the NRVO candidates. We should be able to 8643/// find a maximal set of NRVO variables. 8644void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 8645 ReturnStmt **Returns = Scope->Returns.data(); 8646 8647 const VarDecl *NRVOCandidate = 0; 8648 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 8649 if (!Returns[I]->getNRVOCandidate()) 8650 return; 8651 8652 if (!NRVOCandidate) 8653 NRVOCandidate = Returns[I]->getNRVOCandidate(); 8654 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 8655 return; 8656 } 8657 8658 if (NRVOCandidate) 8659 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 8660} 8661 8662bool Sema::canSkipFunctionBody(Decl *D) { 8663 if (!Consumer.shouldSkipFunctionBody(D)) 8664 return false; 8665 8666 if (isa<ObjCMethodDecl>(D)) 8667 return true; 8668 8669 FunctionDecl *FD = 0; 8670 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) 8671 FD = FTD->getTemplatedDecl(); 8672 else 8673 FD = cast<FunctionDecl>(D); 8674 8675 // We cannot skip the body of a function (or function template) which is 8676 // constexpr, since we may need to evaluate its body in order to parse the 8677 // rest of the file. 8678 return !FD->isConstexpr(); 8679} 8680 8681Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 8682 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 8683 FD->setHasSkippedBody(); 8684 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 8685 MD->setHasSkippedBody(); 8686 return ActOnFinishFunctionBody(Decl, 0); 8687} 8688 8689Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 8690 return ActOnFinishFunctionBody(D, BodyArg, false); 8691} 8692 8693Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 8694 bool IsInstantiation) { 8695 FunctionDecl *FD = 0; 8696 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 8697 if (FunTmpl) 8698 FD = FunTmpl->getTemplatedDecl(); 8699 else 8700 FD = dyn_cast_or_null<FunctionDecl>(dcl); 8701 8702 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 8703 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 8704 8705 if (FD) { 8706 FD->setBody(Body); 8707 8708 // The only way to be included in UndefinedButUsed is if there is an 8709 // ODR use before the definition. Avoid the expensive map lookup if this 8710 // is the first declaration. 8711 if (FD->getPreviousDecl() != 0 && FD->getPreviousDecl()->isUsed()) { 8712 if (FD->getLinkage() != ExternalLinkage) 8713 UndefinedButUsed.erase(FD); 8714 else if (FD->isInlined() && 8715 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 8716 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 8717 UndefinedButUsed.erase(FD); 8718 } 8719 8720 // If the function implicitly returns zero (like 'main') or is naked, 8721 // don't complain about missing return statements. 8722 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 8723 WP.disableCheckFallThrough(); 8724 8725 // MSVC permits the use of pure specifier (=0) on function definition, 8726 // defined at class scope, warn about this non standard construct. 8727 if (getLangOpts().MicrosoftExt && FD->isPure()) 8728 Diag(FD->getLocation(), diag::warn_pure_function_definition); 8729 8730 if (!FD->isInvalidDecl()) { 8731 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 8732 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 8733 FD->getResultType(), FD); 8734 8735 // If this is a constructor, we need a vtable. 8736 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 8737 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 8738 8739 // Try to apply the named return value optimization. We have to check 8740 // if we can do this here because lambdas keep return statements around 8741 // to deduce an implicit return type. 8742 if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() && 8743 !FD->isDependentContext()) 8744 computeNRVO(Body, getCurFunction()); 8745 } 8746 8747 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 8748 "Function parsing confused"); 8749 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 8750 assert(MD == getCurMethodDecl() && "Method parsing confused"); 8751 MD->setBody(Body); 8752 if (!MD->isInvalidDecl()) { 8753 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 8754 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 8755 MD->getResultType(), MD); 8756 8757 if (Body) 8758 computeNRVO(Body, getCurFunction()); 8759 } 8760 if (getCurFunction()->ObjCShouldCallSuper) { 8761 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 8762 << MD->getSelector().getAsString(); 8763 getCurFunction()->ObjCShouldCallSuper = false; 8764 } 8765 } else { 8766 return 0; 8767 } 8768 8769 assert(!getCurFunction()->ObjCShouldCallSuper && 8770 "This should only be set for ObjC methods, which should have been " 8771 "handled in the block above."); 8772 8773 // Verify and clean out per-function state. 8774 if (Body) { 8775 // C++ constructors that have function-try-blocks can't have return 8776 // statements in the handlers of that block. (C++ [except.handle]p14) 8777 // Verify this. 8778 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 8779 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 8780 8781 // Verify that gotos and switch cases don't jump into scopes illegally. 8782 if (getCurFunction()->NeedsScopeChecking() && 8783 !dcl->isInvalidDecl() && 8784 !hasAnyUnrecoverableErrorsInThisFunction() && 8785 !PP.isCodeCompletionEnabled()) 8786 DiagnoseInvalidJumps(Body); 8787 8788 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 8789 if (!Destructor->getParent()->isDependentType()) 8790 CheckDestructor(Destructor); 8791 8792 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8793 Destructor->getParent()); 8794 } 8795 8796 // If any errors have occurred, clear out any temporaries that may have 8797 // been leftover. This ensures that these temporaries won't be picked up for 8798 // deletion in some later function. 8799 if (PP.getDiagnostics().hasErrorOccurred() || 8800 PP.getDiagnostics().getSuppressAllDiagnostics()) { 8801 DiscardCleanupsInEvaluationContext(); 8802 } 8803 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 8804 !isa<FunctionTemplateDecl>(dcl)) { 8805 // Since the body is valid, issue any analysis-based warnings that are 8806 // enabled. 8807 ActivePolicy = &WP; 8808 } 8809 8810 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 8811 (!CheckConstexprFunctionDecl(FD) || 8812 !CheckConstexprFunctionBody(FD, Body))) 8813 FD->setInvalidDecl(); 8814 8815 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 8816 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 8817 assert(MaybeODRUseExprs.empty() && 8818 "Leftover expressions for odr-use checking"); 8819 } 8820 8821 if (!IsInstantiation) 8822 PopDeclContext(); 8823 8824 PopFunctionScopeInfo(ActivePolicy, dcl); 8825 8826 // If any errors have occurred, clear out any temporaries that may have 8827 // been leftover. This ensures that these temporaries won't be picked up for 8828 // deletion in some later function. 8829 if (getDiagnostics().hasErrorOccurred()) { 8830 DiscardCleanupsInEvaluationContext(); 8831 } 8832 8833 return dcl; 8834} 8835 8836 8837/// When we finish delayed parsing of an attribute, we must attach it to the 8838/// relevant Decl. 8839void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 8840 ParsedAttributes &Attrs) { 8841 // Always attach attributes to the underlying decl. 8842 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8843 D = TD->getTemplatedDecl(); 8844 ProcessDeclAttributeList(S, D, Attrs.getList()); 8845 8846 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 8847 if (Method->isStatic()) 8848 checkThisInStaticMemberFunctionAttributes(Method); 8849} 8850 8851 8852/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 8853/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 8854NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 8855 IdentifierInfo &II, Scope *S) { 8856 // Before we produce a declaration for an implicitly defined 8857 // function, see whether there was a locally-scoped declaration of 8858 // this name as a function or variable. If so, use that 8859 // (non-visible) declaration, and complain about it. 8860 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 8861 = findLocallyScopedExternCDecl(&II); 8862 if (Pos != LocallyScopedExternCDecls.end()) { 8863 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 8864 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 8865 return Pos->second; 8866 } 8867 8868 // Extension in C99. Legal in C90, but warn about it. 8869 unsigned diag_id; 8870 if (II.getName().startswith("__builtin_")) 8871 diag_id = diag::warn_builtin_unknown; 8872 else if (getLangOpts().C99) 8873 diag_id = diag::ext_implicit_function_decl; 8874 else 8875 diag_id = diag::warn_implicit_function_decl; 8876 Diag(Loc, diag_id) << &II; 8877 8878 // Because typo correction is expensive, only do it if the implicit 8879 // function declaration is going to be treated as an error. 8880 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 8881 TypoCorrection Corrected; 8882 DeclFilterCCC<FunctionDecl> Validator; 8883 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 8884 LookupOrdinaryName, S, 0, Validator))) { 8885 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 8886 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 8887 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 8888 8889 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 8890 << FixItHint::CreateReplacement(Loc, CorrectedStr); 8891 8892 if (Func->getLocation().isValid() 8893 && !II.getName().startswith("__builtin_")) 8894 Diag(Func->getLocation(), diag::note_previous_decl) 8895 << CorrectedQuotedStr; 8896 } 8897 } 8898 8899 // Set a Declarator for the implicit definition: int foo(); 8900 const char *Dummy; 8901 AttributeFactory attrFactory; 8902 DeclSpec DS(attrFactory); 8903 unsigned DiagID; 8904 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 8905 (void)Error; // Silence warning. 8906 assert(!Error && "Error setting up implicit decl!"); 8907 SourceLocation NoLoc; 8908 Declarator D(DS, Declarator::BlockContext); 8909 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 8910 /*IsAmbiguous=*/false, 8911 /*RParenLoc=*/NoLoc, 8912 /*ArgInfo=*/0, 8913 /*NumArgs=*/0, 8914 /*EllipsisLoc=*/NoLoc, 8915 /*RParenLoc=*/NoLoc, 8916 /*TypeQuals=*/0, 8917 /*RefQualifierIsLvalueRef=*/true, 8918 /*RefQualifierLoc=*/NoLoc, 8919 /*ConstQualifierLoc=*/NoLoc, 8920 /*VolatileQualifierLoc=*/NoLoc, 8921 /*MutableLoc=*/NoLoc, 8922 EST_None, 8923 /*ESpecLoc=*/NoLoc, 8924 /*Exceptions=*/0, 8925 /*ExceptionRanges=*/0, 8926 /*NumExceptions=*/0, 8927 /*NoexceptExpr=*/0, 8928 Loc, Loc, D), 8929 DS.getAttributes(), 8930 SourceLocation()); 8931 D.SetIdentifier(&II, Loc); 8932 8933 // Insert this function into translation-unit scope. 8934 8935 DeclContext *PrevDC = CurContext; 8936 CurContext = Context.getTranslationUnitDecl(); 8937 8938 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 8939 FD->setImplicit(); 8940 8941 CurContext = PrevDC; 8942 8943 AddKnownFunctionAttributes(FD); 8944 8945 return FD; 8946} 8947 8948/// \brief Adds any function attributes that we know a priori based on 8949/// the declaration of this function. 8950/// 8951/// These attributes can apply both to implicitly-declared builtins 8952/// (like __builtin___printf_chk) or to library-declared functions 8953/// like NSLog or printf. 8954/// 8955/// We need to check for duplicate attributes both here and where user-written 8956/// attributes are applied to declarations. 8957void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 8958 if (FD->isInvalidDecl()) 8959 return; 8960 8961 // If this is a built-in function, map its builtin attributes to 8962 // actual attributes. 8963 if (unsigned BuiltinID = FD->getBuiltinID()) { 8964 // Handle printf-formatting attributes. 8965 unsigned FormatIdx; 8966 bool HasVAListArg; 8967 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 8968 if (!FD->getAttr<FormatAttr>()) { 8969 const char *fmt = "printf"; 8970 unsigned int NumParams = FD->getNumParams(); 8971 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 8972 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 8973 fmt = "NSString"; 8974 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8975 fmt, FormatIdx+1, 8976 HasVAListArg ? 0 : FormatIdx+2)); 8977 } 8978 } 8979 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 8980 HasVAListArg)) { 8981 if (!FD->getAttr<FormatAttr>()) 8982 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 8983 "scanf", FormatIdx+1, 8984 HasVAListArg ? 0 : FormatIdx+2)); 8985 } 8986 8987 // Mark const if we don't care about errno and that is the only 8988 // thing preventing the function from being const. This allows 8989 // IRgen to use LLVM intrinsics for such functions. 8990 if (!getLangOpts().MathErrno && 8991 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 8992 if (!FD->getAttr<ConstAttr>()) 8993 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 8994 } 8995 8996 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 8997 !FD->getAttr<ReturnsTwiceAttr>()) 8998 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 8999 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 9000 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 9001 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 9002 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 9003 } 9004 9005 IdentifierInfo *Name = FD->getIdentifier(); 9006 if (!Name) 9007 return; 9008 if ((!getLangOpts().CPlusPlus && 9009 FD->getDeclContext()->isTranslationUnit()) || 9010 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 9011 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 9012 LinkageSpecDecl::lang_c)) { 9013 // Okay: this could be a libc/libm/Objective-C function we know 9014 // about. 9015 } else 9016 return; 9017 9018 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 9019 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 9020 // target-specific builtins, perhaps? 9021 if (!FD->getAttr<FormatAttr>()) 9022 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 9023 "printf", 2, 9024 Name->isStr("vasprintf") ? 0 : 3)); 9025 } 9026 9027 if (Name->isStr("__CFStringMakeConstantString")) { 9028 // We already have a __builtin___CFStringMakeConstantString, 9029 // but builds that use -fno-constant-cfstrings don't go through that. 9030 if (!FD->getAttr<FormatArgAttr>()) 9031 FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1)); 9032 } 9033} 9034 9035TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 9036 TypeSourceInfo *TInfo) { 9037 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 9038 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 9039 9040 if (!TInfo) { 9041 assert(D.isInvalidType() && "no declarator info for valid type"); 9042 TInfo = Context.getTrivialTypeSourceInfo(T); 9043 } 9044 9045 // Scope manipulation handled by caller. 9046 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 9047 D.getLocStart(), 9048 D.getIdentifierLoc(), 9049 D.getIdentifier(), 9050 TInfo); 9051 9052 // Bail out immediately if we have an invalid declaration. 9053 if (D.isInvalidType()) { 9054 NewTD->setInvalidDecl(); 9055 return NewTD; 9056 } 9057 9058 if (D.getDeclSpec().isModulePrivateSpecified()) { 9059 if (CurContext->isFunctionOrMethod()) 9060 Diag(NewTD->getLocation(), diag::err_module_private_local) 9061 << 2 << NewTD->getDeclName() 9062 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9063 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9064 else 9065 NewTD->setModulePrivate(); 9066 } 9067 9068 // C++ [dcl.typedef]p8: 9069 // If the typedef declaration defines an unnamed class (or 9070 // enum), the first typedef-name declared by the declaration 9071 // to be that class type (or enum type) is used to denote the 9072 // class type (or enum type) for linkage purposes only. 9073 // We need to check whether the type was declared in the declaration. 9074 switch (D.getDeclSpec().getTypeSpecType()) { 9075 case TST_enum: 9076 case TST_struct: 9077 case TST_interface: 9078 case TST_union: 9079 case TST_class: { 9080 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 9081 9082 // Do nothing if the tag is not anonymous or already has an 9083 // associated typedef (from an earlier typedef in this decl group). 9084 if (tagFromDeclSpec->getIdentifier()) break; 9085 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 9086 9087 // A well-formed anonymous tag must always be a TUK_Definition. 9088 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 9089 9090 // The type must match the tag exactly; no qualifiers allowed. 9091 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 9092 break; 9093 9094 // Otherwise, set this is the anon-decl typedef for the tag. 9095 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 9096 break; 9097 } 9098 9099 default: 9100 break; 9101 } 9102 9103 return NewTD; 9104} 9105 9106 9107/// \brief Check that this is a valid underlying type for an enum declaration. 9108bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 9109 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 9110 QualType T = TI->getType(); 9111 9112 if (T->isDependentType()) 9113 return false; 9114 9115 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 9116 if (BT->isInteger()) 9117 return false; 9118 9119 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 9120 return true; 9121} 9122 9123/// Check whether this is a valid redeclaration of a previous enumeration. 9124/// \return true if the redeclaration was invalid. 9125bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 9126 QualType EnumUnderlyingTy, 9127 const EnumDecl *Prev) { 9128 bool IsFixed = !EnumUnderlyingTy.isNull(); 9129 9130 if (IsScoped != Prev->isScoped()) { 9131 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 9132 << Prev->isScoped(); 9133 Diag(Prev->getLocation(), diag::note_previous_use); 9134 return true; 9135 } 9136 9137 if (IsFixed && Prev->isFixed()) { 9138 if (!EnumUnderlyingTy->isDependentType() && 9139 !Prev->getIntegerType()->isDependentType() && 9140 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 9141 Prev->getIntegerType())) { 9142 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 9143 << EnumUnderlyingTy << Prev->getIntegerType(); 9144 Diag(Prev->getLocation(), diag::note_previous_use); 9145 return true; 9146 } 9147 } else if (IsFixed != Prev->isFixed()) { 9148 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 9149 << Prev->isFixed(); 9150 Diag(Prev->getLocation(), diag::note_previous_use); 9151 return true; 9152 } 9153 9154 return false; 9155} 9156 9157/// \brief Get diagnostic %select index for tag kind for 9158/// redeclaration diagnostic message. 9159/// WARNING: Indexes apply to particular diagnostics only! 9160/// 9161/// \returns diagnostic %select index. 9162static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 9163 switch (Tag) { 9164 case TTK_Struct: return 0; 9165 case TTK_Interface: return 1; 9166 case TTK_Class: return 2; 9167 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 9168 } 9169} 9170 9171/// \brief Determine if tag kind is a class-key compatible with 9172/// class for redeclaration (class, struct, or __interface). 9173/// 9174/// \returns true iff the tag kind is compatible. 9175static bool isClassCompatTagKind(TagTypeKind Tag) 9176{ 9177 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 9178} 9179 9180/// \brief Determine whether a tag with a given kind is acceptable 9181/// as a redeclaration of the given tag declaration. 9182/// 9183/// \returns true if the new tag kind is acceptable, false otherwise. 9184bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 9185 TagTypeKind NewTag, bool isDefinition, 9186 SourceLocation NewTagLoc, 9187 const IdentifierInfo &Name) { 9188 // C++ [dcl.type.elab]p3: 9189 // The class-key or enum keyword present in the 9190 // elaborated-type-specifier shall agree in kind with the 9191 // declaration to which the name in the elaborated-type-specifier 9192 // refers. This rule also applies to the form of 9193 // elaborated-type-specifier that declares a class-name or 9194 // friend class since it can be construed as referring to the 9195 // definition of the class. Thus, in any 9196 // elaborated-type-specifier, the enum keyword shall be used to 9197 // refer to an enumeration (7.2), the union class-key shall be 9198 // used to refer to a union (clause 9), and either the class or 9199 // struct class-key shall be used to refer to a class (clause 9) 9200 // declared using the class or struct class-key. 9201 TagTypeKind OldTag = Previous->getTagKind(); 9202 if (!isDefinition || !isClassCompatTagKind(NewTag)) 9203 if (OldTag == NewTag) 9204 return true; 9205 9206 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 9207 // Warn about the struct/class tag mismatch. 9208 bool isTemplate = false; 9209 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 9210 isTemplate = Record->getDescribedClassTemplate(); 9211 9212 if (!ActiveTemplateInstantiations.empty()) { 9213 // In a template instantiation, do not offer fix-its for tag mismatches 9214 // since they usually mess up the template instead of fixing the problem. 9215 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 9216 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9217 << getRedeclDiagFromTagKind(OldTag); 9218 return true; 9219 } 9220 9221 if (isDefinition) { 9222 // On definitions, check previous tags and issue a fix-it for each 9223 // one that doesn't match the current tag. 9224 if (Previous->getDefinition()) { 9225 // Don't suggest fix-its for redefinitions. 9226 return true; 9227 } 9228 9229 bool previousMismatch = false; 9230 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 9231 E(Previous->redecls_end()); I != E; ++I) { 9232 if (I->getTagKind() != NewTag) { 9233 if (!previousMismatch) { 9234 previousMismatch = true; 9235 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 9236 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9237 << getRedeclDiagFromTagKind(I->getTagKind()); 9238 } 9239 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 9240 << getRedeclDiagFromTagKind(NewTag) 9241 << FixItHint::CreateReplacement(I->getInnerLocStart(), 9242 TypeWithKeyword::getTagTypeKindName(NewTag)); 9243 } 9244 } 9245 return true; 9246 } 9247 9248 // Check for a previous definition. If current tag and definition 9249 // are same type, do nothing. If no definition, but disagree with 9250 // with previous tag type, give a warning, but no fix-it. 9251 const TagDecl *Redecl = Previous->getDefinition() ? 9252 Previous->getDefinition() : Previous; 9253 if (Redecl->getTagKind() == NewTag) { 9254 return true; 9255 } 9256 9257 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 9258 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 9259 << getRedeclDiagFromTagKind(OldTag); 9260 Diag(Redecl->getLocation(), diag::note_previous_use); 9261 9262 // If there is a previous defintion, suggest a fix-it. 9263 if (Previous->getDefinition()) { 9264 Diag(NewTagLoc, diag::note_struct_class_suggestion) 9265 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 9266 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 9267 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 9268 } 9269 9270 return true; 9271 } 9272 return false; 9273} 9274 9275/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 9276/// former case, Name will be non-null. In the later case, Name will be null. 9277/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 9278/// reference/declaration/definition of a tag. 9279Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 9280 SourceLocation KWLoc, CXXScopeSpec &SS, 9281 IdentifierInfo *Name, SourceLocation NameLoc, 9282 AttributeList *Attr, AccessSpecifier AS, 9283 SourceLocation ModulePrivateLoc, 9284 MultiTemplateParamsArg TemplateParameterLists, 9285 bool &OwnedDecl, bool &IsDependent, 9286 SourceLocation ScopedEnumKWLoc, 9287 bool ScopedEnumUsesClassTag, 9288 TypeResult UnderlyingType) { 9289 // If this is not a definition, it must have a name. 9290 IdentifierInfo *OrigName = Name; 9291 assert((Name != 0 || TUK == TUK_Definition) && 9292 "Nameless record must be a definition!"); 9293 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 9294 9295 OwnedDecl = false; 9296 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9297 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 9298 9299 // FIXME: Check explicit specializations more carefully. 9300 bool isExplicitSpecialization = false; 9301 bool Invalid = false; 9302 9303 // We only need to do this matching if we have template parameters 9304 // or a scope specifier, which also conveniently avoids this work 9305 // for non-C++ cases. 9306 if (TemplateParameterLists.size() > 0 || 9307 (SS.isNotEmpty() && TUK != TUK_Reference)) { 9308 if (TemplateParameterList *TemplateParams 9309 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 9310 TemplateParameterLists.data(), 9311 TemplateParameterLists.size(), 9312 TUK == TUK_Friend, 9313 isExplicitSpecialization, 9314 Invalid)) { 9315 if (TemplateParams->size() > 0) { 9316 // This is a declaration or definition of a class template (which may 9317 // be a member of another template). 9318 9319 if (Invalid) 9320 return 0; 9321 9322 OwnedDecl = false; 9323 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 9324 SS, Name, NameLoc, Attr, 9325 TemplateParams, AS, 9326 ModulePrivateLoc, 9327 TemplateParameterLists.size()-1, 9328 TemplateParameterLists.data()); 9329 return Result.get(); 9330 } else { 9331 // The "template<>" header is extraneous. 9332 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9333 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9334 isExplicitSpecialization = true; 9335 } 9336 } 9337 } 9338 9339 // Figure out the underlying type if this a enum declaration. We need to do 9340 // this early, because it's needed to detect if this is an incompatible 9341 // redeclaration. 9342 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 9343 9344 if (Kind == TTK_Enum) { 9345 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 9346 // No underlying type explicitly specified, or we failed to parse the 9347 // type, default to int. 9348 EnumUnderlying = Context.IntTy.getTypePtr(); 9349 else if (UnderlyingType.get()) { 9350 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 9351 // integral type; any cv-qualification is ignored. 9352 TypeSourceInfo *TI = 0; 9353 GetTypeFromParser(UnderlyingType.get(), &TI); 9354 EnumUnderlying = TI; 9355 9356 if (CheckEnumUnderlyingType(TI)) 9357 // Recover by falling back to int. 9358 EnumUnderlying = Context.IntTy.getTypePtr(); 9359 9360 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 9361 UPPC_FixedUnderlyingType)) 9362 EnumUnderlying = Context.IntTy.getTypePtr(); 9363 9364 } else if (getLangOpts().MicrosoftMode) 9365 // Microsoft enums are always of int type. 9366 EnumUnderlying = Context.IntTy.getTypePtr(); 9367 } 9368 9369 DeclContext *SearchDC = CurContext; 9370 DeclContext *DC = CurContext; 9371 bool isStdBadAlloc = false; 9372 9373 RedeclarationKind Redecl = ForRedeclaration; 9374 if (TUK == TUK_Friend || TUK == TUK_Reference) 9375 Redecl = NotForRedeclaration; 9376 9377 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 9378 9379 if (Name && SS.isNotEmpty()) { 9380 // We have a nested-name tag ('struct foo::bar'). 9381 9382 // Check for invalid 'foo::'. 9383 if (SS.isInvalid()) { 9384 Name = 0; 9385 goto CreateNewDecl; 9386 } 9387 9388 // If this is a friend or a reference to a class in a dependent 9389 // context, don't try to make a decl for it. 9390 if (TUK == TUK_Friend || TUK == TUK_Reference) { 9391 DC = computeDeclContext(SS, false); 9392 if (!DC) { 9393 IsDependent = true; 9394 return 0; 9395 } 9396 } else { 9397 DC = computeDeclContext(SS, true); 9398 if (!DC) { 9399 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 9400 << SS.getRange(); 9401 return 0; 9402 } 9403 } 9404 9405 if (RequireCompleteDeclContext(SS, DC)) 9406 return 0; 9407 9408 SearchDC = DC; 9409 // Look-up name inside 'foo::'. 9410 LookupQualifiedName(Previous, DC); 9411 9412 if (Previous.isAmbiguous()) 9413 return 0; 9414 9415 if (Previous.empty()) { 9416 // Name lookup did not find anything. However, if the 9417 // nested-name-specifier refers to the current instantiation, 9418 // and that current instantiation has any dependent base 9419 // classes, we might find something at instantiation time: treat 9420 // this as a dependent elaborated-type-specifier. 9421 // But this only makes any sense for reference-like lookups. 9422 if (Previous.wasNotFoundInCurrentInstantiation() && 9423 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9424 IsDependent = true; 9425 return 0; 9426 } 9427 9428 // A tag 'foo::bar' must already exist. 9429 Diag(NameLoc, diag::err_not_tag_in_scope) 9430 << Kind << Name << DC << SS.getRange(); 9431 Name = 0; 9432 Invalid = true; 9433 goto CreateNewDecl; 9434 } 9435 } else if (Name) { 9436 // If this is a named struct, check to see if there was a previous forward 9437 // declaration or definition. 9438 // FIXME: We're looking into outer scopes here, even when we 9439 // shouldn't be. Doing so can result in ambiguities that we 9440 // shouldn't be diagnosing. 9441 LookupName(Previous, S); 9442 9443 if (Previous.isAmbiguous() && 9444 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 9445 LookupResult::Filter F = Previous.makeFilter(); 9446 while (F.hasNext()) { 9447 NamedDecl *ND = F.next(); 9448 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 9449 F.erase(); 9450 } 9451 F.done(); 9452 } 9453 9454 // Note: there used to be some attempt at recovery here. 9455 if (Previous.isAmbiguous()) 9456 return 0; 9457 9458 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 9459 // FIXME: This makes sure that we ignore the contexts associated 9460 // with C structs, unions, and enums when looking for a matching 9461 // tag declaration or definition. See the similar lookup tweak 9462 // in Sema::LookupName; is there a better way to deal with this? 9463 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 9464 SearchDC = SearchDC->getParent(); 9465 } 9466 } else if (S->isFunctionPrototypeScope()) { 9467 // If this is an enum declaration in function prototype scope, set its 9468 // initial context to the translation unit. 9469 // FIXME: [citation needed] 9470 SearchDC = Context.getTranslationUnitDecl(); 9471 } 9472 9473 if (Previous.isSingleResult() && 9474 Previous.getFoundDecl()->isTemplateParameter()) { 9475 // Maybe we will complain about the shadowed template parameter. 9476 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 9477 // Just pretend that we didn't see the previous declaration. 9478 Previous.clear(); 9479 } 9480 9481 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 9482 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 9483 // This is a declaration of or a reference to "std::bad_alloc". 9484 isStdBadAlloc = true; 9485 9486 if (Previous.empty() && StdBadAlloc) { 9487 // std::bad_alloc has been implicitly declared (but made invisible to 9488 // name lookup). Fill in this implicit declaration as the previous 9489 // declaration, so that the declarations get chained appropriately. 9490 Previous.addDecl(getStdBadAlloc()); 9491 } 9492 } 9493 9494 // If we didn't find a previous declaration, and this is a reference 9495 // (or friend reference), move to the correct scope. In C++, we 9496 // also need to do a redeclaration lookup there, just in case 9497 // there's a shadow friend decl. 9498 if (Name && Previous.empty() && 9499 (TUK == TUK_Reference || TUK == TUK_Friend)) { 9500 if (Invalid) goto CreateNewDecl; 9501 assert(SS.isEmpty()); 9502 9503 if (TUK == TUK_Reference) { 9504 // C++ [basic.scope.pdecl]p5: 9505 // -- for an elaborated-type-specifier of the form 9506 // 9507 // class-key identifier 9508 // 9509 // if the elaborated-type-specifier is used in the 9510 // decl-specifier-seq or parameter-declaration-clause of a 9511 // function defined in namespace scope, the identifier is 9512 // declared as a class-name in the namespace that contains 9513 // the declaration; otherwise, except as a friend 9514 // declaration, the identifier is declared in the smallest 9515 // non-class, non-function-prototype scope that contains the 9516 // declaration. 9517 // 9518 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 9519 // C structs and unions. 9520 // 9521 // It is an error in C++ to declare (rather than define) an enum 9522 // type, including via an elaborated type specifier. We'll 9523 // diagnose that later; for now, declare the enum in the same 9524 // scope as we would have picked for any other tag type. 9525 // 9526 // GNU C also supports this behavior as part of its incomplete 9527 // enum types extension, while GNU C++ does not. 9528 // 9529 // Find the context where we'll be declaring the tag. 9530 // FIXME: We would like to maintain the current DeclContext as the 9531 // lexical context, 9532 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 9533 SearchDC = SearchDC->getParent(); 9534 9535 // Find the scope where we'll be declaring the tag. 9536 while (S->isClassScope() || 9537 (getLangOpts().CPlusPlus && 9538 S->isFunctionPrototypeScope()) || 9539 ((S->getFlags() & Scope::DeclScope) == 0) || 9540 (S->getEntity() && 9541 ((DeclContext *)S->getEntity())->isTransparentContext())) 9542 S = S->getParent(); 9543 } else { 9544 assert(TUK == TUK_Friend); 9545 // C++ [namespace.memdef]p3: 9546 // If a friend declaration in a non-local class first declares a 9547 // class or function, the friend class or function is a member of 9548 // the innermost enclosing namespace. 9549 SearchDC = SearchDC->getEnclosingNamespaceContext(); 9550 } 9551 9552 // In C++, we need to do a redeclaration lookup to properly 9553 // diagnose some problems. 9554 if (getLangOpts().CPlusPlus) { 9555 Previous.setRedeclarationKind(ForRedeclaration); 9556 LookupQualifiedName(Previous, SearchDC); 9557 } 9558 } 9559 9560 if (!Previous.empty()) { 9561 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 9562 9563 // It's okay to have a tag decl in the same scope as a typedef 9564 // which hides a tag decl in the same scope. Finding this 9565 // insanity with a redeclaration lookup can only actually happen 9566 // in C++. 9567 // 9568 // This is also okay for elaborated-type-specifiers, which is 9569 // technically forbidden by the current standard but which is 9570 // okay according to the likely resolution of an open issue; 9571 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 9572 if (getLangOpts().CPlusPlus) { 9573 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9574 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 9575 TagDecl *Tag = TT->getDecl(); 9576 if (Tag->getDeclName() == Name && 9577 Tag->getDeclContext()->getRedeclContext() 9578 ->Equals(TD->getDeclContext()->getRedeclContext())) { 9579 PrevDecl = Tag; 9580 Previous.clear(); 9581 Previous.addDecl(Tag); 9582 Previous.resolveKind(); 9583 } 9584 } 9585 } 9586 } 9587 9588 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 9589 // If this is a use of a previous tag, or if the tag is already declared 9590 // in the same scope (so that the definition/declaration completes or 9591 // rementions the tag), reuse the decl. 9592 if (TUK == TUK_Reference || TUK == TUK_Friend || 9593 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 9594 // Make sure that this wasn't declared as an enum and now used as a 9595 // struct or something similar. 9596 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 9597 TUK == TUK_Definition, KWLoc, 9598 *Name)) { 9599 bool SafeToContinue 9600 = (PrevTagDecl->getTagKind() != TTK_Enum && 9601 Kind != TTK_Enum); 9602 if (SafeToContinue) 9603 Diag(KWLoc, diag::err_use_with_wrong_tag) 9604 << Name 9605 << FixItHint::CreateReplacement(SourceRange(KWLoc), 9606 PrevTagDecl->getKindName()); 9607 else 9608 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 9609 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 9610 9611 if (SafeToContinue) 9612 Kind = PrevTagDecl->getTagKind(); 9613 else { 9614 // Recover by making this an anonymous redefinition. 9615 Name = 0; 9616 Previous.clear(); 9617 Invalid = true; 9618 } 9619 } 9620 9621 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 9622 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 9623 9624 // If this is an elaborated-type-specifier for a scoped enumeration, 9625 // the 'class' keyword is not necessary and not permitted. 9626 if (TUK == TUK_Reference || TUK == TUK_Friend) { 9627 if (ScopedEnum) 9628 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 9629 << PrevEnum->isScoped() 9630 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 9631 return PrevTagDecl; 9632 } 9633 9634 QualType EnumUnderlyingTy; 9635 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9636 EnumUnderlyingTy = TI->getType(); 9637 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 9638 EnumUnderlyingTy = QualType(T, 0); 9639 9640 // All conflicts with previous declarations are recovered by 9641 // returning the previous declaration, unless this is a definition, 9642 // in which case we want the caller to bail out. 9643 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 9644 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 9645 return TUK == TUK_Declaration ? PrevTagDecl : 0; 9646 } 9647 9648 if (!Invalid) { 9649 // If this is a use, just return the declaration we found. 9650 9651 // FIXME: In the future, return a variant or some other clue 9652 // for the consumer of this Decl to know it doesn't own it. 9653 // For our current ASTs this shouldn't be a problem, but will 9654 // need to be changed with DeclGroups. 9655 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 9656 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 9657 return PrevTagDecl; 9658 9659 // Diagnose attempts to redefine a tag. 9660 if (TUK == TUK_Definition) { 9661 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 9662 // If we're defining a specialization and the previous definition 9663 // is from an implicit instantiation, don't emit an error 9664 // here; we'll catch this in the general case below. 9665 bool IsExplicitSpecializationAfterInstantiation = false; 9666 if (isExplicitSpecialization) { 9667 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 9668 IsExplicitSpecializationAfterInstantiation = 9669 RD->getTemplateSpecializationKind() != 9670 TSK_ExplicitSpecialization; 9671 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 9672 IsExplicitSpecializationAfterInstantiation = 9673 ED->getTemplateSpecializationKind() != 9674 TSK_ExplicitSpecialization; 9675 } 9676 9677 if (!IsExplicitSpecializationAfterInstantiation) { 9678 // A redeclaration in function prototype scope in C isn't 9679 // visible elsewhere, so merely issue a warning. 9680 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 9681 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 9682 else 9683 Diag(NameLoc, diag::err_redefinition) << Name; 9684 Diag(Def->getLocation(), diag::note_previous_definition); 9685 // If this is a redefinition, recover by making this 9686 // struct be anonymous, which will make any later 9687 // references get the previous definition. 9688 Name = 0; 9689 Previous.clear(); 9690 Invalid = true; 9691 } 9692 } else { 9693 // If the type is currently being defined, complain 9694 // about a nested redefinition. 9695 const TagType *Tag 9696 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 9697 if (Tag->isBeingDefined()) { 9698 Diag(NameLoc, diag::err_nested_redefinition) << Name; 9699 Diag(PrevTagDecl->getLocation(), 9700 diag::note_previous_definition); 9701 Name = 0; 9702 Previous.clear(); 9703 Invalid = true; 9704 } 9705 } 9706 9707 // Okay, this is definition of a previously declared or referenced 9708 // tag PrevDecl. We're going to create a new Decl for it. 9709 } 9710 } 9711 // If we get here we have (another) forward declaration or we 9712 // have a definition. Just create a new decl. 9713 9714 } else { 9715 // If we get here, this is a definition of a new tag type in a nested 9716 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 9717 // new decl/type. We set PrevDecl to NULL so that the entities 9718 // have distinct types. 9719 Previous.clear(); 9720 } 9721 // If we get here, we're going to create a new Decl. If PrevDecl 9722 // is non-NULL, it's a definition of the tag declared by 9723 // PrevDecl. If it's NULL, we have a new definition. 9724 9725 9726 // Otherwise, PrevDecl is not a tag, but was found with tag 9727 // lookup. This is only actually possible in C++, where a few 9728 // things like templates still live in the tag namespace. 9729 } else { 9730 // Use a better diagnostic if an elaborated-type-specifier 9731 // found the wrong kind of type on the first 9732 // (non-redeclaration) lookup. 9733 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 9734 !Previous.isForRedeclaration()) { 9735 unsigned Kind = 0; 9736 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9737 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9738 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9739 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 9740 Diag(PrevDecl->getLocation(), diag::note_declared_at); 9741 Invalid = true; 9742 9743 // Otherwise, only diagnose if the declaration is in scope. 9744 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 9745 isExplicitSpecialization)) { 9746 // do nothing 9747 9748 // Diagnose implicit declarations introduced by elaborated types. 9749 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 9750 unsigned Kind = 0; 9751 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 9752 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 9753 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 9754 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 9755 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9756 Invalid = true; 9757 9758 // Otherwise it's a declaration. Call out a particularly common 9759 // case here. 9760 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 9761 unsigned Kind = 0; 9762 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 9763 Diag(NameLoc, diag::err_tag_definition_of_typedef) 9764 << Name << Kind << TND->getUnderlyingType(); 9765 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 9766 Invalid = true; 9767 9768 // Otherwise, diagnose. 9769 } else { 9770 // The tag name clashes with something else in the target scope, 9771 // issue an error and recover by making this tag be anonymous. 9772 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 9773 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9774 Name = 0; 9775 Invalid = true; 9776 } 9777 9778 // The existing declaration isn't relevant to us; we're in a 9779 // new scope, so clear out the previous declaration. 9780 Previous.clear(); 9781 } 9782 } 9783 9784CreateNewDecl: 9785 9786 TagDecl *PrevDecl = 0; 9787 if (Previous.isSingleResult()) 9788 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 9789 9790 // If there is an identifier, use the location of the identifier as the 9791 // location of the decl, otherwise use the location of the struct/union 9792 // keyword. 9793 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 9794 9795 // Otherwise, create a new declaration. If there is a previous 9796 // declaration of the same entity, the two will be linked via 9797 // PrevDecl. 9798 TagDecl *New; 9799 9800 bool IsForwardReference = false; 9801 if (Kind == TTK_Enum) { 9802 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9803 // enum X { A, B, C } D; D should chain to X. 9804 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 9805 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 9806 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 9807 // If this is an undefined enum, warn. 9808 if (TUK != TUK_Definition && !Invalid) { 9809 TagDecl *Def; 9810 if (getLangOpts().CPlusPlus11 && cast<EnumDecl>(New)->isFixed()) { 9811 // C++0x: 7.2p2: opaque-enum-declaration. 9812 // Conflicts are diagnosed above. Do nothing. 9813 } 9814 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 9815 Diag(Loc, diag::ext_forward_ref_enum_def) 9816 << New; 9817 Diag(Def->getLocation(), diag::note_previous_definition); 9818 } else { 9819 unsigned DiagID = diag::ext_forward_ref_enum; 9820 if (getLangOpts().MicrosoftMode) 9821 DiagID = diag::ext_ms_forward_ref_enum; 9822 else if (getLangOpts().CPlusPlus) 9823 DiagID = diag::err_forward_ref_enum; 9824 Diag(Loc, DiagID); 9825 9826 // If this is a forward-declared reference to an enumeration, make a 9827 // note of it; we won't actually be introducing the declaration into 9828 // the declaration context. 9829 if (TUK == TUK_Reference) 9830 IsForwardReference = true; 9831 } 9832 } 9833 9834 if (EnumUnderlying) { 9835 EnumDecl *ED = cast<EnumDecl>(New); 9836 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 9837 ED->setIntegerTypeSourceInfo(TI); 9838 else 9839 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 9840 ED->setPromotionType(ED->getIntegerType()); 9841 } 9842 9843 } else { 9844 // struct/union/class 9845 9846 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 9847 // struct X { int A; } D; D should chain to X. 9848 if (getLangOpts().CPlusPlus) { 9849 // FIXME: Look for a way to use RecordDecl for simple structs. 9850 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9851 cast_or_null<CXXRecordDecl>(PrevDecl)); 9852 9853 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 9854 StdBadAlloc = cast<CXXRecordDecl>(New); 9855 } else 9856 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 9857 cast_or_null<RecordDecl>(PrevDecl)); 9858 } 9859 9860 // Maybe add qualifier info. 9861 if (SS.isNotEmpty()) { 9862 if (SS.isSet()) { 9863 // If this is either a declaration or a definition, check the 9864 // nested-name-specifier against the current context. We don't do this 9865 // for explicit specializations, because they have similar checking 9866 // (with more specific diagnostics) in the call to 9867 // CheckMemberSpecialization, below. 9868 if (!isExplicitSpecialization && 9869 (TUK == TUK_Definition || TUK == TUK_Declaration) && 9870 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 9871 Invalid = true; 9872 9873 New->setQualifierInfo(SS.getWithLocInContext(Context)); 9874 if (TemplateParameterLists.size() > 0) { 9875 New->setTemplateParameterListsInfo(Context, 9876 TemplateParameterLists.size(), 9877 TemplateParameterLists.data()); 9878 } 9879 } 9880 else 9881 Invalid = true; 9882 } 9883 9884 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 9885 // Add alignment attributes if necessary; these attributes are checked when 9886 // the ASTContext lays out the structure. 9887 // 9888 // It is important for implementing the correct semantics that this 9889 // happen here (in act on tag decl). The #pragma pack stack is 9890 // maintained as a result of parser callbacks which can occur at 9891 // many points during the parsing of a struct declaration (because 9892 // the #pragma tokens are effectively skipped over during the 9893 // parsing of the struct). 9894 if (TUK == TUK_Definition) { 9895 AddAlignmentAttributesForRecord(RD); 9896 AddMsStructLayoutForRecord(RD); 9897 } 9898 } 9899 9900 if (ModulePrivateLoc.isValid()) { 9901 if (isExplicitSpecialization) 9902 Diag(New->getLocation(), diag::err_module_private_specialization) 9903 << 2 9904 << FixItHint::CreateRemoval(ModulePrivateLoc); 9905 // __module_private__ does not apply to local classes. However, we only 9906 // diagnose this as an error when the declaration specifiers are 9907 // freestanding. Here, we just ignore the __module_private__. 9908 else if (!SearchDC->isFunctionOrMethod()) 9909 New->setModulePrivate(); 9910 } 9911 9912 // If this is a specialization of a member class (of a class template), 9913 // check the specialization. 9914 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 9915 Invalid = true; 9916 9917 if (Invalid) 9918 New->setInvalidDecl(); 9919 9920 if (Attr) 9921 ProcessDeclAttributeList(S, New, Attr); 9922 9923 // If we're declaring or defining a tag in function prototype scope 9924 // in C, note that this type can only be used within the function. 9925 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 9926 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 9927 9928 // Set the lexical context. If the tag has a C++ scope specifier, the 9929 // lexical context will be different from the semantic context. 9930 New->setLexicalDeclContext(CurContext); 9931 9932 // Mark this as a friend decl if applicable. 9933 // In Microsoft mode, a friend declaration also acts as a forward 9934 // declaration so we always pass true to setObjectOfFriendDecl to make 9935 // the tag name visible. 9936 if (TUK == TUK_Friend) 9937 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 9938 getLangOpts().MicrosoftExt); 9939 9940 // Set the access specifier. 9941 if (!Invalid && SearchDC->isRecord()) 9942 SetMemberAccessSpecifier(New, PrevDecl, AS); 9943 9944 if (TUK == TUK_Definition) 9945 New->startDefinition(); 9946 9947 // If this has an identifier, add it to the scope stack. 9948 if (TUK == TUK_Friend) { 9949 // We might be replacing an existing declaration in the lookup tables; 9950 // if so, borrow its access specifier. 9951 if (PrevDecl) 9952 New->setAccess(PrevDecl->getAccess()); 9953 9954 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 9955 DC->makeDeclVisibleInContext(New); 9956 if (Name) // can be null along some error paths 9957 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 9958 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 9959 } else if (Name) { 9960 S = getNonFieldDeclScope(S); 9961 PushOnScopeChains(New, S, !IsForwardReference); 9962 if (IsForwardReference) 9963 SearchDC->makeDeclVisibleInContext(New); 9964 9965 } else { 9966 CurContext->addDecl(New); 9967 } 9968 9969 // If this is the C FILE type, notify the AST context. 9970 if (IdentifierInfo *II = New->getIdentifier()) 9971 if (!New->isInvalidDecl() && 9972 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 9973 II->isStr("FILE")) 9974 Context.setFILEDecl(New); 9975 9976 // If we were in function prototype scope (and not in C++ mode), add this 9977 // tag to the list of decls to inject into the function definition scope. 9978 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 9979 InFunctionDeclarator && Name) 9980 DeclsInPrototypeScope.push_back(New); 9981 9982 if (PrevDecl) 9983 mergeDeclAttributes(New, PrevDecl); 9984 9985 // If there's a #pragma GCC visibility in scope, set the visibility of this 9986 // record. 9987 AddPushedVisibilityAttribute(New); 9988 9989 OwnedDecl = true; 9990 // In C++, don't return an invalid declaration. We can't recover well from 9991 // the cases where we make the type anonymous. 9992 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 9993} 9994 9995void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 9996 AdjustDeclIfTemplate(TagD); 9997 TagDecl *Tag = cast<TagDecl>(TagD); 9998 9999 // Enter the tag context. 10000 PushDeclContext(S, Tag); 10001 10002 ActOnDocumentableDecl(TagD); 10003 10004 // If there's a #pragma GCC visibility in scope, set the visibility of this 10005 // record. 10006 AddPushedVisibilityAttribute(Tag); 10007} 10008 10009Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 10010 assert(isa<ObjCContainerDecl>(IDecl) && 10011 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 10012 DeclContext *OCD = cast<DeclContext>(IDecl); 10013 assert(getContainingDC(OCD) == CurContext && 10014 "The next DeclContext should be lexically contained in the current one."); 10015 CurContext = OCD; 10016 return IDecl; 10017} 10018 10019void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 10020 SourceLocation FinalLoc, 10021 SourceLocation LBraceLoc) { 10022 AdjustDeclIfTemplate(TagD); 10023 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 10024 10025 FieldCollector->StartClass(); 10026 10027 if (!Record->getIdentifier()) 10028 return; 10029 10030 if (FinalLoc.isValid()) 10031 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 10032 10033 // C++ [class]p2: 10034 // [...] The class-name is also inserted into the scope of the 10035 // class itself; this is known as the injected-class-name. For 10036 // purposes of access checking, the injected-class-name is treated 10037 // as if it were a public member name. 10038 CXXRecordDecl *InjectedClassName 10039 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 10040 Record->getLocStart(), Record->getLocation(), 10041 Record->getIdentifier(), 10042 /*PrevDecl=*/0, 10043 /*DelayTypeCreation=*/true); 10044 Context.getTypeDeclType(InjectedClassName, Record); 10045 InjectedClassName->setImplicit(); 10046 InjectedClassName->setAccess(AS_public); 10047 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 10048 InjectedClassName->setDescribedClassTemplate(Template); 10049 PushOnScopeChains(InjectedClassName, S); 10050 assert(InjectedClassName->isInjectedClassName() && 10051 "Broken injected-class-name"); 10052} 10053 10054void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 10055 SourceLocation RBraceLoc) { 10056 AdjustDeclIfTemplate(TagD); 10057 TagDecl *Tag = cast<TagDecl>(TagD); 10058 Tag->setRBraceLoc(RBraceLoc); 10059 10060 // Make sure we "complete" the definition even it is invalid. 10061 if (Tag->isBeingDefined()) { 10062 assert(Tag->isInvalidDecl() && "We should already have completed it"); 10063 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 10064 RD->completeDefinition(); 10065 } 10066 10067 if (isa<CXXRecordDecl>(Tag)) 10068 FieldCollector->FinishClass(); 10069 10070 // Exit this scope of this tag's definition. 10071 PopDeclContext(); 10072 10073 if (getCurLexicalContext()->isObjCContainer() && 10074 Tag->getDeclContext()->isFileContext()) 10075 Tag->setTopLevelDeclInObjCContainer(); 10076 10077 // Notify the consumer that we've defined a tag. 10078 Consumer.HandleTagDeclDefinition(Tag); 10079} 10080 10081void Sema::ActOnObjCContainerFinishDefinition() { 10082 // Exit this scope of this interface definition. 10083 PopDeclContext(); 10084} 10085 10086void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 10087 assert(DC == CurContext && "Mismatch of container contexts"); 10088 OriginalLexicalContext = DC; 10089 ActOnObjCContainerFinishDefinition(); 10090} 10091 10092void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 10093 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 10094 OriginalLexicalContext = 0; 10095} 10096 10097void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 10098 AdjustDeclIfTemplate(TagD); 10099 TagDecl *Tag = cast<TagDecl>(TagD); 10100 Tag->setInvalidDecl(); 10101 10102 // Make sure we "complete" the definition even it is invalid. 10103 if (Tag->isBeingDefined()) { 10104 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 10105 RD->completeDefinition(); 10106 } 10107 10108 // We're undoing ActOnTagStartDefinition here, not 10109 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 10110 // the FieldCollector. 10111 10112 PopDeclContext(); 10113} 10114 10115// Note that FieldName may be null for anonymous bitfields. 10116ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 10117 IdentifierInfo *FieldName, 10118 QualType FieldTy, Expr *BitWidth, 10119 bool *ZeroWidth) { 10120 // Default to true; that shouldn't confuse checks for emptiness 10121 if (ZeroWidth) 10122 *ZeroWidth = true; 10123 10124 // C99 6.7.2.1p4 - verify the field type. 10125 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 10126 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 10127 // Handle incomplete types with specific error. 10128 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 10129 return ExprError(); 10130 if (FieldName) 10131 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 10132 << FieldName << FieldTy << BitWidth->getSourceRange(); 10133 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 10134 << FieldTy << BitWidth->getSourceRange(); 10135 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 10136 UPPC_BitFieldWidth)) 10137 return ExprError(); 10138 10139 // If the bit-width is type- or value-dependent, don't try to check 10140 // it now. 10141 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 10142 return Owned(BitWidth); 10143 10144 llvm::APSInt Value; 10145 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 10146 if (ICE.isInvalid()) 10147 return ICE; 10148 BitWidth = ICE.take(); 10149 10150 if (Value != 0 && ZeroWidth) 10151 *ZeroWidth = false; 10152 10153 // Zero-width bitfield is ok for anonymous field. 10154 if (Value == 0 && FieldName) 10155 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 10156 10157 if (Value.isSigned() && Value.isNegative()) { 10158 if (FieldName) 10159 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 10160 << FieldName << Value.toString(10); 10161 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 10162 << Value.toString(10); 10163 } 10164 10165 if (!FieldTy->isDependentType()) { 10166 uint64_t TypeSize = Context.getTypeSize(FieldTy); 10167 if (Value.getZExtValue() > TypeSize) { 10168 if (!getLangOpts().CPlusPlus) { 10169 if (FieldName) 10170 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 10171 << FieldName << (unsigned)Value.getZExtValue() 10172 << (unsigned)TypeSize; 10173 10174 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 10175 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 10176 } 10177 10178 if (FieldName) 10179 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 10180 << FieldName << (unsigned)Value.getZExtValue() 10181 << (unsigned)TypeSize; 10182 else 10183 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 10184 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 10185 } 10186 } 10187 10188 return Owned(BitWidth); 10189} 10190 10191/// ActOnField - Each field of a C struct/union is passed into this in order 10192/// to create a FieldDecl object for it. 10193Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 10194 Declarator &D, Expr *BitfieldWidth) { 10195 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 10196 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 10197 /*InitStyle=*/ICIS_NoInit, AS_public); 10198 return Res; 10199} 10200 10201/// HandleField - Analyze a field of a C struct or a C++ data member. 10202/// 10203FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 10204 SourceLocation DeclStart, 10205 Declarator &D, Expr *BitWidth, 10206 InClassInitStyle InitStyle, 10207 AccessSpecifier AS) { 10208 IdentifierInfo *II = D.getIdentifier(); 10209 SourceLocation Loc = DeclStart; 10210 if (II) Loc = D.getIdentifierLoc(); 10211 10212 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10213 QualType T = TInfo->getType(); 10214 if (getLangOpts().CPlusPlus) { 10215 CheckExtraCXXDefaultArguments(D); 10216 10217 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10218 UPPC_DataMemberType)) { 10219 D.setInvalidType(); 10220 T = Context.IntTy; 10221 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 10222 } 10223 } 10224 10225 // TR 18037 does not allow fields to be declared with address spaces. 10226 if (T.getQualifiers().hasAddressSpace()) { 10227 Diag(Loc, diag::err_field_with_address_space); 10228 D.setInvalidType(); 10229 } 10230 10231 // OpenCL 1.2 spec, s6.9 r: 10232 // The event type cannot be used to declare a structure or union field. 10233 if (LangOpts.OpenCL && T->isEventT()) { 10234 Diag(Loc, diag::err_event_t_struct_field); 10235 D.setInvalidType(); 10236 } 10237 10238 DiagnoseFunctionSpecifiers(D); 10239 10240 if (D.getDeclSpec().isThreadSpecified()) 10241 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 10242 10243 // Check to see if this name was declared as a member previously 10244 NamedDecl *PrevDecl = 0; 10245 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 10246 LookupName(Previous, S); 10247 switch (Previous.getResultKind()) { 10248 case LookupResult::Found: 10249 case LookupResult::FoundUnresolvedValue: 10250 PrevDecl = Previous.getAsSingle<NamedDecl>(); 10251 break; 10252 10253 case LookupResult::FoundOverloaded: 10254 PrevDecl = Previous.getRepresentativeDecl(); 10255 break; 10256 10257 case LookupResult::NotFound: 10258 case LookupResult::NotFoundInCurrentInstantiation: 10259 case LookupResult::Ambiguous: 10260 break; 10261 } 10262 Previous.suppressDiagnostics(); 10263 10264 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10265 // Maybe we will complain about the shadowed template parameter. 10266 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10267 // Just pretend that we didn't see the previous declaration. 10268 PrevDecl = 0; 10269 } 10270 10271 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 10272 PrevDecl = 0; 10273 10274 bool Mutable 10275 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 10276 SourceLocation TSSL = D.getLocStart(); 10277 FieldDecl *NewFD 10278 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 10279 TSSL, AS, PrevDecl, &D); 10280 10281 if (NewFD->isInvalidDecl()) 10282 Record->setInvalidDecl(); 10283 10284 if (D.getDeclSpec().isModulePrivateSpecified()) 10285 NewFD->setModulePrivate(); 10286 10287 if (NewFD->isInvalidDecl() && PrevDecl) { 10288 // Don't introduce NewFD into scope; there's already something 10289 // with the same name in the same scope. 10290 } else if (II) { 10291 PushOnScopeChains(NewFD, S); 10292 } else 10293 Record->addDecl(NewFD); 10294 10295 return NewFD; 10296} 10297 10298/// \brief Build a new FieldDecl and check its well-formedness. 10299/// 10300/// This routine builds a new FieldDecl given the fields name, type, 10301/// record, etc. \p PrevDecl should refer to any previous declaration 10302/// with the same name and in the same scope as the field to be 10303/// created. 10304/// 10305/// \returns a new FieldDecl. 10306/// 10307/// \todo The Declarator argument is a hack. It will be removed once 10308FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 10309 TypeSourceInfo *TInfo, 10310 RecordDecl *Record, SourceLocation Loc, 10311 bool Mutable, Expr *BitWidth, 10312 InClassInitStyle InitStyle, 10313 SourceLocation TSSL, 10314 AccessSpecifier AS, NamedDecl *PrevDecl, 10315 Declarator *D) { 10316 IdentifierInfo *II = Name.getAsIdentifierInfo(); 10317 bool InvalidDecl = false; 10318 if (D) InvalidDecl = D->isInvalidType(); 10319 10320 // If we receive a broken type, recover by assuming 'int' and 10321 // marking this declaration as invalid. 10322 if (T.isNull()) { 10323 InvalidDecl = true; 10324 T = Context.IntTy; 10325 } 10326 10327 QualType EltTy = Context.getBaseElementType(T); 10328 if (!EltTy->isDependentType()) { 10329 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 10330 // Fields of incomplete type force their record to be invalid. 10331 Record->setInvalidDecl(); 10332 InvalidDecl = true; 10333 } else { 10334 NamedDecl *Def; 10335 EltTy->isIncompleteType(&Def); 10336 if (Def && Def->isInvalidDecl()) { 10337 Record->setInvalidDecl(); 10338 InvalidDecl = true; 10339 } 10340 } 10341 } 10342 10343 // OpenCL v1.2 s6.9.c: bitfields are not supported. 10344 if (BitWidth && getLangOpts().OpenCL) { 10345 Diag(Loc, diag::err_opencl_bitfields); 10346 InvalidDecl = true; 10347 } 10348 10349 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10350 // than a variably modified type. 10351 if (!InvalidDecl && T->isVariablyModifiedType()) { 10352 bool SizeIsNegative; 10353 llvm::APSInt Oversized; 10354 10355 TypeSourceInfo *FixedTInfo = 10356 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 10357 SizeIsNegative, 10358 Oversized); 10359 if (FixedTInfo) { 10360 Diag(Loc, diag::warn_illegal_constant_array_size); 10361 TInfo = FixedTInfo; 10362 T = FixedTInfo->getType(); 10363 } else { 10364 if (SizeIsNegative) 10365 Diag(Loc, diag::err_typecheck_negative_array_size); 10366 else if (Oversized.getBoolValue()) 10367 Diag(Loc, diag::err_array_too_large) 10368 << Oversized.toString(10); 10369 else 10370 Diag(Loc, diag::err_typecheck_field_variable_size); 10371 InvalidDecl = true; 10372 } 10373 } 10374 10375 // Fields can not have abstract class types 10376 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 10377 diag::err_abstract_type_in_decl, 10378 AbstractFieldType)) 10379 InvalidDecl = true; 10380 10381 bool ZeroWidth = false; 10382 // If this is declared as a bit-field, check the bit-field. 10383 if (!InvalidDecl && BitWidth) { 10384 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 10385 if (!BitWidth) { 10386 InvalidDecl = true; 10387 BitWidth = 0; 10388 ZeroWidth = false; 10389 } 10390 } 10391 10392 // Check that 'mutable' is consistent with the type of the declaration. 10393 if (!InvalidDecl && Mutable) { 10394 unsigned DiagID = 0; 10395 if (T->isReferenceType()) 10396 DiagID = diag::err_mutable_reference; 10397 else if (T.isConstQualified()) 10398 DiagID = diag::err_mutable_const; 10399 10400 if (DiagID) { 10401 SourceLocation ErrLoc = Loc; 10402 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 10403 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 10404 Diag(ErrLoc, DiagID); 10405 Mutable = false; 10406 InvalidDecl = true; 10407 } 10408 } 10409 10410 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 10411 BitWidth, Mutable, InitStyle); 10412 if (InvalidDecl) 10413 NewFD->setInvalidDecl(); 10414 10415 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 10416 Diag(Loc, diag::err_duplicate_member) << II; 10417 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10418 NewFD->setInvalidDecl(); 10419 } 10420 10421 if (!InvalidDecl && getLangOpts().CPlusPlus) { 10422 if (Record->isUnion()) { 10423 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10424 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10425 if (RDecl->getDefinition()) { 10426 // C++ [class.union]p1: An object of a class with a non-trivial 10427 // constructor, a non-trivial copy constructor, a non-trivial 10428 // destructor, or a non-trivial copy assignment operator 10429 // cannot be a member of a union, nor can an array of such 10430 // objects. 10431 if (CheckNontrivialField(NewFD)) 10432 NewFD->setInvalidDecl(); 10433 } 10434 } 10435 10436 // C++ [class.union]p1: If a union contains a member of reference type, 10437 // the program is ill-formed. 10438 if (EltTy->isReferenceType()) { 10439 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 10440 << NewFD->getDeclName() << EltTy; 10441 NewFD->setInvalidDecl(); 10442 } 10443 } 10444 } 10445 10446 // FIXME: We need to pass in the attributes given an AST 10447 // representation, not a parser representation. 10448 if (D) { 10449 // FIXME: What to pass instead of TUScope? 10450 ProcessDeclAttributes(TUScope, NewFD, *D); 10451 10452 if (NewFD->hasAttrs()) 10453 CheckAlignasUnderalignment(NewFD); 10454 } 10455 10456 // In auto-retain/release, infer strong retension for fields of 10457 // retainable type. 10458 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 10459 NewFD->setInvalidDecl(); 10460 10461 if (T.isObjCGCWeak()) 10462 Diag(Loc, diag::warn_attribute_weak_on_field); 10463 10464 NewFD->setAccess(AS); 10465 return NewFD; 10466} 10467 10468bool Sema::CheckNontrivialField(FieldDecl *FD) { 10469 assert(FD); 10470 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 10471 10472 if (FD->isInvalidDecl()) 10473 return true; 10474 10475 QualType EltTy = Context.getBaseElementType(FD->getType()); 10476 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 10477 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 10478 if (RDecl->getDefinition()) { 10479 // We check for copy constructors before constructors 10480 // because otherwise we'll never get complaints about 10481 // copy constructors. 10482 10483 CXXSpecialMember member = CXXInvalid; 10484 // We're required to check for any non-trivial constructors. Since the 10485 // implicit default constructor is suppressed if there are any 10486 // user-declared constructors, we just need to check that there is a 10487 // trivial default constructor and a trivial copy constructor. (We don't 10488 // worry about move constructors here, since this is a C++98 check.) 10489 if (RDecl->hasNonTrivialCopyConstructor()) 10490 member = CXXCopyConstructor; 10491 else if (!RDecl->hasTrivialDefaultConstructor()) 10492 member = CXXDefaultConstructor; 10493 else if (RDecl->hasNonTrivialCopyAssignment()) 10494 member = CXXCopyAssignment; 10495 else if (RDecl->hasNonTrivialDestructor()) 10496 member = CXXDestructor; 10497 10498 if (member != CXXInvalid) { 10499 if (!getLangOpts().CPlusPlus11 && 10500 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 10501 // Objective-C++ ARC: it is an error to have a non-trivial field of 10502 // a union. However, system headers in Objective-C programs 10503 // occasionally have Objective-C lifetime objects within unions, 10504 // and rather than cause the program to fail, we make those 10505 // members unavailable. 10506 SourceLocation Loc = FD->getLocation(); 10507 if (getSourceManager().isInSystemHeader(Loc)) { 10508 if (!FD->hasAttr<UnavailableAttr>()) 10509 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 10510 "this system field has retaining ownership")); 10511 return false; 10512 } 10513 } 10514 10515 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 10516 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 10517 diag::err_illegal_union_or_anon_struct_member) 10518 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 10519 DiagnoseNontrivial(RDecl, member); 10520 return !getLangOpts().CPlusPlus11; 10521 } 10522 } 10523 } 10524 10525 return false; 10526} 10527 10528/// TranslateIvarVisibility - Translate visibility from a token ID to an 10529/// AST enum value. 10530static ObjCIvarDecl::AccessControl 10531TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 10532 switch (ivarVisibility) { 10533 default: llvm_unreachable("Unknown visitibility kind"); 10534 case tok::objc_private: return ObjCIvarDecl::Private; 10535 case tok::objc_public: return ObjCIvarDecl::Public; 10536 case tok::objc_protected: return ObjCIvarDecl::Protected; 10537 case tok::objc_package: return ObjCIvarDecl::Package; 10538 } 10539} 10540 10541/// ActOnIvar - Each ivar field of an objective-c class is passed into this 10542/// in order to create an IvarDecl object for it. 10543Decl *Sema::ActOnIvar(Scope *S, 10544 SourceLocation DeclStart, 10545 Declarator &D, Expr *BitfieldWidth, 10546 tok::ObjCKeywordKind Visibility) { 10547 10548 IdentifierInfo *II = D.getIdentifier(); 10549 Expr *BitWidth = (Expr*)BitfieldWidth; 10550 SourceLocation Loc = DeclStart; 10551 if (II) Loc = D.getIdentifierLoc(); 10552 10553 // FIXME: Unnamed fields can be handled in various different ways, for 10554 // example, unnamed unions inject all members into the struct namespace! 10555 10556 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10557 QualType T = TInfo->getType(); 10558 10559 if (BitWidth) { 10560 // 6.7.2.1p3, 6.7.2.1p4 10561 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 10562 if (!BitWidth) 10563 D.setInvalidType(); 10564 } else { 10565 // Not a bitfield. 10566 10567 // validate II. 10568 10569 } 10570 if (T->isReferenceType()) { 10571 Diag(Loc, diag::err_ivar_reference_type); 10572 D.setInvalidType(); 10573 } 10574 // C99 6.7.2.1p8: A member of a structure or union may have any type other 10575 // than a variably modified type. 10576 else if (T->isVariablyModifiedType()) { 10577 Diag(Loc, diag::err_typecheck_ivar_variable_size); 10578 D.setInvalidType(); 10579 } 10580 10581 // Get the visibility (access control) for this ivar. 10582 ObjCIvarDecl::AccessControl ac = 10583 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 10584 : ObjCIvarDecl::None; 10585 // Must set ivar's DeclContext to its enclosing interface. 10586 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 10587 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 10588 return 0; 10589 ObjCContainerDecl *EnclosingContext; 10590 if (ObjCImplementationDecl *IMPDecl = 10591 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10592 if (LangOpts.ObjCRuntime.isFragile()) { 10593 // Case of ivar declared in an implementation. Context is that of its class. 10594 EnclosingContext = IMPDecl->getClassInterface(); 10595 assert(EnclosingContext && "Implementation has no class interface!"); 10596 } 10597 else 10598 EnclosingContext = EnclosingDecl; 10599 } else { 10600 if (ObjCCategoryDecl *CDecl = 10601 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 10602 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 10603 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 10604 return 0; 10605 } 10606 } 10607 EnclosingContext = EnclosingDecl; 10608 } 10609 10610 // Construct the decl. 10611 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 10612 DeclStart, Loc, II, T, 10613 TInfo, ac, (Expr *)BitfieldWidth); 10614 10615 if (II) { 10616 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 10617 ForRedeclaration); 10618 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 10619 && !isa<TagDecl>(PrevDecl)) { 10620 Diag(Loc, diag::err_duplicate_member) << II; 10621 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10622 NewID->setInvalidDecl(); 10623 } 10624 } 10625 10626 // Process attributes attached to the ivar. 10627 ProcessDeclAttributes(S, NewID, D); 10628 10629 if (D.isInvalidType()) 10630 NewID->setInvalidDecl(); 10631 10632 // In ARC, infer 'retaining' for ivars of retainable type. 10633 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 10634 NewID->setInvalidDecl(); 10635 10636 if (D.getDeclSpec().isModulePrivateSpecified()) 10637 NewID->setModulePrivate(); 10638 10639 if (II) { 10640 // FIXME: When interfaces are DeclContexts, we'll need to add 10641 // these to the interface. 10642 S->AddDecl(NewID); 10643 IdResolver.AddDecl(NewID); 10644 } 10645 10646 if (LangOpts.ObjCRuntime.isNonFragile() && 10647 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 10648 Diag(Loc, diag::warn_ivars_in_interface); 10649 10650 return NewID; 10651} 10652 10653/// ActOnLastBitfield - This routine handles synthesized bitfields rules for 10654/// class and class extensions. For every class @interface and class 10655/// extension @interface, if the last ivar is a bitfield of any type, 10656/// then add an implicit `char :0` ivar to the end of that interface. 10657void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 10658 SmallVectorImpl<Decl *> &AllIvarDecls) { 10659 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 10660 return; 10661 10662 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 10663 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 10664 10665 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 10666 return; 10667 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 10668 if (!ID) { 10669 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 10670 if (!CD->IsClassExtension()) 10671 return; 10672 } 10673 // No need to add this to end of @implementation. 10674 else 10675 return; 10676 } 10677 // All conditions are met. Add a new bitfield to the tail end of ivars. 10678 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 10679 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 10680 10681 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 10682 DeclLoc, DeclLoc, 0, 10683 Context.CharTy, 10684 Context.getTrivialTypeSourceInfo(Context.CharTy, 10685 DeclLoc), 10686 ObjCIvarDecl::Private, BW, 10687 true); 10688 AllIvarDecls.push_back(Ivar); 10689} 10690 10691void Sema::ActOnFields(Scope* S, 10692 SourceLocation RecLoc, Decl *EnclosingDecl, 10693 llvm::ArrayRef<Decl *> Fields, 10694 SourceLocation LBrac, SourceLocation RBrac, 10695 AttributeList *Attr) { 10696 assert(EnclosingDecl && "missing record or interface decl"); 10697 10698 // If this is an Objective-C @implementation or category and we have 10699 // new fields here we should reset the layout of the interface since 10700 // it will now change. 10701 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 10702 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 10703 switch (DC->getKind()) { 10704 default: break; 10705 case Decl::ObjCCategory: 10706 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 10707 break; 10708 case Decl::ObjCImplementation: 10709 Context. 10710 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 10711 break; 10712 } 10713 } 10714 10715 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 10716 10717 // Start counting up the number of named members; make sure to include 10718 // members of anonymous structs and unions in the total. 10719 unsigned NumNamedMembers = 0; 10720 if (Record) { 10721 for (RecordDecl::decl_iterator i = Record->decls_begin(), 10722 e = Record->decls_end(); i != e; i++) { 10723 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 10724 if (IFD->getDeclName()) 10725 ++NumNamedMembers; 10726 } 10727 } 10728 10729 // Verify that all the fields are okay. 10730 SmallVector<FieldDecl*, 32> RecFields; 10731 10732 bool ARCErrReported = false; 10733 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 10734 i != end; ++i) { 10735 FieldDecl *FD = cast<FieldDecl>(*i); 10736 10737 // Get the type for the field. 10738 const Type *FDTy = FD->getType().getTypePtr(); 10739 10740 if (!FD->isAnonymousStructOrUnion()) { 10741 // Remember all fields written by the user. 10742 RecFields.push_back(FD); 10743 } 10744 10745 // If the field is already invalid for some reason, don't emit more 10746 // diagnostics about it. 10747 if (FD->isInvalidDecl()) { 10748 EnclosingDecl->setInvalidDecl(); 10749 continue; 10750 } 10751 10752 // C99 6.7.2.1p2: 10753 // A structure or union shall not contain a member with 10754 // incomplete or function type (hence, a structure shall not 10755 // contain an instance of itself, but may contain a pointer to 10756 // an instance of itself), except that the last member of a 10757 // structure with more than one named member may have incomplete 10758 // array type; such a structure (and any union containing, 10759 // possibly recursively, a member that is such a structure) 10760 // shall not be a member of a structure or an element of an 10761 // array. 10762 if (FDTy->isFunctionType()) { 10763 // Field declared as a function. 10764 Diag(FD->getLocation(), diag::err_field_declared_as_function) 10765 << FD->getDeclName(); 10766 FD->setInvalidDecl(); 10767 EnclosingDecl->setInvalidDecl(); 10768 continue; 10769 } else if (FDTy->isIncompleteArrayType() && Record && 10770 ((i + 1 == Fields.end() && !Record->isUnion()) || 10771 ((getLangOpts().MicrosoftExt || 10772 getLangOpts().CPlusPlus) && 10773 (i + 1 == Fields.end() || Record->isUnion())))) { 10774 // Flexible array member. 10775 // Microsoft and g++ is more permissive regarding flexible array. 10776 // It will accept flexible array in union and also 10777 // as the sole element of a struct/class. 10778 if (getLangOpts().MicrosoftExt) { 10779 if (Record->isUnion()) 10780 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 10781 << FD->getDeclName(); 10782 else if (Fields.size() == 1) 10783 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 10784 << FD->getDeclName() << Record->getTagKind(); 10785 } else if (getLangOpts().CPlusPlus) { 10786 if (Record->isUnion()) 10787 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10788 << FD->getDeclName(); 10789 else if (Fields.size() == 1) 10790 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 10791 << FD->getDeclName() << Record->getTagKind(); 10792 } else if (!getLangOpts().C99) { 10793 if (Record->isUnion()) 10794 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 10795 << FD->getDeclName(); 10796 else 10797 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 10798 << FD->getDeclName() << Record->getTagKind(); 10799 } else if (NumNamedMembers < 1) { 10800 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 10801 << FD->getDeclName(); 10802 FD->setInvalidDecl(); 10803 EnclosingDecl->setInvalidDecl(); 10804 continue; 10805 } 10806 if (!FD->getType()->isDependentType() && 10807 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 10808 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 10809 << FD->getDeclName() << FD->getType(); 10810 FD->setInvalidDecl(); 10811 EnclosingDecl->setInvalidDecl(); 10812 continue; 10813 } 10814 // Okay, we have a legal flexible array member at the end of the struct. 10815 if (Record) 10816 Record->setHasFlexibleArrayMember(true); 10817 } else if (!FDTy->isDependentType() && 10818 RequireCompleteType(FD->getLocation(), FD->getType(), 10819 diag::err_field_incomplete)) { 10820 // Incomplete type 10821 FD->setInvalidDecl(); 10822 EnclosingDecl->setInvalidDecl(); 10823 continue; 10824 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 10825 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 10826 // If this is a member of a union, then entire union becomes "flexible". 10827 if (Record && Record->isUnion()) { 10828 Record->setHasFlexibleArrayMember(true); 10829 } else { 10830 // If this is a struct/class and this is not the last element, reject 10831 // it. Note that GCC supports variable sized arrays in the middle of 10832 // structures. 10833 if (i + 1 != Fields.end()) 10834 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 10835 << FD->getDeclName() << FD->getType(); 10836 else { 10837 // We support flexible arrays at the end of structs in 10838 // other structs as an extension. 10839 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 10840 << FD->getDeclName(); 10841 if (Record) 10842 Record->setHasFlexibleArrayMember(true); 10843 } 10844 } 10845 } 10846 if (isa<ObjCContainerDecl>(EnclosingDecl) && 10847 RequireNonAbstractType(FD->getLocation(), FD->getType(), 10848 diag::err_abstract_type_in_decl, 10849 AbstractIvarType)) { 10850 // Ivars can not have abstract class types 10851 FD->setInvalidDecl(); 10852 } 10853 if (Record && FDTTy->getDecl()->hasObjectMember()) 10854 Record->setHasObjectMember(true); 10855 if (Record && FDTTy->getDecl()->hasVolatileMember()) 10856 Record->setHasVolatileMember(true); 10857 } else if (FDTy->isObjCObjectType()) { 10858 /// A field cannot be an Objective-c object 10859 Diag(FD->getLocation(), diag::err_statically_allocated_object) 10860 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 10861 QualType T = Context.getObjCObjectPointerType(FD->getType()); 10862 FD->setType(T); 10863 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 10864 (!getLangOpts().CPlusPlus || Record->isUnion())) { 10865 // It's an error in ARC if a field has lifetime. 10866 // We don't want to report this in a system header, though, 10867 // so we just make the field unavailable. 10868 // FIXME: that's really not sufficient; we need to make the type 10869 // itself invalid to, say, initialize or copy. 10870 QualType T = FD->getType(); 10871 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 10872 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 10873 SourceLocation loc = FD->getLocation(); 10874 if (getSourceManager().isInSystemHeader(loc)) { 10875 if (!FD->hasAttr<UnavailableAttr>()) { 10876 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 10877 "this system field has retaining ownership")); 10878 } 10879 } else { 10880 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 10881 << T->isBlockPointerType() << Record->getTagKind(); 10882 } 10883 ARCErrReported = true; 10884 } 10885 } else if (getLangOpts().ObjC1 && 10886 getLangOpts().getGC() != LangOptions::NonGC && 10887 Record && !Record->hasObjectMember()) { 10888 if (FD->getType()->isObjCObjectPointerType() || 10889 FD->getType().isObjCGCStrong()) 10890 Record->setHasObjectMember(true); 10891 else if (Context.getAsArrayType(FD->getType())) { 10892 QualType BaseType = Context.getBaseElementType(FD->getType()); 10893 if (BaseType->isRecordType() && 10894 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 10895 Record->setHasObjectMember(true); 10896 else if (BaseType->isObjCObjectPointerType() || 10897 BaseType.isObjCGCStrong()) 10898 Record->setHasObjectMember(true); 10899 } 10900 } 10901 if (Record && FD->getType().isVolatileQualified()) 10902 Record->setHasVolatileMember(true); 10903 // Keep track of the number of named members. 10904 if (FD->getIdentifier()) 10905 ++NumNamedMembers; 10906 } 10907 10908 // Okay, we successfully defined 'Record'. 10909 if (Record) { 10910 bool Completed = false; 10911 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 10912 if (!CXXRecord->isInvalidDecl()) { 10913 // Set access bits correctly on the directly-declared conversions. 10914 for (CXXRecordDecl::conversion_iterator 10915 I = CXXRecord->conversion_begin(), 10916 E = CXXRecord->conversion_end(); I != E; ++I) 10917 I.setAccess((*I)->getAccess()); 10918 10919 if (!CXXRecord->isDependentType()) { 10920 // Adjust user-defined destructor exception spec. 10921 if (getLangOpts().CPlusPlus11 && 10922 CXXRecord->hasUserDeclaredDestructor()) 10923 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 10924 10925 // Add any implicitly-declared members to this class. 10926 AddImplicitlyDeclaredMembersToClass(CXXRecord); 10927 10928 // If we have virtual base classes, we may end up finding multiple 10929 // final overriders for a given virtual function. Check for this 10930 // problem now. 10931 if (CXXRecord->getNumVBases()) { 10932 CXXFinalOverriderMap FinalOverriders; 10933 CXXRecord->getFinalOverriders(FinalOverriders); 10934 10935 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 10936 MEnd = FinalOverriders.end(); 10937 M != MEnd; ++M) { 10938 for (OverridingMethods::iterator SO = M->second.begin(), 10939 SOEnd = M->second.end(); 10940 SO != SOEnd; ++SO) { 10941 assert(SO->second.size() > 0 && 10942 "Virtual function without overridding functions?"); 10943 if (SO->second.size() == 1) 10944 continue; 10945 10946 // C++ [class.virtual]p2: 10947 // In a derived class, if a virtual member function of a base 10948 // class subobject has more than one final overrider the 10949 // program is ill-formed. 10950 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 10951 << (const NamedDecl *)M->first << Record; 10952 Diag(M->first->getLocation(), 10953 diag::note_overridden_virtual_function); 10954 for (OverridingMethods::overriding_iterator 10955 OM = SO->second.begin(), 10956 OMEnd = SO->second.end(); 10957 OM != OMEnd; ++OM) 10958 Diag(OM->Method->getLocation(), diag::note_final_overrider) 10959 << (const NamedDecl *)M->first << OM->Method->getParent(); 10960 10961 Record->setInvalidDecl(); 10962 } 10963 } 10964 CXXRecord->completeDefinition(&FinalOverriders); 10965 Completed = true; 10966 } 10967 } 10968 } 10969 } 10970 10971 if (!Completed) 10972 Record->completeDefinition(); 10973 10974 if (Record->hasAttrs()) 10975 CheckAlignasUnderalignment(Record); 10976 } else { 10977 ObjCIvarDecl **ClsFields = 10978 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 10979 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 10980 ID->setEndOfDefinitionLoc(RBrac); 10981 // Add ivar's to class's DeclContext. 10982 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 10983 ClsFields[i]->setLexicalDeclContext(ID); 10984 ID->addDecl(ClsFields[i]); 10985 } 10986 // Must enforce the rule that ivars in the base classes may not be 10987 // duplicates. 10988 if (ID->getSuperClass()) 10989 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 10990 } else if (ObjCImplementationDecl *IMPDecl = 10991 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 10992 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 10993 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 10994 // Ivar declared in @implementation never belongs to the implementation. 10995 // Only it is in implementation's lexical context. 10996 ClsFields[I]->setLexicalDeclContext(IMPDecl); 10997 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 10998 IMPDecl->setIvarLBraceLoc(LBrac); 10999 IMPDecl->setIvarRBraceLoc(RBrac); 11000 } else if (ObjCCategoryDecl *CDecl = 11001 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11002 // case of ivars in class extension; all other cases have been 11003 // reported as errors elsewhere. 11004 // FIXME. Class extension does not have a LocEnd field. 11005 // CDecl->setLocEnd(RBrac); 11006 // Add ivar's to class extension's DeclContext. 11007 // Diagnose redeclaration of private ivars. 11008 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 11009 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 11010 if (IDecl) { 11011 if (const ObjCIvarDecl *ClsIvar = 11012 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 11013 Diag(ClsFields[i]->getLocation(), 11014 diag::err_duplicate_ivar_declaration); 11015 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 11016 continue; 11017 } 11018 for (ObjCInterfaceDecl::known_extensions_iterator 11019 Ext = IDecl->known_extensions_begin(), 11020 ExtEnd = IDecl->known_extensions_end(); 11021 Ext != ExtEnd; ++Ext) { 11022 if (const ObjCIvarDecl *ClsExtIvar 11023 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 11024 Diag(ClsFields[i]->getLocation(), 11025 diag::err_duplicate_ivar_declaration); 11026 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 11027 continue; 11028 } 11029 } 11030 } 11031 ClsFields[i]->setLexicalDeclContext(CDecl); 11032 CDecl->addDecl(ClsFields[i]); 11033 } 11034 CDecl->setIvarLBraceLoc(LBrac); 11035 CDecl->setIvarRBraceLoc(RBrac); 11036 } 11037 } 11038 11039 if (Attr) 11040 ProcessDeclAttributeList(S, Record, Attr); 11041} 11042 11043/// \brief Determine whether the given integral value is representable within 11044/// the given type T. 11045static bool isRepresentableIntegerValue(ASTContext &Context, 11046 llvm::APSInt &Value, 11047 QualType T) { 11048 assert(T->isIntegralType(Context) && "Integral type required!"); 11049 unsigned BitWidth = Context.getIntWidth(T); 11050 11051 if (Value.isUnsigned() || Value.isNonNegative()) { 11052 if (T->isSignedIntegerOrEnumerationType()) 11053 --BitWidth; 11054 return Value.getActiveBits() <= BitWidth; 11055 } 11056 return Value.getMinSignedBits() <= BitWidth; 11057} 11058 11059// \brief Given an integral type, return the next larger integral type 11060// (or a NULL type of no such type exists). 11061static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 11062 // FIXME: Int128/UInt128 support, which also needs to be introduced into 11063 // enum checking below. 11064 assert(T->isIntegralType(Context) && "Integral type required!"); 11065 const unsigned NumTypes = 4; 11066 QualType SignedIntegralTypes[NumTypes] = { 11067 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 11068 }; 11069 QualType UnsignedIntegralTypes[NumTypes] = { 11070 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 11071 Context.UnsignedLongLongTy 11072 }; 11073 11074 unsigned BitWidth = Context.getTypeSize(T); 11075 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 11076 : UnsignedIntegralTypes; 11077 for (unsigned I = 0; I != NumTypes; ++I) 11078 if (Context.getTypeSize(Types[I]) > BitWidth) 11079 return Types[I]; 11080 11081 return QualType(); 11082} 11083 11084EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 11085 EnumConstantDecl *LastEnumConst, 11086 SourceLocation IdLoc, 11087 IdentifierInfo *Id, 11088 Expr *Val) { 11089 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11090 llvm::APSInt EnumVal(IntWidth); 11091 QualType EltTy; 11092 11093 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 11094 Val = 0; 11095 11096 if (Val) 11097 Val = DefaultLvalueConversion(Val).take(); 11098 11099 if (Val) { 11100 if (Enum->isDependentType() || Val->isTypeDependent()) 11101 EltTy = Context.DependentTy; 11102 else { 11103 SourceLocation ExpLoc; 11104 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 11105 !getLangOpts().MicrosoftMode) { 11106 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 11107 // constant-expression in the enumerator-definition shall be a converted 11108 // constant expression of the underlying type. 11109 EltTy = Enum->getIntegerType(); 11110 ExprResult Converted = 11111 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 11112 CCEK_Enumerator); 11113 if (Converted.isInvalid()) 11114 Val = 0; 11115 else 11116 Val = Converted.take(); 11117 } else if (!Val->isValueDependent() && 11118 !(Val = VerifyIntegerConstantExpression(Val, 11119 &EnumVal).take())) { 11120 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 11121 } else { 11122 if (Enum->isFixed()) { 11123 EltTy = Enum->getIntegerType(); 11124 11125 // In Obj-C and Microsoft mode, require the enumeration value to be 11126 // representable in the underlying type of the enumeration. In C++11, 11127 // we perform a non-narrowing conversion as part of converted constant 11128 // expression checking. 11129 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 11130 if (getLangOpts().MicrosoftMode) { 11131 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 11132 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 11133 } else 11134 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 11135 } else 11136 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 11137 } else if (getLangOpts().CPlusPlus) { 11138 // C++11 [dcl.enum]p5: 11139 // If the underlying type is not fixed, the type of each enumerator 11140 // is the type of its initializing value: 11141 // - If an initializer is specified for an enumerator, the 11142 // initializing value has the same type as the expression. 11143 EltTy = Val->getType(); 11144 } else { 11145 // C99 6.7.2.2p2: 11146 // The expression that defines the value of an enumeration constant 11147 // shall be an integer constant expression that has a value 11148 // representable as an int. 11149 11150 // Complain if the value is not representable in an int. 11151 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 11152 Diag(IdLoc, diag::ext_enum_value_not_int) 11153 << EnumVal.toString(10) << Val->getSourceRange() 11154 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 11155 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 11156 // Force the type of the expression to 'int'. 11157 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 11158 } 11159 EltTy = Val->getType(); 11160 } 11161 } 11162 } 11163 } 11164 11165 if (!Val) { 11166 if (Enum->isDependentType()) 11167 EltTy = Context.DependentTy; 11168 else if (!LastEnumConst) { 11169 // C++0x [dcl.enum]p5: 11170 // If the underlying type is not fixed, the type of each enumerator 11171 // is the type of its initializing value: 11172 // - If no initializer is specified for the first enumerator, the 11173 // initializing value has an unspecified integral type. 11174 // 11175 // GCC uses 'int' for its unspecified integral type, as does 11176 // C99 6.7.2.2p3. 11177 if (Enum->isFixed()) { 11178 EltTy = Enum->getIntegerType(); 11179 } 11180 else { 11181 EltTy = Context.IntTy; 11182 } 11183 } else { 11184 // Assign the last value + 1. 11185 EnumVal = LastEnumConst->getInitVal(); 11186 ++EnumVal; 11187 EltTy = LastEnumConst->getType(); 11188 11189 // Check for overflow on increment. 11190 if (EnumVal < LastEnumConst->getInitVal()) { 11191 // C++0x [dcl.enum]p5: 11192 // If the underlying type is not fixed, the type of each enumerator 11193 // is the type of its initializing value: 11194 // 11195 // - Otherwise the type of the initializing value is the same as 11196 // the type of the initializing value of the preceding enumerator 11197 // unless the incremented value is not representable in that type, 11198 // in which case the type is an unspecified integral type 11199 // sufficient to contain the incremented value. If no such type 11200 // exists, the program is ill-formed. 11201 QualType T = getNextLargerIntegralType(Context, EltTy); 11202 if (T.isNull() || Enum->isFixed()) { 11203 // There is no integral type larger enough to represent this 11204 // value. Complain, then allow the value to wrap around. 11205 EnumVal = LastEnumConst->getInitVal(); 11206 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 11207 ++EnumVal; 11208 if (Enum->isFixed()) 11209 // When the underlying type is fixed, this is ill-formed. 11210 Diag(IdLoc, diag::err_enumerator_wrapped) 11211 << EnumVal.toString(10) 11212 << EltTy; 11213 else 11214 Diag(IdLoc, diag::warn_enumerator_too_large) 11215 << EnumVal.toString(10); 11216 } else { 11217 EltTy = T; 11218 } 11219 11220 // Retrieve the last enumerator's value, extent that type to the 11221 // type that is supposed to be large enough to represent the incremented 11222 // value, then increment. 11223 EnumVal = LastEnumConst->getInitVal(); 11224 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 11225 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 11226 ++EnumVal; 11227 11228 // If we're not in C++, diagnose the overflow of enumerator values, 11229 // which in C99 means that the enumerator value is not representable in 11230 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 11231 // permits enumerator values that are representable in some larger 11232 // integral type. 11233 if (!getLangOpts().CPlusPlus && !T.isNull()) 11234 Diag(IdLoc, diag::warn_enum_value_overflow); 11235 } else if (!getLangOpts().CPlusPlus && 11236 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 11237 // Enforce C99 6.7.2.2p2 even when we compute the next value. 11238 Diag(IdLoc, diag::ext_enum_value_not_int) 11239 << EnumVal.toString(10) << 1; 11240 } 11241 } 11242 } 11243 11244 if (!EltTy->isDependentType()) { 11245 // Make the enumerator value match the signedness and size of the 11246 // enumerator's type. 11247 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 11248 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 11249 } 11250 11251 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 11252 Val, EnumVal); 11253} 11254 11255 11256Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 11257 SourceLocation IdLoc, IdentifierInfo *Id, 11258 AttributeList *Attr, 11259 SourceLocation EqualLoc, Expr *Val) { 11260 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 11261 EnumConstantDecl *LastEnumConst = 11262 cast_or_null<EnumConstantDecl>(lastEnumConst); 11263 11264 // The scope passed in may not be a decl scope. Zip up the scope tree until 11265 // we find one that is. 11266 S = getNonFieldDeclScope(S); 11267 11268 // Verify that there isn't already something declared with this name in this 11269 // scope. 11270 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 11271 ForRedeclaration); 11272 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11273 // Maybe we will complain about the shadowed template parameter. 11274 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 11275 // Just pretend that we didn't see the previous declaration. 11276 PrevDecl = 0; 11277 } 11278 11279 if (PrevDecl) { 11280 // When in C++, we may get a TagDecl with the same name; in this case the 11281 // enum constant will 'hide' the tag. 11282 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 11283 "Received TagDecl when not in C++!"); 11284 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 11285 if (isa<EnumConstantDecl>(PrevDecl)) 11286 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 11287 else 11288 Diag(IdLoc, diag::err_redefinition) << Id; 11289 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11290 return 0; 11291 } 11292 } 11293 11294 // C++ [class.mem]p15: 11295 // If T is the name of a class, then each of the following shall have a name 11296 // different from T: 11297 // - every enumerator of every member of class T that is an unscoped 11298 // enumerated type 11299 if (CXXRecordDecl *Record 11300 = dyn_cast<CXXRecordDecl>( 11301 TheEnumDecl->getDeclContext()->getRedeclContext())) 11302 if (!TheEnumDecl->isScoped() && 11303 Record->getIdentifier() && Record->getIdentifier() == Id) 11304 Diag(IdLoc, diag::err_member_name_of_class) << Id; 11305 11306 EnumConstantDecl *New = 11307 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 11308 11309 if (New) { 11310 // Process attributes. 11311 if (Attr) ProcessDeclAttributeList(S, New, Attr); 11312 11313 // Register this decl in the current scope stack. 11314 New->setAccess(TheEnumDecl->getAccess()); 11315 PushOnScopeChains(New, S); 11316 } 11317 11318 ActOnDocumentableDecl(New); 11319 11320 return New; 11321} 11322 11323// Returns true when the enum initial expression does not trigger the 11324// duplicate enum warning. A few common cases are exempted as follows: 11325// Element2 = Element1 11326// Element2 = Element1 + 1 11327// Element2 = Element1 - 1 11328// Where Element2 and Element1 are from the same enum. 11329static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 11330 Expr *InitExpr = ECD->getInitExpr(); 11331 if (!InitExpr) 11332 return true; 11333 InitExpr = InitExpr->IgnoreImpCasts(); 11334 11335 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 11336 if (!BO->isAdditiveOp()) 11337 return true; 11338 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 11339 if (!IL) 11340 return true; 11341 if (IL->getValue() != 1) 11342 return true; 11343 11344 InitExpr = BO->getLHS(); 11345 } 11346 11347 // This checks if the elements are from the same enum. 11348 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 11349 if (!DRE) 11350 return true; 11351 11352 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 11353 if (!EnumConstant) 11354 return true; 11355 11356 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 11357 Enum) 11358 return true; 11359 11360 return false; 11361} 11362 11363struct DupKey { 11364 int64_t val; 11365 bool isTombstoneOrEmptyKey; 11366 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 11367 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 11368}; 11369 11370static DupKey GetDupKey(const llvm::APSInt& Val) { 11371 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 11372 false); 11373} 11374 11375struct DenseMapInfoDupKey { 11376 static DupKey getEmptyKey() { return DupKey(0, true); } 11377 static DupKey getTombstoneKey() { return DupKey(1, true); } 11378 static unsigned getHashValue(const DupKey Key) { 11379 return (unsigned)(Key.val * 37); 11380 } 11381 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 11382 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 11383 LHS.val == RHS.val; 11384 } 11385}; 11386 11387// Emits a warning when an element is implicitly set a value that 11388// a previous element has already been set to. 11389static void CheckForDuplicateEnumValues(Sema &S, Decl **Elements, 11390 unsigned NumElements, EnumDecl *Enum, 11391 QualType EnumType) { 11392 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 11393 Enum->getLocation()) == 11394 DiagnosticsEngine::Ignored) 11395 return; 11396 // Avoid anonymous enums 11397 if (!Enum->getIdentifier()) 11398 return; 11399 11400 // Only check for small enums. 11401 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 11402 return; 11403 11404 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 11405 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 11406 11407 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 11408 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 11409 ValueToVectorMap; 11410 11411 DuplicatesVector DupVector; 11412 ValueToVectorMap EnumMap; 11413 11414 // Populate the EnumMap with all values represented by enum constants without 11415 // an initialier. 11416 for (unsigned i = 0; i < NumElements; ++i) { 11417 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 11418 11419 // Null EnumConstantDecl means a previous diagnostic has been emitted for 11420 // this constant. Skip this enum since it may be ill-formed. 11421 if (!ECD) { 11422 return; 11423 } 11424 11425 if (ECD->getInitExpr()) 11426 continue; 11427 11428 DupKey Key = GetDupKey(ECD->getInitVal()); 11429 DeclOrVector &Entry = EnumMap[Key]; 11430 11431 // First time encountering this value. 11432 if (Entry.isNull()) 11433 Entry = ECD; 11434 } 11435 11436 // Create vectors for any values that has duplicates. 11437 for (unsigned i = 0; i < NumElements; ++i) { 11438 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 11439 if (!ValidDuplicateEnum(ECD, Enum)) 11440 continue; 11441 11442 DupKey Key = GetDupKey(ECD->getInitVal()); 11443 11444 DeclOrVector& Entry = EnumMap[Key]; 11445 if (Entry.isNull()) 11446 continue; 11447 11448 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 11449 // Ensure constants are different. 11450 if (D == ECD) 11451 continue; 11452 11453 // Create new vector and push values onto it. 11454 ECDVector *Vec = new ECDVector(); 11455 Vec->push_back(D); 11456 Vec->push_back(ECD); 11457 11458 // Update entry to point to the duplicates vector. 11459 Entry = Vec; 11460 11461 // Store the vector somewhere we can consult later for quick emission of 11462 // diagnostics. 11463 DupVector.push_back(Vec); 11464 continue; 11465 } 11466 11467 ECDVector *Vec = Entry.get<ECDVector*>(); 11468 // Make sure constants are not added more than once. 11469 if (*Vec->begin() == ECD) 11470 continue; 11471 11472 Vec->push_back(ECD); 11473 } 11474 11475 // Emit diagnostics. 11476 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 11477 DupVectorEnd = DupVector.end(); 11478 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 11479 ECDVector *Vec = *DupVectorIter; 11480 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 11481 11482 // Emit warning for one enum constant. 11483 ECDVector::iterator I = Vec->begin(); 11484 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 11485 << (*I)->getName() << (*I)->getInitVal().toString(10) 11486 << (*I)->getSourceRange(); 11487 ++I; 11488 11489 // Emit one note for each of the remaining enum constants with 11490 // the same value. 11491 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 11492 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 11493 << (*I)->getName() << (*I)->getInitVal().toString(10) 11494 << (*I)->getSourceRange(); 11495 delete Vec; 11496 } 11497} 11498 11499void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 11500 SourceLocation RBraceLoc, Decl *EnumDeclX, 11501 Decl **Elements, unsigned NumElements, 11502 Scope *S, AttributeList *Attr) { 11503 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 11504 QualType EnumType = Context.getTypeDeclType(Enum); 11505 11506 if (Attr) 11507 ProcessDeclAttributeList(S, Enum, Attr); 11508 11509 if (Enum->isDependentType()) { 11510 for (unsigned i = 0; i != NumElements; ++i) { 11511 EnumConstantDecl *ECD = 11512 cast_or_null<EnumConstantDecl>(Elements[i]); 11513 if (!ECD) continue; 11514 11515 ECD->setType(EnumType); 11516 } 11517 11518 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 11519 return; 11520 } 11521 11522 // TODO: If the result value doesn't fit in an int, it must be a long or long 11523 // long value. ISO C does not support this, but GCC does as an extension, 11524 // emit a warning. 11525 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 11526 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 11527 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 11528 11529 // Verify that all the values are okay, compute the size of the values, and 11530 // reverse the list. 11531 unsigned NumNegativeBits = 0; 11532 unsigned NumPositiveBits = 0; 11533 11534 // Keep track of whether all elements have type int. 11535 bool AllElementsInt = true; 11536 11537 for (unsigned i = 0; i != NumElements; ++i) { 11538 EnumConstantDecl *ECD = 11539 cast_or_null<EnumConstantDecl>(Elements[i]); 11540 if (!ECD) continue; // Already issued a diagnostic. 11541 11542 const llvm::APSInt &InitVal = ECD->getInitVal(); 11543 11544 // Keep track of the size of positive and negative values. 11545 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 11546 NumPositiveBits = std::max(NumPositiveBits, 11547 (unsigned)InitVal.getActiveBits()); 11548 else 11549 NumNegativeBits = std::max(NumNegativeBits, 11550 (unsigned)InitVal.getMinSignedBits()); 11551 11552 // Keep track of whether every enum element has type int (very commmon). 11553 if (AllElementsInt) 11554 AllElementsInt = ECD->getType() == Context.IntTy; 11555 } 11556 11557 // Figure out the type that should be used for this enum. 11558 QualType BestType; 11559 unsigned BestWidth; 11560 11561 // C++0x N3000 [conv.prom]p3: 11562 // An rvalue of an unscoped enumeration type whose underlying 11563 // type is not fixed can be converted to an rvalue of the first 11564 // of the following types that can represent all the values of 11565 // the enumeration: int, unsigned int, long int, unsigned long 11566 // int, long long int, or unsigned long long int. 11567 // C99 6.4.4.3p2: 11568 // An identifier declared as an enumeration constant has type int. 11569 // The C99 rule is modified by a gcc extension 11570 QualType BestPromotionType; 11571 11572 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 11573 // -fshort-enums is the equivalent to specifying the packed attribute on all 11574 // enum definitions. 11575 if (LangOpts.ShortEnums) 11576 Packed = true; 11577 11578 if (Enum->isFixed()) { 11579 BestType = Enum->getIntegerType(); 11580 if (BestType->isPromotableIntegerType()) 11581 BestPromotionType = Context.getPromotedIntegerType(BestType); 11582 else 11583 BestPromotionType = BestType; 11584 // We don't need to set BestWidth, because BestType is going to be the type 11585 // of the enumerators, but we do anyway because otherwise some compilers 11586 // warn that it might be used uninitialized. 11587 BestWidth = CharWidth; 11588 } 11589 else if (NumNegativeBits) { 11590 // If there is a negative value, figure out the smallest integer type (of 11591 // int/long/longlong) that fits. 11592 // If it's packed, check also if it fits a char or a short. 11593 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 11594 BestType = Context.SignedCharTy; 11595 BestWidth = CharWidth; 11596 } else if (Packed && NumNegativeBits <= ShortWidth && 11597 NumPositiveBits < ShortWidth) { 11598 BestType = Context.ShortTy; 11599 BestWidth = ShortWidth; 11600 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 11601 BestType = Context.IntTy; 11602 BestWidth = IntWidth; 11603 } else { 11604 BestWidth = Context.getTargetInfo().getLongWidth(); 11605 11606 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 11607 BestType = Context.LongTy; 11608 } else { 11609 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11610 11611 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 11612 Diag(Enum->getLocation(), diag::warn_enum_too_large); 11613 BestType = Context.LongLongTy; 11614 } 11615 } 11616 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 11617 } else { 11618 // If there is no negative value, figure out the smallest type that fits 11619 // all of the enumerator values. 11620 // If it's packed, check also if it fits a char or a short. 11621 if (Packed && NumPositiveBits <= CharWidth) { 11622 BestType = Context.UnsignedCharTy; 11623 BestPromotionType = Context.IntTy; 11624 BestWidth = CharWidth; 11625 } else if (Packed && NumPositiveBits <= ShortWidth) { 11626 BestType = Context.UnsignedShortTy; 11627 BestPromotionType = Context.IntTy; 11628 BestWidth = ShortWidth; 11629 } else if (NumPositiveBits <= IntWidth) { 11630 BestType = Context.UnsignedIntTy; 11631 BestWidth = IntWidth; 11632 BestPromotionType 11633 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11634 ? Context.UnsignedIntTy : Context.IntTy; 11635 } else if (NumPositiveBits <= 11636 (BestWidth = Context.getTargetInfo().getLongWidth())) { 11637 BestType = Context.UnsignedLongTy; 11638 BestPromotionType 11639 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11640 ? Context.UnsignedLongTy : Context.LongTy; 11641 } else { 11642 BestWidth = Context.getTargetInfo().getLongLongWidth(); 11643 assert(NumPositiveBits <= BestWidth && 11644 "How could an initializer get larger than ULL?"); 11645 BestType = Context.UnsignedLongLongTy; 11646 BestPromotionType 11647 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 11648 ? Context.UnsignedLongLongTy : Context.LongLongTy; 11649 } 11650 } 11651 11652 // Loop over all of the enumerator constants, changing their types to match 11653 // the type of the enum if needed. 11654 for (unsigned i = 0; i != NumElements; ++i) { 11655 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 11656 if (!ECD) continue; // Already issued a diagnostic. 11657 11658 // Standard C says the enumerators have int type, but we allow, as an 11659 // extension, the enumerators to be larger than int size. If each 11660 // enumerator value fits in an int, type it as an int, otherwise type it the 11661 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 11662 // that X has type 'int', not 'unsigned'. 11663 11664 // Determine whether the value fits into an int. 11665 llvm::APSInt InitVal = ECD->getInitVal(); 11666 11667 // If it fits into an integer type, force it. Otherwise force it to match 11668 // the enum decl type. 11669 QualType NewTy; 11670 unsigned NewWidth; 11671 bool NewSign; 11672 if (!getLangOpts().CPlusPlus && 11673 !Enum->isFixed() && 11674 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 11675 NewTy = Context.IntTy; 11676 NewWidth = IntWidth; 11677 NewSign = true; 11678 } else if (ECD->getType() == BestType) { 11679 // Already the right type! 11680 if (getLangOpts().CPlusPlus) 11681 // C++ [dcl.enum]p4: Following the closing brace of an 11682 // enum-specifier, each enumerator has the type of its 11683 // enumeration. 11684 ECD->setType(EnumType); 11685 continue; 11686 } else { 11687 NewTy = BestType; 11688 NewWidth = BestWidth; 11689 NewSign = BestType->isSignedIntegerOrEnumerationType(); 11690 } 11691 11692 // Adjust the APSInt value. 11693 InitVal = InitVal.extOrTrunc(NewWidth); 11694 InitVal.setIsSigned(NewSign); 11695 ECD->setInitVal(InitVal); 11696 11697 // Adjust the Expr initializer and type. 11698 if (ECD->getInitExpr() && 11699 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 11700 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 11701 CK_IntegralCast, 11702 ECD->getInitExpr(), 11703 /*base paths*/ 0, 11704 VK_RValue)); 11705 if (getLangOpts().CPlusPlus) 11706 // C++ [dcl.enum]p4: Following the closing brace of an 11707 // enum-specifier, each enumerator has the type of its 11708 // enumeration. 11709 ECD->setType(EnumType); 11710 else 11711 ECD->setType(NewTy); 11712 } 11713 11714 Enum->completeDefinition(BestType, BestPromotionType, 11715 NumPositiveBits, NumNegativeBits); 11716 11717 // If we're declaring a function, ensure this decl isn't forgotten about - 11718 // it needs to go into the function scope. 11719 if (InFunctionDeclarator) 11720 DeclsInPrototypeScope.push_back(Enum); 11721 11722 CheckForDuplicateEnumValues(*this, Elements, NumElements, Enum, EnumType); 11723 11724 // Now that the enum type is defined, ensure it's not been underaligned. 11725 if (Enum->hasAttrs()) 11726 CheckAlignasUnderalignment(Enum); 11727} 11728 11729Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 11730 SourceLocation StartLoc, 11731 SourceLocation EndLoc) { 11732 StringLiteral *AsmString = cast<StringLiteral>(expr); 11733 11734 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 11735 AsmString, StartLoc, 11736 EndLoc); 11737 CurContext->addDecl(New); 11738 return New; 11739} 11740 11741DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 11742 SourceLocation ImportLoc, 11743 ModuleIdPath Path) { 11744 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 11745 Module::AllVisible, 11746 /*IsIncludeDirective=*/false); 11747 if (!Mod) 11748 return true; 11749 11750 SmallVector<SourceLocation, 2> IdentifierLocs; 11751 Module *ModCheck = Mod; 11752 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 11753 // If we've run out of module parents, just drop the remaining identifiers. 11754 // We need the length to be consistent. 11755 if (!ModCheck) 11756 break; 11757 ModCheck = ModCheck->Parent; 11758 11759 IdentifierLocs.push_back(Path[I].second); 11760 } 11761 11762 ImportDecl *Import = ImportDecl::Create(Context, 11763 Context.getTranslationUnitDecl(), 11764 AtLoc.isValid()? AtLoc : ImportLoc, 11765 Mod, IdentifierLocs); 11766 Context.getTranslationUnitDecl()->addDecl(Import); 11767 return Import; 11768} 11769 11770void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 11771 // Create the implicit import declaration. 11772 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 11773 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 11774 Loc, Mod, Loc); 11775 TU->addDecl(ImportD); 11776 Consumer.HandleImplicitImportDecl(ImportD); 11777 11778 // Make the module visible. 11779 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 11780} 11781 11782void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 11783 IdentifierInfo* AliasName, 11784 SourceLocation PragmaLoc, 11785 SourceLocation NameLoc, 11786 SourceLocation AliasNameLoc) { 11787 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 11788 LookupOrdinaryName); 11789 AsmLabelAttr *Attr = 11790 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 11791 11792 if (PrevDecl) 11793 PrevDecl->addAttr(Attr); 11794 else 11795 (void)ExtnameUndeclaredIdentifiers.insert( 11796 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 11797} 11798 11799void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 11800 SourceLocation PragmaLoc, 11801 SourceLocation NameLoc) { 11802 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 11803 11804 if (PrevDecl) { 11805 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 11806 } else { 11807 (void)WeakUndeclaredIdentifiers.insert( 11808 std::pair<IdentifierInfo*,WeakInfo> 11809 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 11810 } 11811} 11812 11813void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 11814 IdentifierInfo* AliasName, 11815 SourceLocation PragmaLoc, 11816 SourceLocation NameLoc, 11817 SourceLocation AliasNameLoc) { 11818 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 11819 LookupOrdinaryName); 11820 WeakInfo W = WeakInfo(Name, NameLoc); 11821 11822 if (PrevDecl) { 11823 if (!PrevDecl->hasAttr<AliasAttr>()) 11824 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 11825 DeclApplyPragmaWeak(TUScope, ND, W); 11826 } else { 11827 (void)WeakUndeclaredIdentifiers.insert( 11828 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 11829 } 11830} 11831 11832Decl *Sema::getObjCDeclContext() const { 11833 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 11834} 11835 11836AvailabilityResult Sema::getCurContextAvailability() const { 11837 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 11838 return D->getAvailability(); 11839} 11840