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> 47 using namespace clang; 48 using namespace sema; 49 50 Sema::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 59 namespace { 60 61 class 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. 86 bool 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. 132 ParsedType 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. 354 DeclSpec::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 387 bool 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 401 bool 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 502 static 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 517 static 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. 572 static 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 586 Sema::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 618 Corrected: 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. 885 DeclContext *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 912 void 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 919 void 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 /// 929 void 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 958 void 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 972 void 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 1000 void 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. 1018 static 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. 1031 void 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 1092 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1093 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1094 TUScope->AddDecl(D); 1095 } 1096 1097 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 1098 bool ExplicitInstantiationOrSpecialization) { 1099 return IdResolver.isDeclInScope(D, Ctx, S, 1100 ExplicitInstantiationOrSpecialization); 1101 } 1102 1103 Scope *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 1114 static 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. 1120 void 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 1141 static 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. 1148 static 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 1164 static 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. 1189 bool 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 1202 bool 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 1254 void 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 1274 static 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 1335 static 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). 1350 void 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 1368 static 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 1376 void 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 1404 void Sema::ActOnStartFunctionDeclarator() { 1405 ++InFunctionDeclarator; 1406 } 1407 1408 void 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. 1426 ObjCInterfaceDecl *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. 1480 Scope *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. 1493 static 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. 1511 NamedDecl *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. 1597 static 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 1627 bool 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 /// 1666 void 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. 1801 static bool 1802 DeclHasAttr(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 1847 static 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. 1859 static 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 1970 static 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 2015 static 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 2028 static 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. 2040 static 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. 2089 void 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. 2140 static 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 2185 namespace { 2186 2187 /// Used in MergeFunctionDecl to keep track of function parameters in 2188 /// C. 2189 struct GNUCompatibleParamWarning { 2190 ParmVarDecl *OldParm; 2191 ParmVarDecl *NewParm; 2192 QualType PromotedType; 2193 }; 2194 2195 } 2196 2197 /// getSpecialMember - get the special member enum for a method. 2198 Sema::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. 2222 static 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? 2232 static 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 2243 template <typename T> 2244 static 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. 2270 bool 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 2714 bool 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 2752 void 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. 2776 void 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 /// 2834 void 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. 2981 Decl *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 accepts template 2988 /// parameters to cope with template friend declarations. 2989 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 2990 DeclSpec &DS, 2991 MultiTemplateParamsArg TemplateParams, 2992 bool IsExplicitInstantiation) { 2993 Decl *TagD = 0; 2994 TagDecl *Tag = 0; 2995 if (DS.getTypeSpecType() == DeclSpec::TST_class || 2996 DS.getTypeSpecType() == DeclSpec::TST_struct || 2997 DS.getTypeSpecType() == DeclSpec::TST_interface || 2998 DS.getTypeSpecType() == DeclSpec::TST_union || 2999 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3000 TagD = DS.getRepAsDecl(); 3001 3002 if (!TagD) // We probably had an error 3003 return 0; 3004 3005 // Note that the above type specs guarantee that the 3006 // type rep is a Decl, whereas in many of the others 3007 // it's a Type. 3008 if (isa<TagDecl>(TagD)) 3009 Tag = cast<TagDecl>(TagD); 3010 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3011 Tag = CTD->getTemplatedDecl(); 3012 } 3013 3014 if (Tag) { 3015 getASTContext().addUnnamedTag(Tag); 3016 Tag->setFreeStanding(); 3017 if (Tag->isInvalidDecl()) 3018 return Tag; 3019 } 3020 3021 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3022 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3023 // or incomplete types shall not be restrict-qualified." 3024 if (TypeQuals & DeclSpec::TQ_restrict) 3025 Diag(DS.getRestrictSpecLoc(), 3026 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3027 << DS.getSourceRange(); 3028 } 3029 3030 if (DS.isConstexprSpecified()) { 3031 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3032 // and definitions of functions and variables. 3033 if (Tag) 3034 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3035 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3036 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3037 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3038 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3039 else 3040 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3041 // Don't emit warnings after this error. 3042 return TagD; 3043 } 3044 3045 DiagnoseFunctionSpecifiers(DS); 3046 3047 if (DS.isFriendSpecified()) { 3048 // If we're dealing with a decl but not a TagDecl, assume that 3049 // whatever routines created it handled the friendship aspect. 3050 if (TagD && !Tag) 3051 return 0; 3052 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3053 } 3054 3055 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3056 bool IsExplicitSpecialization = 3057 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3058 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3059 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3060 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3061 // nested-name-specifier unless it is an explicit instantiation 3062 // or an explicit specialization. 3063 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3064 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3065 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3066 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3067 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3068 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3069 << SS.getRange(); 3070 return 0; 3071 } 3072 3073 // Track whether this decl-specifier declares anything. 3074 bool DeclaresAnything = true; 3075 3076 // Handle anonymous struct definitions. 3077 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3078 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3079 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3080 if (getLangOpts().CPlusPlus || 3081 Record->getDeclContext()->isRecord()) 3082 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 3083 3084 DeclaresAnything = false; 3085 } 3086 } 3087 3088 // Check for Microsoft C extension: anonymous struct member. 3089 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3090 CurContext->isRecord() && 3091 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3092 // Handle 2 kinds of anonymous struct: 3093 // struct STRUCT; 3094 // and 3095 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3096 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3097 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3098 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3099 DS.getRepAsType().get()->isStructureType())) { 3100 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3101 << DS.getSourceRange(); 3102 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3103 } 3104 } 3105 3106 // Skip all the checks below if we have a type error. 3107 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3108 (TagD && TagD->isInvalidDecl())) 3109 return TagD; 3110 3111 if (getLangOpts().CPlusPlus && 3112 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3113 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3114 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3115 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3116 DeclaresAnything = false; 3117 3118 if (!DS.isMissingDeclaratorOk()) { 3119 // Customize diagnostic for a typedef missing a name. 3120 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3121 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3122 << DS.getSourceRange(); 3123 else 3124 DeclaresAnything = false; 3125 } 3126 3127 if (DS.isModulePrivateSpecified() && 3128 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3129 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3130 << Tag->getTagKind() 3131 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3132 3133 ActOnDocumentableDecl(TagD); 3134 3135 // C 6.7/2: 3136 // A declaration [...] shall declare at least a declarator [...], a tag, 3137 // or the members of an enumeration. 3138 // C++ [dcl.dcl]p3: 3139 // [If there are no declarators], and except for the declaration of an 3140 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3141 // names into the program, or shall redeclare a name introduced by a 3142 // previous declaration. 3143 if (!DeclaresAnything) { 3144 // In C, we allow this as a (popular) extension / bug. Don't bother 3145 // producing further diagnostics for redundant qualifiers after this. 3146 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3147 return TagD; 3148 } 3149 3150 // C++ [dcl.stc]p1: 3151 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3152 // init-declarator-list of the declaration shall not be empty. 3153 // C++ [dcl.fct.spec]p1: 3154 // If a cv-qualifier appears in a decl-specifier-seq, the 3155 // init-declarator-list of the declaration shall not be empty. 3156 // 3157 // Spurious qualifiers here appear to be valid in C. 3158 unsigned DiagID = diag::warn_standalone_specifier; 3159 if (getLangOpts().CPlusPlus) 3160 DiagID = diag::ext_standalone_specifier; 3161 3162 // Note that a linkage-specification sets a storage class, but 3163 // 'extern "C" struct foo;' is actually valid and not theoretically 3164 // useless. 3165 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3166 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3167 Diag(DS.getStorageClassSpecLoc(), DiagID) 3168 << DeclSpec::getSpecifierName(SCS); 3169 3170 if (DS.isThreadSpecified()) 3171 Diag(DS.getThreadSpecLoc(), DiagID) << "__thread"; 3172 if (DS.getTypeQualifiers()) { 3173 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3174 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3175 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3176 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3177 // Restrict is covered above. 3178 } 3179 3180 // Warn about ignored type attributes, for example: 3181 // __attribute__((aligned)) struct A; 3182 // Attributes should be placed after tag to apply to type declaration. 3183 if (!DS.getAttributes().empty()) { 3184 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3185 if (TypeSpecType == DeclSpec::TST_class || 3186 TypeSpecType == DeclSpec::TST_struct || 3187 TypeSpecType == DeclSpec::TST_interface || 3188 TypeSpecType == DeclSpec::TST_union || 3189 TypeSpecType == DeclSpec::TST_enum) { 3190 AttributeList* attrs = DS.getAttributes().getList(); 3191 while (attrs) { 3192 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3193 << attrs->getName() 3194 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3195 TypeSpecType == DeclSpec::TST_struct ? 1 : 3196 TypeSpecType == DeclSpec::TST_union ? 2 : 3197 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3198 attrs = attrs->getNext(); 3199 } 3200 } 3201 } 3202 3203 return TagD; 3204 } 3205 3206 /// We are trying to inject an anonymous member into the given scope; 3207 /// check if there's an existing declaration that can't be overloaded. 3208 /// 3209 /// \return true if this is a forbidden redeclaration 3210 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3211 Scope *S, 3212 DeclContext *Owner, 3213 DeclarationName Name, 3214 SourceLocation NameLoc, 3215 unsigned diagnostic) { 3216 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3217 Sema::ForRedeclaration); 3218 if (!SemaRef.LookupName(R, S)) return false; 3219 3220 if (R.getAsSingle<TagDecl>()) 3221 return false; 3222 3223 // Pick a representative declaration. 3224 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3225 assert(PrevDecl && "Expected a non-null Decl"); 3226 3227 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3228 return false; 3229 3230 SemaRef.Diag(NameLoc, diagnostic) << Name; 3231 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3232 3233 return true; 3234 } 3235 3236 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3237 /// anonymous struct or union AnonRecord into the owning context Owner 3238 /// and scope S. This routine will be invoked just after we realize 3239 /// that an unnamed union or struct is actually an anonymous union or 3240 /// struct, e.g., 3241 /// 3242 /// @code 3243 /// union { 3244 /// int i; 3245 /// float f; 3246 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3247 /// // f into the surrounding scope.x 3248 /// @endcode 3249 /// 3250 /// This routine is recursive, injecting the names of nested anonymous 3251 /// structs/unions into the owning context and scope as well. 3252 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3253 DeclContext *Owner, 3254 RecordDecl *AnonRecord, 3255 AccessSpecifier AS, 3256 SmallVector<NamedDecl*, 2> &Chaining, 3257 bool MSAnonStruct) { 3258 unsigned diagKind 3259 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3260 : diag::err_anonymous_struct_member_redecl; 3261 3262 bool Invalid = false; 3263 3264 // Look every FieldDecl and IndirectFieldDecl with a name. 3265 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 3266 DEnd = AnonRecord->decls_end(); 3267 D != DEnd; ++D) { 3268 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 3269 cast<NamedDecl>(*D)->getDeclName()) { 3270 ValueDecl *VD = cast<ValueDecl>(*D); 3271 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3272 VD->getLocation(), diagKind)) { 3273 // C++ [class.union]p2: 3274 // The names of the members of an anonymous union shall be 3275 // distinct from the names of any other entity in the 3276 // scope in which the anonymous union is declared. 3277 Invalid = true; 3278 } else { 3279 // C++ [class.union]p2: 3280 // For the purpose of name lookup, after the anonymous union 3281 // definition, the members of the anonymous union are 3282 // considered to have been defined in the scope in which the 3283 // anonymous union is declared. 3284 unsigned OldChainingSize = Chaining.size(); 3285 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3286 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 3287 PE = IF->chain_end(); PI != PE; ++PI) 3288 Chaining.push_back(*PI); 3289 else 3290 Chaining.push_back(VD); 3291 3292 assert(Chaining.size() >= 2); 3293 NamedDecl **NamedChain = 3294 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3295 for (unsigned i = 0; i < Chaining.size(); i++) 3296 NamedChain[i] = Chaining[i]; 3297 3298 IndirectFieldDecl* IndirectField = 3299 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3300 VD->getIdentifier(), VD->getType(), 3301 NamedChain, Chaining.size()); 3302 3303 IndirectField->setAccess(AS); 3304 IndirectField->setImplicit(); 3305 SemaRef.PushOnScopeChains(IndirectField, S); 3306 3307 // That includes picking up the appropriate access specifier. 3308 if (AS != AS_none) IndirectField->setAccess(AS); 3309 3310 Chaining.resize(OldChainingSize); 3311 } 3312 } 3313 } 3314 3315 return Invalid; 3316 } 3317 3318 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3319 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3320 /// illegal input values are mapped to SC_None. 3321 static StorageClass 3322 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3323 switch (StorageClassSpec) { 3324 case DeclSpec::SCS_unspecified: return SC_None; 3325 case DeclSpec::SCS_extern: return SC_Extern; 3326 case DeclSpec::SCS_static: return SC_Static; 3327 case DeclSpec::SCS_auto: return SC_Auto; 3328 case DeclSpec::SCS_register: return SC_Register; 3329 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3330 // Illegal SCSs map to None: error reporting is up to the caller. 3331 case DeclSpec::SCS_mutable: // Fall through. 3332 case DeclSpec::SCS_typedef: return SC_None; 3333 } 3334 llvm_unreachable("unknown storage class specifier"); 3335 } 3336 3337 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 3338 /// a StorageClass. Any error reporting is up to the caller: 3339 /// illegal input values are mapped to SC_None. 3340 static StorageClass 3341 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 3342 switch (StorageClassSpec) { 3343 case DeclSpec::SCS_unspecified: return SC_None; 3344 case DeclSpec::SCS_extern: return SC_Extern; 3345 case DeclSpec::SCS_static: return SC_Static; 3346 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3347 // Illegal SCSs map to None: error reporting is up to the caller. 3348 case DeclSpec::SCS_auto: // Fall through. 3349 case DeclSpec::SCS_mutable: // Fall through. 3350 case DeclSpec::SCS_register: // Fall through. 3351 case DeclSpec::SCS_typedef: return SC_None; 3352 } 3353 llvm_unreachable("unknown storage class specifier"); 3354 } 3355 3356 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3357 /// anonymous structure or union. Anonymous unions are a C++ feature 3358 /// (C++ [class.union]) and a C11 feature; anonymous structures 3359 /// are a C11 feature and GNU C++ extension. 3360 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3361 AccessSpecifier AS, 3362 RecordDecl *Record) { 3363 DeclContext *Owner = Record->getDeclContext(); 3364 3365 // Diagnose whether this anonymous struct/union is an extension. 3366 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3367 Diag(Record->getLocation(), diag::ext_anonymous_union); 3368 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3369 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3370 else if (!Record->isUnion() && !getLangOpts().C11) 3371 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3372 3373 // C and C++ require different kinds of checks for anonymous 3374 // structs/unions. 3375 bool Invalid = false; 3376 if (getLangOpts().CPlusPlus) { 3377 const char* PrevSpec = 0; 3378 unsigned DiagID; 3379 if (Record->isUnion()) { 3380 // C++ [class.union]p6: 3381 // Anonymous unions declared in a named namespace or in the 3382 // global namespace shall be declared static. 3383 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3384 (isa<TranslationUnitDecl>(Owner) || 3385 (isa<NamespaceDecl>(Owner) && 3386 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3387 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3388 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3389 3390 // Recover by adding 'static'. 3391 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3392 PrevSpec, DiagID); 3393 } 3394 // C++ [class.union]p6: 3395 // A storage class is not allowed in a declaration of an 3396 // anonymous union in a class scope. 3397 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3398 isa<RecordDecl>(Owner)) { 3399 Diag(DS.getStorageClassSpecLoc(), 3400 diag::err_anonymous_union_with_storage_spec) 3401 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3402 3403 // Recover by removing the storage specifier. 3404 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3405 SourceLocation(), 3406 PrevSpec, DiagID); 3407 } 3408 } 3409 3410 // Ignore const/volatile/restrict qualifiers. 3411 if (DS.getTypeQualifiers()) { 3412 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3413 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3414 << Record->isUnion() << 0 3415 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3416 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3417 Diag(DS.getVolatileSpecLoc(), 3418 diag::ext_anonymous_struct_union_qualified) 3419 << Record->isUnion() << 1 3420 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3421 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3422 Diag(DS.getRestrictSpecLoc(), 3423 diag::ext_anonymous_struct_union_qualified) 3424 << Record->isUnion() << 2 3425 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3426 3427 DS.ClearTypeQualifiers(); 3428 } 3429 3430 // C++ [class.union]p2: 3431 // The member-specification of an anonymous union shall only 3432 // define non-static data members. [Note: nested types and 3433 // functions cannot be declared within an anonymous union. ] 3434 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 3435 MemEnd = Record->decls_end(); 3436 Mem != MemEnd; ++Mem) { 3437 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 3438 // C++ [class.union]p3: 3439 // An anonymous union shall not have private or protected 3440 // members (clause 11). 3441 assert(FD->getAccess() != AS_none); 3442 if (FD->getAccess() != AS_public) { 3443 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3444 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3445 Invalid = true; 3446 } 3447 3448 // C++ [class.union]p1 3449 // An object of a class with a non-trivial constructor, a non-trivial 3450 // copy constructor, a non-trivial destructor, or a non-trivial copy 3451 // assignment operator cannot be a member of a union, nor can an 3452 // array of such objects. 3453 if (CheckNontrivialField(FD)) 3454 Invalid = true; 3455 } else if ((*Mem)->isImplicit()) { 3456 // Any implicit members are fine. 3457 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 3458 // This is a type that showed up in an 3459 // elaborated-type-specifier inside the anonymous struct or 3460 // union, but which actually declares a type outside of the 3461 // anonymous struct or union. It's okay. 3462 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 3463 if (!MemRecord->isAnonymousStructOrUnion() && 3464 MemRecord->getDeclName()) { 3465 // Visual C++ allows type definition in anonymous struct or union. 3466 if (getLangOpts().MicrosoftExt) 3467 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3468 << (int)Record->isUnion(); 3469 else { 3470 // This is a nested type declaration. 3471 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3472 << (int)Record->isUnion(); 3473 Invalid = true; 3474 } 3475 } else { 3476 // This is an anonymous type definition within another anonymous type. 3477 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3478 // not part of standard C++. 3479 Diag(MemRecord->getLocation(), 3480 diag::ext_anonymous_record_with_anonymous_type) 3481 << (int)Record->isUnion(); 3482 } 3483 } else if (isa<AccessSpecDecl>(*Mem)) { 3484 // Any access specifier is fine. 3485 } else { 3486 // We have something that isn't a non-static data 3487 // member. Complain about it. 3488 unsigned DK = diag::err_anonymous_record_bad_member; 3489 if (isa<TypeDecl>(*Mem)) 3490 DK = diag::err_anonymous_record_with_type; 3491 else if (isa<FunctionDecl>(*Mem)) 3492 DK = diag::err_anonymous_record_with_function; 3493 else if (isa<VarDecl>(*Mem)) 3494 DK = diag::err_anonymous_record_with_static; 3495 3496 // Visual C++ allows type definition in anonymous struct or union. 3497 if (getLangOpts().MicrosoftExt && 3498 DK == diag::err_anonymous_record_with_type) 3499 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 3500 << (int)Record->isUnion(); 3501 else { 3502 Diag((*Mem)->getLocation(), DK) 3503 << (int)Record->isUnion(); 3504 Invalid = true; 3505 } 3506 } 3507 } 3508 } 3509 3510 if (!Record->isUnion() && !Owner->isRecord()) { 3511 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3512 << (int)getLangOpts().CPlusPlus; 3513 Invalid = true; 3514 } 3515 3516 // Mock up a declarator. 3517 Declarator Dc(DS, Declarator::MemberContext); 3518 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3519 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3520 3521 // Create a declaration for this anonymous struct/union. 3522 NamedDecl *Anon = 0; 3523 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3524 Anon = FieldDecl::Create(Context, OwningClass, 3525 DS.getLocStart(), 3526 Record->getLocation(), 3527 /*IdentifierInfo=*/0, 3528 Context.getTypeDeclType(Record), 3529 TInfo, 3530 /*BitWidth=*/0, /*Mutable=*/false, 3531 /*InitStyle=*/ICIS_NoInit); 3532 Anon->setAccess(AS); 3533 if (getLangOpts().CPlusPlus) 3534 FieldCollector->Add(cast<FieldDecl>(Anon)); 3535 } else { 3536 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3537 assert(SCSpec != DeclSpec::SCS_typedef && 3538 "Parser allowed 'typedef' as storage class VarDecl."); 3539 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 3540 if (SCSpec == DeclSpec::SCS_mutable) { 3541 // mutable can only appear on non-static class members, so it's always 3542 // an error here 3543 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3544 Invalid = true; 3545 SC = SC_None; 3546 } 3547 SCSpec = DS.getStorageClassSpecAsWritten(); 3548 VarDecl::StorageClass SCAsWritten 3549 = StorageClassSpecToVarDeclStorageClass(SCSpec); 3550 3551 Anon = VarDecl::Create(Context, Owner, 3552 DS.getLocStart(), 3553 Record->getLocation(), /*IdentifierInfo=*/0, 3554 Context.getTypeDeclType(Record), 3555 TInfo, SC, SCAsWritten); 3556 3557 // Default-initialize the implicit variable. This initialization will be 3558 // trivial in almost all cases, except if a union member has an in-class 3559 // initializer: 3560 // union { int n = 0; }; 3561 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3562 } 3563 Anon->setImplicit(); 3564 3565 // Add the anonymous struct/union object to the current 3566 // context. We'll be referencing this object when we refer to one of 3567 // its members. 3568 Owner->addDecl(Anon); 3569 3570 // Inject the members of the anonymous struct/union into the owning 3571 // context and into the identifier resolver chain for name lookup 3572 // purposes. 3573 SmallVector<NamedDecl*, 2> Chain; 3574 Chain.push_back(Anon); 3575 3576 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3577 Chain, false)) 3578 Invalid = true; 3579 3580 // Mark this as an anonymous struct/union type. Note that we do not 3581 // do this until after we have already checked and injected the 3582 // members of this anonymous struct/union type, because otherwise 3583 // the members could be injected twice: once by DeclContext when it 3584 // builds its lookup table, and once by 3585 // InjectAnonymousStructOrUnionMembers. 3586 Record->setAnonymousStructOrUnion(true); 3587 3588 if (Invalid) 3589 Anon->setInvalidDecl(); 3590 3591 return Anon; 3592 } 3593 3594 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3595 /// Microsoft C anonymous structure. 3596 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3597 /// Example: 3598 /// 3599 /// struct A { int a; }; 3600 /// struct B { struct A; int b; }; 3601 /// 3602 /// void foo() { 3603 /// B var; 3604 /// var.a = 3; 3605 /// } 3606 /// 3607 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3608 RecordDecl *Record) { 3609 3610 // If there is no Record, get the record via the typedef. 3611 if (!Record) 3612 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3613 3614 // Mock up a declarator. 3615 Declarator Dc(DS, Declarator::TypeNameContext); 3616 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3617 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3618 3619 // Create a declaration for this anonymous struct. 3620 NamedDecl* Anon = FieldDecl::Create(Context, 3621 cast<RecordDecl>(CurContext), 3622 DS.getLocStart(), 3623 DS.getLocStart(), 3624 /*IdentifierInfo=*/0, 3625 Context.getTypeDeclType(Record), 3626 TInfo, 3627 /*BitWidth=*/0, /*Mutable=*/false, 3628 /*InitStyle=*/ICIS_NoInit); 3629 Anon->setImplicit(); 3630 3631 // Add the anonymous struct object to the current context. 3632 CurContext->addDecl(Anon); 3633 3634 // Inject the members of the anonymous struct into the current 3635 // context and into the identifier resolver chain for name lookup 3636 // purposes. 3637 SmallVector<NamedDecl*, 2> Chain; 3638 Chain.push_back(Anon); 3639 3640 RecordDecl *RecordDef = Record->getDefinition(); 3641 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3642 RecordDef, AS_none, 3643 Chain, true)) 3644 Anon->setInvalidDecl(); 3645 3646 return Anon; 3647 } 3648 3649 /// GetNameForDeclarator - Determine the full declaration name for the 3650 /// given Declarator. 3651 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3652 return GetNameFromUnqualifiedId(D.getName()); 3653 } 3654 3655 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3656 DeclarationNameInfo 3657 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3658 DeclarationNameInfo NameInfo; 3659 NameInfo.setLoc(Name.StartLocation); 3660 3661 switch (Name.getKind()) { 3662 3663 case UnqualifiedId::IK_ImplicitSelfParam: 3664 case UnqualifiedId::IK_Identifier: 3665 NameInfo.setName(Name.Identifier); 3666 NameInfo.setLoc(Name.StartLocation); 3667 return NameInfo; 3668 3669 case UnqualifiedId::IK_OperatorFunctionId: 3670 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3671 Name.OperatorFunctionId.Operator)); 3672 NameInfo.setLoc(Name.StartLocation); 3673 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3674 = Name.OperatorFunctionId.SymbolLocations[0]; 3675 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3676 = Name.EndLocation.getRawEncoding(); 3677 return NameInfo; 3678 3679 case UnqualifiedId::IK_LiteralOperatorId: 3680 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3681 Name.Identifier)); 3682 NameInfo.setLoc(Name.StartLocation); 3683 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3684 return NameInfo; 3685 3686 case UnqualifiedId::IK_ConversionFunctionId: { 3687 TypeSourceInfo *TInfo; 3688 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3689 if (Ty.isNull()) 3690 return DeclarationNameInfo(); 3691 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3692 Context.getCanonicalType(Ty))); 3693 NameInfo.setLoc(Name.StartLocation); 3694 NameInfo.setNamedTypeInfo(TInfo); 3695 return NameInfo; 3696 } 3697 3698 case UnqualifiedId::IK_ConstructorName: { 3699 TypeSourceInfo *TInfo; 3700 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3701 if (Ty.isNull()) 3702 return DeclarationNameInfo(); 3703 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3704 Context.getCanonicalType(Ty))); 3705 NameInfo.setLoc(Name.StartLocation); 3706 NameInfo.setNamedTypeInfo(TInfo); 3707 return NameInfo; 3708 } 3709 3710 case UnqualifiedId::IK_ConstructorTemplateId: { 3711 // In well-formed code, we can only have a constructor 3712 // template-id that refers to the current context, so go there 3713 // to find the actual type being constructed. 3714 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3715 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3716 return DeclarationNameInfo(); 3717 3718 // Determine the type of the class being constructed. 3719 QualType CurClassType = Context.getTypeDeclType(CurClass); 3720 3721 // FIXME: Check two things: that the template-id names the same type as 3722 // CurClassType, and that the template-id does not occur when the name 3723 // was qualified. 3724 3725 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3726 Context.getCanonicalType(CurClassType))); 3727 NameInfo.setLoc(Name.StartLocation); 3728 // FIXME: should we retrieve TypeSourceInfo? 3729 NameInfo.setNamedTypeInfo(0); 3730 return NameInfo; 3731 } 3732 3733 case UnqualifiedId::IK_DestructorName: { 3734 TypeSourceInfo *TInfo; 3735 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3736 if (Ty.isNull()) 3737 return DeclarationNameInfo(); 3738 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3739 Context.getCanonicalType(Ty))); 3740 NameInfo.setLoc(Name.StartLocation); 3741 NameInfo.setNamedTypeInfo(TInfo); 3742 return NameInfo; 3743 } 3744 3745 case UnqualifiedId::IK_TemplateId: { 3746 TemplateName TName = Name.TemplateId->Template.get(); 3747 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3748 return Context.getNameForTemplate(TName, TNameLoc); 3749 } 3750 3751 } // switch (Name.getKind()) 3752 3753 llvm_unreachable("Unknown name kind"); 3754 } 3755 3756 static QualType getCoreType(QualType Ty) { 3757 do { 3758 if (Ty->isPointerType() || Ty->isReferenceType()) 3759 Ty = Ty->getPointeeType(); 3760 else if (Ty->isArrayType()) 3761 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3762 else 3763 return Ty.withoutLocalFastQualifiers(); 3764 } while (true); 3765 } 3766 3767 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3768 /// and Definition have "nearly" matching parameters. This heuristic is 3769 /// used to improve diagnostics in the case where an out-of-line function 3770 /// definition doesn't match any declaration within the class or namespace. 3771 /// Also sets Params to the list of indices to the parameters that differ 3772 /// between the declaration and the definition. If hasSimilarParameters 3773 /// returns true and Params is empty, then all of the parameters match. 3774 static bool hasSimilarParameters(ASTContext &Context, 3775 FunctionDecl *Declaration, 3776 FunctionDecl *Definition, 3777 SmallVectorImpl<unsigned> &Params) { 3778 Params.clear(); 3779 if (Declaration->param_size() != Definition->param_size()) 3780 return false; 3781 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3782 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3783 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3784 3785 // The parameter types are identical 3786 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3787 continue; 3788 3789 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 3790 QualType DefParamBaseTy = getCoreType(DefParamTy); 3791 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 3792 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 3793 3794 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 3795 (DeclTyName && DeclTyName == DefTyName)) 3796 Params.push_back(Idx); 3797 else // The two parameters aren't even close 3798 return false; 3799 } 3800 3801 return true; 3802 } 3803 3804 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 3805 /// declarator needs to be rebuilt in the current instantiation. 3806 /// Any bits of declarator which appear before the name are valid for 3807 /// consideration here. That's specifically the type in the decl spec 3808 /// and the base type in any member-pointer chunks. 3809 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 3810 DeclarationName Name) { 3811 // The types we specifically need to rebuild are: 3812 // - typenames, typeofs, and decltypes 3813 // - types which will become injected class names 3814 // Of course, we also need to rebuild any type referencing such a 3815 // type. It's safest to just say "dependent", but we call out a 3816 // few cases here. 3817 3818 DeclSpec &DS = D.getMutableDeclSpec(); 3819 switch (DS.getTypeSpecType()) { 3820 case DeclSpec::TST_typename: 3821 case DeclSpec::TST_typeofType: 3822 case DeclSpec::TST_underlyingType: 3823 case DeclSpec::TST_atomic: { 3824 // Grab the type from the parser. 3825 TypeSourceInfo *TSI = 0; 3826 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 3827 if (T.isNull() || !T->isDependentType()) break; 3828 3829 // Make sure there's a type source info. This isn't really much 3830 // of a waste; most dependent types should have type source info 3831 // attached already. 3832 if (!TSI) 3833 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 3834 3835 // Rebuild the type in the current instantiation. 3836 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 3837 if (!TSI) return true; 3838 3839 // Store the new type back in the decl spec. 3840 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 3841 DS.UpdateTypeRep(LocType); 3842 break; 3843 } 3844 3845 case DeclSpec::TST_decltype: 3846 case DeclSpec::TST_typeofExpr: { 3847 Expr *E = DS.getRepAsExpr(); 3848 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 3849 if (Result.isInvalid()) return true; 3850 DS.UpdateExprRep(Result.get()); 3851 break; 3852 } 3853 3854 default: 3855 // Nothing to do for these decl specs. 3856 break; 3857 } 3858 3859 // It doesn't matter what order we do this in. 3860 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 3861 DeclaratorChunk &Chunk = D.getTypeObject(I); 3862 3863 // The only type information in the declarator which can come 3864 // before the declaration name is the base type of a member 3865 // pointer. 3866 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 3867 continue; 3868 3869 // Rebuild the scope specifier in-place. 3870 CXXScopeSpec &SS = Chunk.Mem.Scope(); 3871 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 3872 return true; 3873 } 3874 3875 return false; 3876 } 3877 3878 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 3879 D.setFunctionDefinitionKind(FDK_Declaration); 3880 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 3881 3882 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 3883 Dcl && Dcl->getDeclContext()->isFileContext()) 3884 Dcl->setTopLevelDeclInObjCContainer(); 3885 3886 return Dcl; 3887 } 3888 3889 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 3890 /// If T is the name of a class, then each of the following shall have a 3891 /// name different from T: 3892 /// - every static data member of class T; 3893 /// - every member function of class T 3894 /// - every member of class T that is itself a type; 3895 /// \returns true if the declaration name violates these rules. 3896 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 3897 DeclarationNameInfo NameInfo) { 3898 DeclarationName Name = NameInfo.getName(); 3899 3900 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 3901 if (Record->getIdentifier() && Record->getDeclName() == Name) { 3902 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 3903 return true; 3904 } 3905 3906 return false; 3907 } 3908 3909 /// \brief Diagnose a declaration whose declarator-id has the given 3910 /// nested-name-specifier. 3911 /// 3912 /// \param SS The nested-name-specifier of the declarator-id. 3913 /// 3914 /// \param DC The declaration context to which the nested-name-specifier 3915 /// resolves. 3916 /// 3917 /// \param Name The name of the entity being declared. 3918 /// 3919 /// \param Loc The location of the name of the entity being declared. 3920 /// 3921 /// \returns true if we cannot safely recover from this error, false otherwise. 3922 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 3923 DeclarationName Name, 3924 SourceLocation Loc) { 3925 DeclContext *Cur = CurContext; 3926 while (isa<LinkageSpecDecl>(Cur)) 3927 Cur = Cur->getParent(); 3928 3929 // C++ [dcl.meaning]p1: 3930 // A declarator-id shall not be qualified except for the definition 3931 // of a member function (9.3) or static data member (9.4) outside of 3932 // its class, the definition or explicit instantiation of a function 3933 // or variable member of a namespace outside of its namespace, or the 3934 // definition of an explicit specialization outside of its namespace, 3935 // or the declaration of a friend function that is a member of 3936 // another class or namespace (11.3). [...] 3937 3938 // The user provided a superfluous scope specifier that refers back to the 3939 // class or namespaces in which the entity is already declared. 3940 // 3941 // class X { 3942 // void X::f(); 3943 // }; 3944 if (Cur->Equals(DC)) { 3945 Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification 3946 : diag::err_member_extra_qualification) 3947 << Name << FixItHint::CreateRemoval(SS.getRange()); 3948 SS.clear(); 3949 return false; 3950 } 3951 3952 // Check whether the qualifying scope encloses the scope of the original 3953 // declaration. 3954 if (!Cur->Encloses(DC)) { 3955 if (Cur->isRecord()) 3956 Diag(Loc, diag::err_member_qualification) 3957 << Name << SS.getRange(); 3958 else if (isa<TranslationUnitDecl>(DC)) 3959 Diag(Loc, diag::err_invalid_declarator_global_scope) 3960 << Name << SS.getRange(); 3961 else if (isa<FunctionDecl>(Cur)) 3962 Diag(Loc, diag::err_invalid_declarator_in_function) 3963 << Name << SS.getRange(); 3964 else 3965 Diag(Loc, diag::err_invalid_declarator_scope) 3966 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 3967 3968 return true; 3969 } 3970 3971 if (Cur->isRecord()) { 3972 // Cannot qualify members within a class. 3973 Diag(Loc, diag::err_member_qualification) 3974 << Name << SS.getRange(); 3975 SS.clear(); 3976 3977 // C++ constructors and destructors with incorrect scopes can break 3978 // our AST invariants by having the wrong underlying types. If 3979 // that's the case, then drop this declaration entirely. 3980 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 3981 Name.getNameKind() == DeclarationName::CXXDestructorName) && 3982 !Context.hasSameType(Name.getCXXNameType(), 3983 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 3984 return true; 3985 3986 return false; 3987 } 3988 3989 // C++11 [dcl.meaning]p1: 3990 // [...] "The nested-name-specifier of the qualified declarator-id shall 3991 // not begin with a decltype-specifer" 3992 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 3993 while (SpecLoc.getPrefix()) 3994 SpecLoc = SpecLoc.getPrefix(); 3995 if (dyn_cast_or_null<DecltypeType>( 3996 SpecLoc.getNestedNameSpecifier()->getAsType())) 3997 Diag(Loc, diag::err_decltype_in_declarator) 3998 << SpecLoc.getTypeLoc().getSourceRange(); 3999 4000 return false; 4001 } 4002 4003 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4004 MultiTemplateParamsArg TemplateParamLists) { 4005 // TODO: consider using NameInfo for diagnostic. 4006 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4007 DeclarationName Name = NameInfo.getName(); 4008 4009 // All of these full declarators require an identifier. If it doesn't have 4010 // one, the ParsedFreeStandingDeclSpec action should be used. 4011 if (!Name) { 4012 if (!D.isInvalidType()) // Reject this if we think it is valid. 4013 Diag(D.getDeclSpec().getLocStart(), 4014 diag::err_declarator_need_ident) 4015 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4016 return 0; 4017 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4018 return 0; 4019 4020 // The scope passed in may not be a decl scope. Zip up the scope tree until 4021 // we find one that is. 4022 while ((S->getFlags() & Scope::DeclScope) == 0 || 4023 (S->getFlags() & Scope::TemplateParamScope) != 0) 4024 S = S->getParent(); 4025 4026 DeclContext *DC = CurContext; 4027 if (D.getCXXScopeSpec().isInvalid()) 4028 D.setInvalidType(); 4029 else if (D.getCXXScopeSpec().isSet()) { 4030 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4031 UPPC_DeclarationQualifier)) 4032 return 0; 4033 4034 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4035 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4036 if (!DC) { 4037 // If we could not compute the declaration context, it's because the 4038 // declaration context is dependent but does not refer to a class, 4039 // class template, or class template partial specialization. Complain 4040 // and return early, to avoid the coming semantic disaster. 4041 Diag(D.getIdentifierLoc(), 4042 diag::err_template_qualified_declarator_no_match) 4043 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 4044 << D.getCXXScopeSpec().getRange(); 4045 return 0; 4046 } 4047 bool IsDependentContext = DC->isDependentContext(); 4048 4049 if (!IsDependentContext && 4050 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4051 return 0; 4052 4053 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4054 Diag(D.getIdentifierLoc(), 4055 diag::err_member_def_undefined_record) 4056 << Name << DC << D.getCXXScopeSpec().getRange(); 4057 D.setInvalidType(); 4058 } else if (!D.getDeclSpec().isFriendSpecified()) { 4059 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4060 Name, D.getIdentifierLoc())) { 4061 if (DC->isRecord()) 4062 return 0; 4063 4064 D.setInvalidType(); 4065 } 4066 } 4067 4068 // Check whether we need to rebuild the type of the given 4069 // declaration in the current instantiation. 4070 if (EnteringContext && IsDependentContext && 4071 TemplateParamLists.size() != 0) { 4072 ContextRAII SavedContext(*this, DC); 4073 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4074 D.setInvalidType(); 4075 } 4076 } 4077 4078 if (DiagnoseClassNameShadow(DC, NameInfo)) 4079 // If this is a typedef, we'll end up spewing multiple diagnostics. 4080 // Just return early; it's safer. 4081 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4082 return 0; 4083 4084 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4085 QualType R = TInfo->getType(); 4086 4087 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4088 UPPC_DeclarationType)) 4089 D.setInvalidType(); 4090 4091 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4092 ForRedeclaration); 4093 4094 // See if this is a redefinition of a variable in the same scope. 4095 if (!D.getCXXScopeSpec().isSet()) { 4096 bool IsLinkageLookup = false; 4097 4098 // If the declaration we're planning to build will be a function 4099 // or object with linkage, then look for another declaration with 4100 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4101 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4102 /* Do nothing*/; 4103 else if (R->isFunctionType()) { 4104 if (CurContext->isFunctionOrMethod() || 4105 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4106 IsLinkageLookup = true; 4107 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 4108 IsLinkageLookup = true; 4109 else if (CurContext->getRedeclContext()->isTranslationUnit() && 4110 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4111 IsLinkageLookup = true; 4112 4113 if (IsLinkageLookup) 4114 Previous.clear(LookupRedeclarationWithLinkage); 4115 4116 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 4117 } else { // Something like "int foo::x;" 4118 LookupQualifiedName(Previous, DC); 4119 4120 // C++ [dcl.meaning]p1: 4121 // When the declarator-id is qualified, the declaration shall refer to a 4122 // previously declared member of the class or namespace to which the 4123 // qualifier refers (or, in the case of a namespace, of an element of the 4124 // inline namespace set of that namespace (7.3.1)) or to a specialization 4125 // thereof; [...] 4126 // 4127 // Note that we already checked the context above, and that we do not have 4128 // enough information to make sure that Previous contains the declaration 4129 // we want to match. For example, given: 4130 // 4131 // class X { 4132 // void f(); 4133 // void f(float); 4134 // }; 4135 // 4136 // void X::f(int) { } // ill-formed 4137 // 4138 // In this case, Previous will point to the overload set 4139 // containing the two f's declared in X, but neither of them 4140 // matches. 4141 4142 // C++ [dcl.meaning]p1: 4143 // [...] the member shall not merely have been introduced by a 4144 // using-declaration in the scope of the class or namespace nominated by 4145 // the nested-name-specifier of the declarator-id. 4146 RemoveUsingDecls(Previous); 4147 } 4148 4149 if (Previous.isSingleResult() && 4150 Previous.getFoundDecl()->isTemplateParameter()) { 4151 // Maybe we will complain about the shadowed template parameter. 4152 if (!D.isInvalidType()) 4153 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4154 Previous.getFoundDecl()); 4155 4156 // Just pretend that we didn't see the previous declaration. 4157 Previous.clear(); 4158 } 4159 4160 // In C++, the previous declaration we find might be a tag type 4161 // (class or enum). In this case, the new declaration will hide the 4162 // tag type. Note that this does does not apply if we're declaring a 4163 // typedef (C++ [dcl.typedef]p4). 4164 if (Previous.isSingleTagDecl() && 4165 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4166 Previous.clear(); 4167 4168 // Check that there are no default arguments other than in the parameters 4169 // of a function declaration (C++ only). 4170 if (getLangOpts().CPlusPlus) 4171 CheckExtraCXXDefaultArguments(D); 4172 4173 NamedDecl *New; 4174 4175 bool AddToScope = true; 4176 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4177 if (TemplateParamLists.size()) { 4178 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4179 return 0; 4180 } 4181 4182 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4183 } else if (R->isFunctionType()) { 4184 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4185 TemplateParamLists, 4186 AddToScope); 4187 } else { 4188 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 4189 TemplateParamLists); 4190 } 4191 4192 if (New == 0) 4193 return 0; 4194 4195 // If this has an identifier and is not an invalid redeclaration or 4196 // function template specialization, add it to the scope stack. 4197 if (New->getDeclName() && AddToScope && 4198 !(D.isRedeclaration() && New->isInvalidDecl())) 4199 PushOnScopeChains(New, S); 4200 4201 return New; 4202 } 4203 4204 /// Helper method to turn variable array types into constant array 4205 /// types in certain situations which would otherwise be errors (for 4206 /// GCC compatibility). 4207 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4208 ASTContext &Context, 4209 bool &SizeIsNegative, 4210 llvm::APSInt &Oversized) { 4211 // This method tries to turn a variable array into a constant 4212 // array even when the size isn't an ICE. This is necessary 4213 // for compatibility with code that depends on gcc's buggy 4214 // constant expression folding, like struct {char x[(int)(char*)2];} 4215 SizeIsNegative = false; 4216 Oversized = 0; 4217 4218 if (T->isDependentType()) 4219 return QualType(); 4220 4221 QualifierCollector Qs; 4222 const Type *Ty = Qs.strip(T); 4223 4224 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4225 QualType Pointee = PTy->getPointeeType(); 4226 QualType FixedType = 4227 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4228 Oversized); 4229 if (FixedType.isNull()) return FixedType; 4230 FixedType = Context.getPointerType(FixedType); 4231 return Qs.apply(Context, FixedType); 4232 } 4233 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4234 QualType Inner = PTy->getInnerType(); 4235 QualType FixedType = 4236 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4237 Oversized); 4238 if (FixedType.isNull()) return FixedType; 4239 FixedType = Context.getParenType(FixedType); 4240 return Qs.apply(Context, FixedType); 4241 } 4242 4243 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4244 if (!VLATy) 4245 return QualType(); 4246 // FIXME: We should probably handle this case 4247 if (VLATy->getElementType()->isVariablyModifiedType()) 4248 return QualType(); 4249 4250 llvm::APSInt Res; 4251 if (!VLATy->getSizeExpr() || 4252 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4253 return QualType(); 4254 4255 // Check whether the array size is negative. 4256 if (Res.isSigned() && Res.isNegative()) { 4257 SizeIsNegative = true; 4258 return QualType(); 4259 } 4260 4261 // Check whether the array is too large to be addressed. 4262 unsigned ActiveSizeBits 4263 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4264 Res); 4265 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4266 Oversized = Res; 4267 return QualType(); 4268 } 4269 4270 return Context.getConstantArrayType(VLATy->getElementType(), 4271 Res, ArrayType::Normal, 0); 4272 } 4273 4274 static void 4275 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4276 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4277 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4278 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4279 DstPTL.getPointeeLoc()); 4280 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4281 return; 4282 } 4283 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4284 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4285 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4286 DstPTL.getInnerLoc()); 4287 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4288 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4289 return; 4290 } 4291 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4292 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4293 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4294 TypeLoc DstElemTL = DstATL.getElementLoc(); 4295 DstElemTL.initializeFullCopy(SrcElemTL); 4296 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4297 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4298 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4299 } 4300 4301 /// Helper method to turn variable array types into constant array 4302 /// types in certain situations which would otherwise be errors (for 4303 /// GCC compatibility). 4304 static TypeSourceInfo* 4305 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4306 ASTContext &Context, 4307 bool &SizeIsNegative, 4308 llvm::APSInt &Oversized) { 4309 QualType FixedTy 4310 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4311 SizeIsNegative, Oversized); 4312 if (FixedTy.isNull()) 4313 return 0; 4314 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4315 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4316 FixedTInfo->getTypeLoc()); 4317 return FixedTInfo; 4318 } 4319 4320 /// \brief Register the given locally-scoped extern "C" declaration so 4321 /// that it can be found later for redeclarations 4322 void 4323 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 4324 const LookupResult &Previous, 4325 Scope *S) { 4326 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 4327 "Decl is not a locally-scoped decl!"); 4328 // Note that we have a locally-scoped external with this name. 4329 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4330 4331 if (!Previous.isSingleResult()) 4332 return; 4333 4334 NamedDecl *PrevDecl = Previous.getFoundDecl(); 4335 4336 // If there was a previous declaration of this entity, it may be in 4337 // our identifier chain. Update the identifier chain with the new 4338 // declaration. 4339 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 4340 // The previous declaration was found on the identifer resolver 4341 // chain, so remove it from its scope. 4342 4343 if (S->isDeclScope(PrevDecl)) { 4344 // Special case for redeclarations in the SAME scope. 4345 // Because this declaration is going to be added to the identifier chain 4346 // later, we should temporarily take it OFF the chain. 4347 IdResolver.RemoveDecl(ND); 4348 4349 } else { 4350 // Find the scope for the original declaration. 4351 while (S && !S->isDeclScope(PrevDecl)) 4352 S = S->getParent(); 4353 } 4354 4355 if (S) 4356 S->RemoveDecl(PrevDecl); 4357 } 4358 } 4359 4360 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 4361 Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4362 if (ExternalSource) { 4363 // Load locally-scoped external decls from the external source. 4364 SmallVector<NamedDecl *, 4> Decls; 4365 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4366 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4367 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4368 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4369 if (Pos == LocallyScopedExternCDecls.end()) 4370 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4371 } 4372 } 4373 4374 return LocallyScopedExternCDecls.find(Name); 4375 } 4376 4377 /// \brief Diagnose function specifiers on a declaration of an identifier that 4378 /// does not identify a function. 4379 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4380 // FIXME: We should probably indicate the identifier in question to avoid 4381 // confusion for constructs like "inline int a(), b;" 4382 if (DS.isInlineSpecified()) 4383 Diag(DS.getInlineSpecLoc(), 4384 diag::err_inline_non_function); 4385 4386 if (DS.isVirtualSpecified()) 4387 Diag(DS.getVirtualSpecLoc(), 4388 diag::err_virtual_non_function); 4389 4390 if (DS.isExplicitSpecified()) 4391 Diag(DS.getExplicitSpecLoc(), 4392 diag::err_explicit_non_function); 4393 4394 if (DS.isNoreturnSpecified()) 4395 Diag(DS.getNoreturnSpecLoc(), 4396 diag::err_noreturn_non_function); 4397 } 4398 4399 NamedDecl* 4400 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4401 TypeSourceInfo *TInfo, LookupResult &Previous) { 4402 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4403 if (D.getCXXScopeSpec().isSet()) { 4404 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4405 << D.getCXXScopeSpec().getRange(); 4406 D.setInvalidType(); 4407 // Pretend we didn't see the scope specifier. 4408 DC = CurContext; 4409 Previous.clear(); 4410 } 4411 4412 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4413 4414 if (D.getDeclSpec().isThreadSpecified()) 4415 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4416 if (D.getDeclSpec().isConstexprSpecified()) 4417 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4418 << 1; 4419 4420 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4421 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4422 << D.getName().getSourceRange(); 4423 return 0; 4424 } 4425 4426 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4427 if (!NewTD) return 0; 4428 4429 // Handle attributes prior to checking for duplicates in MergeVarDecl 4430 ProcessDeclAttributes(S, NewTD, D); 4431 4432 CheckTypedefForVariablyModifiedType(S, NewTD); 4433 4434 bool Redeclaration = D.isRedeclaration(); 4435 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4436 D.setRedeclaration(Redeclaration); 4437 return ND; 4438 } 4439 4440 void 4441 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4442 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4443 // then it shall have block scope. 4444 // Note that variably modified types must be fixed before merging the decl so 4445 // that redeclarations will match. 4446 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4447 QualType T = TInfo->getType(); 4448 if (T->isVariablyModifiedType()) { 4449 getCurFunction()->setHasBranchProtectedScope(); 4450 4451 if (S->getFnParent() == 0) { 4452 bool SizeIsNegative; 4453 llvm::APSInt Oversized; 4454 TypeSourceInfo *FixedTInfo = 4455 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4456 SizeIsNegative, 4457 Oversized); 4458 if (FixedTInfo) { 4459 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4460 NewTD->setTypeSourceInfo(FixedTInfo); 4461 } else { 4462 if (SizeIsNegative) 4463 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4464 else if (T->isVariableArrayType()) 4465 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4466 else if (Oversized.getBoolValue()) 4467 Diag(NewTD->getLocation(), diag::err_array_too_large) 4468 << Oversized.toString(10); 4469 else 4470 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4471 NewTD->setInvalidDecl(); 4472 } 4473 } 4474 } 4475 } 4476 4477 4478 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4479 /// declares a typedef-name, either using the 'typedef' type specifier or via 4480 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4481 NamedDecl* 4482 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4483 LookupResult &Previous, bool &Redeclaration) { 4484 // Merge the decl with the existing one if appropriate. If the decl is 4485 // in an outer scope, it isn't the same thing. 4486 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 4487 /*ExplicitInstantiationOrSpecialization=*/false); 4488 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4489 if (!Previous.empty()) { 4490 Redeclaration = true; 4491 MergeTypedefNameDecl(NewTD, Previous); 4492 } 4493 4494 // If this is the C FILE type, notify the AST context. 4495 if (IdentifierInfo *II = NewTD->getIdentifier()) 4496 if (!NewTD->isInvalidDecl() && 4497 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4498 if (II->isStr("FILE")) 4499 Context.setFILEDecl(NewTD); 4500 else if (II->isStr("jmp_buf")) 4501 Context.setjmp_bufDecl(NewTD); 4502 else if (II->isStr("sigjmp_buf")) 4503 Context.setsigjmp_bufDecl(NewTD); 4504 else if (II->isStr("ucontext_t")) 4505 Context.setucontext_tDecl(NewTD); 4506 } 4507 4508 return NewTD; 4509 } 4510 4511 /// \brief Determines whether the given declaration is an out-of-scope 4512 /// previous declaration. 4513 /// 4514 /// This routine should be invoked when name lookup has found a 4515 /// previous declaration (PrevDecl) that is not in the scope where a 4516 /// new declaration by the same name is being introduced. If the new 4517 /// declaration occurs in a local scope, previous declarations with 4518 /// linkage may still be considered previous declarations (C99 4519 /// 6.2.2p4-5, C++ [basic.link]p6). 4520 /// 4521 /// \param PrevDecl the previous declaration found by name 4522 /// lookup 4523 /// 4524 /// \param DC the context in which the new declaration is being 4525 /// declared. 4526 /// 4527 /// \returns true if PrevDecl is an out-of-scope previous declaration 4528 /// for a new delcaration with the same name. 4529 static bool 4530 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4531 ASTContext &Context) { 4532 if (!PrevDecl) 4533 return false; 4534 4535 if (!PrevDecl->hasLinkage()) 4536 return false; 4537 4538 if (Context.getLangOpts().CPlusPlus) { 4539 // C++ [basic.link]p6: 4540 // If there is a visible declaration of an entity with linkage 4541 // having the same name and type, ignoring entities declared 4542 // outside the innermost enclosing namespace scope, the block 4543 // scope declaration declares that same entity and receives the 4544 // linkage of the previous declaration. 4545 DeclContext *OuterContext = DC->getRedeclContext(); 4546 if (!OuterContext->isFunctionOrMethod()) 4547 // This rule only applies to block-scope declarations. 4548 return false; 4549 4550 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4551 if (PrevOuterContext->isRecord()) 4552 // We found a member function: ignore it. 4553 return false; 4554 4555 // Find the innermost enclosing namespace for the new and 4556 // previous declarations. 4557 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4558 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4559 4560 // The previous declaration is in a different namespace, so it 4561 // isn't the same function. 4562 if (!OuterContext->Equals(PrevOuterContext)) 4563 return false; 4564 } 4565 4566 return true; 4567 } 4568 4569 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4570 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4571 if (!SS.isSet()) return; 4572 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4573 } 4574 4575 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4576 QualType type = decl->getType(); 4577 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4578 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4579 // Various kinds of declaration aren't allowed to be __autoreleasing. 4580 unsigned kind = -1U; 4581 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4582 if (var->hasAttr<BlocksAttr>()) 4583 kind = 0; // __block 4584 else if (!var->hasLocalStorage()) 4585 kind = 1; // global 4586 } else if (isa<ObjCIvarDecl>(decl)) { 4587 kind = 3; // ivar 4588 } else if (isa<FieldDecl>(decl)) { 4589 kind = 2; // field 4590 } 4591 4592 if (kind != -1U) { 4593 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4594 << kind; 4595 } 4596 } else if (lifetime == Qualifiers::OCL_None) { 4597 // Try to infer lifetime. 4598 if (!type->isObjCLifetimeType()) 4599 return false; 4600 4601 lifetime = type->getObjCARCImplicitLifetime(); 4602 type = Context.getLifetimeQualifiedType(type, lifetime); 4603 decl->setType(type); 4604 } 4605 4606 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4607 // Thread-local variables cannot have lifetime. 4608 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4609 var->isThreadSpecified()) { 4610 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4611 << var->getType(); 4612 return true; 4613 } 4614 } 4615 4616 return false; 4617 } 4618 4619 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4620 // 'weak' only applies to declarations with external linkage. 4621 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4622 if (ND.getLinkage() != ExternalLinkage) { 4623 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4624 ND.dropAttr<WeakAttr>(); 4625 } 4626 } 4627 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4628 if (ND.hasExternalLinkage()) { 4629 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4630 ND.dropAttr<WeakRefAttr>(); 4631 } 4632 } 4633 } 4634 4635 static bool shouldConsiderLinkage(const VarDecl *VD) { 4636 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4637 if (DC->isFunctionOrMethod()) 4638 return VD->hasExternalStorageAsWritten(); 4639 if (DC->isFileContext()) 4640 return true; 4641 if (DC->isRecord()) 4642 return false; 4643 llvm_unreachable("Unexpected context"); 4644 } 4645 4646 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4647 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4648 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4649 return true; 4650 if (DC->isRecord()) 4651 return false; 4652 llvm_unreachable("Unexpected context"); 4653 } 4654 4655 NamedDecl* 4656 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 4657 TypeSourceInfo *TInfo, LookupResult &Previous, 4658 MultiTemplateParamsArg TemplateParamLists) { 4659 QualType R = TInfo->getType(); 4660 DeclarationName Name = GetNameForDeclarator(D).getName(); 4661 4662 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 4663 assert(SCSpec != DeclSpec::SCS_typedef && 4664 "Parser allowed 'typedef' as storage class VarDecl."); 4665 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 4666 4667 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) 4668 { 4669 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 4670 // half array type (unless the cl_khr_fp16 extension is enabled). 4671 if (Context.getBaseElementType(R)->isHalfType()) { 4672 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 4673 D.setInvalidType(); 4674 } 4675 } 4676 4677 if (SCSpec == DeclSpec::SCS_mutable) { 4678 // mutable can only appear on non-static class members, so it's always 4679 // an error here 4680 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 4681 D.setInvalidType(); 4682 SC = SC_None; 4683 } 4684 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 4685 VarDecl::StorageClass SCAsWritten 4686 = StorageClassSpecToVarDeclStorageClass(SCSpec); 4687 4688 IdentifierInfo *II = Name.getAsIdentifierInfo(); 4689 if (!II) { 4690 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 4691 << Name; 4692 return 0; 4693 } 4694 4695 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4696 4697 if (!DC->isRecord() && S->getFnParent() == 0) { 4698 // C99 6.9p2: The storage-class specifiers auto and register shall not 4699 // appear in the declaration specifiers in an external declaration. 4700 if (SC == SC_Auto || SC == SC_Register) { 4701 4702 // If this is a register variable with an asm label specified, then this 4703 // is a GNU extension. 4704 if (SC == SC_Register && D.getAsmLabel()) 4705 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 4706 else 4707 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 4708 D.setInvalidType(); 4709 } 4710 } 4711 4712 if (getLangOpts().OpenCL) { 4713 // Set up the special work-group-local storage class for variables in the 4714 // OpenCL __local address space. 4715 if (R.getAddressSpace() == LangAS::opencl_local) { 4716 SC = SC_OpenCLWorkGroupLocal; 4717 SCAsWritten = SC_OpenCLWorkGroupLocal; 4718 } 4719 4720 // OpenCL v1.2 s6.9.b p4: 4721 // The sampler type cannot be used with the __local and __global address 4722 // space qualifiers. 4723 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 4724 R.getAddressSpace() == LangAS::opencl_global)) { 4725 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 4726 } 4727 4728 // OpenCL 1.2 spec, p6.9 r: 4729 // The event type cannot be used to declare a program scope variable. 4730 // The event type cannot be used with the __local, __constant and __global 4731 // address space qualifiers. 4732 if (R->isEventT()) { 4733 if (S->getParent() == 0) { 4734 Diag(D.getLocStart(), diag::err_event_t_global_var); 4735 D.setInvalidType(); 4736 } 4737 4738 if (R.getAddressSpace()) { 4739 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 4740 D.setInvalidType(); 4741 } 4742 } 4743 } 4744 4745 bool isExplicitSpecialization = false; 4746 VarDecl *NewVD; 4747 if (!getLangOpts().CPlusPlus) { 4748 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4749 D.getIdentifierLoc(), II, 4750 R, TInfo, SC, SCAsWritten); 4751 4752 if (D.isInvalidType()) 4753 NewVD->setInvalidDecl(); 4754 } else { 4755 if (DC->isRecord() && !CurContext->isRecord()) { 4756 // This is an out-of-line definition of a static data member. 4757 if (SC == SC_Static) { 4758 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 4759 diag::err_static_out_of_line) 4760 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4761 } else if (SC == SC_None) 4762 SC = SC_Static; 4763 } 4764 if (SC == SC_Static && CurContext->isRecord()) { 4765 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 4766 if (RD->isLocalClass()) 4767 Diag(D.getIdentifierLoc(), 4768 diag::err_static_data_member_not_allowed_in_local_class) 4769 << Name << RD->getDeclName(); 4770 4771 // C++98 [class.union]p1: If a union contains a static data member, 4772 // the program is ill-formed. C++11 drops this restriction. 4773 if (RD->isUnion()) 4774 Diag(D.getIdentifierLoc(), 4775 getLangOpts().CPlusPlus11 4776 ? diag::warn_cxx98_compat_static_data_member_in_union 4777 : diag::ext_static_data_member_in_union) << Name; 4778 // We conservatively disallow static data members in anonymous structs. 4779 else if (!RD->getDeclName()) 4780 Diag(D.getIdentifierLoc(), 4781 diag::err_static_data_member_not_allowed_in_anon_struct) 4782 << Name << RD->isUnion(); 4783 } 4784 } 4785 4786 // Match up the template parameter lists with the scope specifier, then 4787 // determine whether we have a template or a template specialization. 4788 isExplicitSpecialization = false; 4789 bool Invalid = false; 4790 if (TemplateParameterList *TemplateParams 4791 = MatchTemplateParametersToScopeSpecifier( 4792 D.getDeclSpec().getLocStart(), 4793 D.getIdentifierLoc(), 4794 D.getCXXScopeSpec(), 4795 TemplateParamLists.data(), 4796 TemplateParamLists.size(), 4797 /*never a friend*/ false, 4798 isExplicitSpecialization, 4799 Invalid)) { 4800 if (TemplateParams->size() > 0) { 4801 // There is no such thing as a variable template. 4802 Diag(D.getIdentifierLoc(), diag::err_template_variable) 4803 << II 4804 << SourceRange(TemplateParams->getTemplateLoc(), 4805 TemplateParams->getRAngleLoc()); 4806 return 0; 4807 } else { 4808 // There is an extraneous 'template<>' for this variable. Complain 4809 // about it, but allow the declaration of the variable. 4810 Diag(TemplateParams->getTemplateLoc(), 4811 diag::err_template_variable_noparams) 4812 << II 4813 << SourceRange(TemplateParams->getTemplateLoc(), 4814 TemplateParams->getRAngleLoc()); 4815 } 4816 } 4817 4818 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 4819 D.getIdentifierLoc(), II, 4820 R, TInfo, SC, SCAsWritten); 4821 4822 // If this decl has an auto type in need of deduction, make a note of the 4823 // Decl so we can diagnose uses of it in its own initializer. 4824 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 4825 R->getContainedAutoType()) 4826 ParsingInitForAutoVars.insert(NewVD); 4827 4828 if (D.isInvalidType() || Invalid) 4829 NewVD->setInvalidDecl(); 4830 4831 SetNestedNameSpecifier(NewVD, D); 4832 4833 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 4834 NewVD->setTemplateParameterListsInfo(Context, 4835 TemplateParamLists.size(), 4836 TemplateParamLists.data()); 4837 } 4838 4839 if (D.getDeclSpec().isConstexprSpecified()) 4840 NewVD->setConstexpr(true); 4841 } 4842 4843 // Set the lexical context. If the declarator has a C++ scope specifier, the 4844 // lexical context will be different from the semantic context. 4845 NewVD->setLexicalDeclContext(CurContext); 4846 4847 if (D.getDeclSpec().isThreadSpecified()) { 4848 if (NewVD->hasLocalStorage()) 4849 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 4850 else if (!Context.getTargetInfo().isTLSSupported()) 4851 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 4852 else 4853 NewVD->setThreadSpecified(true); 4854 } 4855 4856 if (D.getDeclSpec().isModulePrivateSpecified()) { 4857 if (isExplicitSpecialization) 4858 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 4859 << 2 4860 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4861 else if (NewVD->hasLocalStorage()) 4862 Diag(NewVD->getLocation(), diag::err_module_private_local) 4863 << 0 << NewVD->getDeclName() 4864 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 4865 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 4866 else 4867 NewVD->setModulePrivate(); 4868 } 4869 4870 // Handle attributes prior to checking for duplicates in MergeVarDecl 4871 ProcessDeclAttributes(S, NewVD, D); 4872 4873 if (NewVD->hasAttrs()) 4874 CheckAlignasUnderalignment(NewVD); 4875 4876 if (getLangOpts().CUDA) { 4877 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 4878 // storage [duration]." 4879 if (SC == SC_None && S->getFnParent() != 0 && 4880 (NewVD->hasAttr<CUDASharedAttr>() || 4881 NewVD->hasAttr<CUDAConstantAttr>())) { 4882 NewVD->setStorageClass(SC_Static); 4883 NewVD->setStorageClassAsWritten(SC_Static); 4884 } 4885 } 4886 4887 // In auto-retain/release, infer strong retension for variables of 4888 // retainable type. 4889 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 4890 NewVD->setInvalidDecl(); 4891 4892 // Handle GNU asm-label extension (encoded as an attribute). 4893 if (Expr *E = (Expr*)D.getAsmLabel()) { 4894 // The parser guarantees this is a string. 4895 StringLiteral *SE = cast<StringLiteral>(E); 4896 StringRef Label = SE->getString(); 4897 if (S->getFnParent() != 0) { 4898 switch (SC) { 4899 case SC_None: 4900 case SC_Auto: 4901 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 4902 break; 4903 case SC_Register: 4904 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 4905 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 4906 break; 4907 case SC_Static: 4908 case SC_Extern: 4909 case SC_PrivateExtern: 4910 case SC_OpenCLWorkGroupLocal: 4911 break; 4912 } 4913 } 4914 4915 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 4916 Context, Label)); 4917 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 4918 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::