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