1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex 32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex 33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex 34 #include "clang/Parse/ParseDiagnostic.h" 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/Template.h" 44 #include "llvm/ADT/SmallString.h" 45 #include "llvm/ADT/Triple.h" 46 #include <algorithm> 47 #include <cstring> 48 #include <functional> 49 using namespace clang; 50 using namespace sema; 51 52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 53 if (OwnedType) { 54 Decl *Group[2] = { OwnedType, Ptr }; 55 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 56 } 57 58 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 59 } 60 61 namespace { 62 63 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 64 public: 65 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 66 bool AllowTemplates=false) 67 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 68 AllowClassTemplates(AllowTemplates) { 69 WantExpressionKeywords = false; 70 WantCXXNamedCasts = false; 71 WantRemainingKeywords = false; 72 } 73 74 bool ValidateCandidate(const TypoCorrection &candidate) override { 75 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 76 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 77 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 78 return (IsType || AllowedTemplate) && 79 (AllowInvalidDecl || !ND->isInvalidDecl()); 80 } 81 return !WantClassName && candidate.isKeyword(); 82 } 83 84 private: 85 bool AllowInvalidDecl; 86 bool WantClassName; 87 bool AllowClassTemplates; 88 }; 89 90 } 91 92 /// \brief Determine whether the token kind starts a simple-type-specifier. 93 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 94 switch (Kind) { 95 // FIXME: Take into account the current language when deciding whether a 96 // token kind is a valid type specifier 97 case tok::kw_short: 98 case tok::kw_long: 99 case tok::kw___int64: 100 case tok::kw___int128: 101 case tok::kw_signed: 102 case tok::kw_unsigned: 103 case tok::kw_void: 104 case tok::kw_char: 105 case tok::kw_int: 106 case tok::kw_half: 107 case tok::kw_float: 108 case tok::kw_double: 109 case tok::kw_wchar_t: 110 case tok::kw_bool: 111 case tok::kw___underlying_type: 112 return true; 113 114 case tok::annot_typename: 115 case tok::kw_char16_t: 116 case tok::kw_char32_t: 117 case tok::kw_typeof: 118 case tok::annot_decltype: 119 case tok::kw_decltype: 120 return getLangOpts().CPlusPlus; 121 122 default: 123 break; 124 } 125 126 return false; 127 } 128 129 /// \brief If the identifier refers to a type name within this scope, 130 /// return the declaration of that type. 131 /// 132 /// This routine performs ordinary name lookup of the identifier II 133 /// within the given scope, with optional C++ scope specifier SS, to 134 /// determine whether the name refers to a type. If so, returns an 135 /// opaque pointer (actually a QualType) corresponding to that 136 /// type. Otherwise, returns NULL. 137 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 138 Scope *S, CXXScopeSpec *SS, 139 bool isClassName, bool HasTrailingDot, 140 ParsedType ObjectTypePtr, 141 bool IsCtorOrDtorName, 142 bool WantNontrivialTypeSourceInfo, 143 IdentifierInfo **CorrectedII) { 144 // Determine where we will perform name lookup. 145 DeclContext *LookupCtx = 0; 146 if (ObjectTypePtr) { 147 QualType ObjectType = ObjectTypePtr.get(); 148 if (ObjectType->isRecordType()) 149 LookupCtx = computeDeclContext(ObjectType); 150 } else if (SS && SS->isNotEmpty()) { 151 LookupCtx = computeDeclContext(*SS, false); 152 153 if (!LookupCtx) { 154 if (isDependentScopeSpecifier(*SS)) { 155 // C++ [temp.res]p3: 156 // A qualified-id that refers to a type and in which the 157 // nested-name-specifier depends on a template-parameter (14.6.2) 158 // shall be prefixed by the keyword typename to indicate that the 159 // qualified-id denotes a type, forming an 160 // elaborated-type-specifier (7.1.5.3). 161 // 162 // We therefore do not perform any name lookup if the result would 163 // refer to a member of an unknown specialization. 164 if (!isClassName && !IsCtorOrDtorName) 165 return ParsedType(); 166 167 // We know from the grammar that this name refers to a type, 168 // so build a dependent node to describe the type. 169 if (WantNontrivialTypeSourceInfo) 170 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 171 172 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 173 QualType T = 174 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 175 II, NameLoc); 176 177 return ParsedType::make(T); 178 } 179 180 return ParsedType(); 181 } 182 183 if (!LookupCtx->isDependentContext() && 184 RequireCompleteDeclContext(*SS, LookupCtx)) 185 return ParsedType(); 186 } 187 188 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 189 // lookup for class-names. 190 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 191 LookupOrdinaryName; 192 LookupResult Result(*this, &II, NameLoc, Kind); 193 if (LookupCtx) { 194 // Perform "qualified" name lookup into the declaration context we 195 // computed, which is either the type of the base of a member access 196 // expression or the declaration context associated with a prior 197 // nested-name-specifier. 198 LookupQualifiedName(Result, LookupCtx); 199 200 if (ObjectTypePtr && Result.empty()) { 201 // C++ [basic.lookup.classref]p3: 202 // If the unqualified-id is ~type-name, the type-name is looked up 203 // in the context of the entire postfix-expression. If the type T of 204 // the object expression is of a class type C, the type-name is also 205 // looked up in the scope of class C. At least one of the lookups shall 206 // find a name that refers to (possibly cv-qualified) T. 207 LookupName(Result, S); 208 } 209 } else { 210 // Perform unqualified name lookup. 211 LookupName(Result, S); 212 } 213 214 NamedDecl *IIDecl = 0; 215 switch (Result.getResultKind()) { 216 case LookupResult::NotFound: 217 case LookupResult::NotFoundInCurrentInstantiation: 218 if (CorrectedII) { 219 TypeNameValidatorCCC Validator(true, isClassName); 220 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 221 Kind, S, SS, Validator); 222 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 223 TemplateTy Template; 224 bool MemberOfUnknownSpecialization; 225 UnqualifiedId TemplateName; 226 TemplateName.setIdentifier(NewII, NameLoc); 227 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 228 CXXScopeSpec NewSS, *NewSSPtr = SS; 229 if (SS && NNS) { 230 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 231 NewSSPtr = &NewSS; 232 } 233 if (Correction && (NNS || NewII != &II) && 234 // Ignore a correction to a template type as the to-be-corrected 235 // identifier is not a template (typo correction for template names 236 // is handled elsewhere). 237 !(getLangOpts().CPlusPlus && NewSSPtr && 238 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 239 false, Template, MemberOfUnknownSpecialization))) { 240 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 241 isClassName, HasTrailingDot, ObjectTypePtr, 242 IsCtorOrDtorName, 243 WantNontrivialTypeSourceInfo); 244 if (Ty) { 245 diagnoseTypo(Correction, 246 PDiag(diag::err_unknown_type_or_class_name_suggest) 247 << Result.getLookupName() << isClassName); 248 if (SS && NNS) 249 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 250 *CorrectedII = NewII; 251 return Ty; 252 } 253 } 254 } 255 // If typo correction failed or was not performed, fall through 256 case LookupResult::FoundOverloaded: 257 case LookupResult::FoundUnresolvedValue: 258 Result.suppressDiagnostics(); 259 return ParsedType(); 260 261 case LookupResult::Ambiguous: 262 // Recover from type-hiding ambiguities by hiding the type. We'll 263 // do the lookup again when looking for an object, and we can 264 // diagnose the error then. If we don't do this, then the error 265 // about hiding the type will be immediately followed by an error 266 // that only makes sense if the identifier was treated like a type. 267 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 268 Result.suppressDiagnostics(); 269 return ParsedType(); 270 } 271 272 // Look to see if we have a type anywhere in the list of results. 273 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 274 Res != ResEnd; ++Res) { 275 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 276 if (!IIDecl || 277 (*Res)->getLocation().getRawEncoding() < 278 IIDecl->getLocation().getRawEncoding()) 279 IIDecl = *Res; 280 } 281 } 282 283 if (!IIDecl) { 284 // None of the entities we found is a type, so there is no way 285 // to even assume that the result is a type. In this case, don't 286 // complain about the ambiguity. The parser will either try to 287 // perform this lookup again (e.g., as an object name), which 288 // will produce the ambiguity, or will complain that it expected 289 // a type name. 290 Result.suppressDiagnostics(); 291 return ParsedType(); 292 } 293 294 // We found a type within the ambiguous lookup; diagnose the 295 // ambiguity and then return that type. This might be the right 296 // answer, or it might not be, but it suppresses any attempt to 297 // perform the name lookup again. 298 break; 299 300 case LookupResult::Found: 301 IIDecl = Result.getFoundDecl(); 302 break; 303 } 304 305 assert(IIDecl && "Didn't find decl"); 306 307 QualType T; 308 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 309 DiagnoseUseOfDecl(IIDecl, NameLoc); 310 311 if (T.isNull()) 312 T = Context.getTypeDeclType(TD); 313 314 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 315 // constructor or destructor name (in such a case, the scope specifier 316 // will be attached to the enclosing Expr or Decl node). 317 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 318 if (WantNontrivialTypeSourceInfo) { 319 // Construct a type with type-source information. 320 TypeLocBuilder Builder; 321 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 322 323 T = getElaboratedType(ETK_None, *SS, T); 324 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 325 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 326 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 327 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 328 } else { 329 T = getElaboratedType(ETK_None, *SS, T); 330 } 331 } 332 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 333 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 334 if (!HasTrailingDot) 335 T = Context.getObjCInterfaceType(IDecl); 336 } 337 338 if (T.isNull()) { 339 // If it's not plausibly a type, suppress diagnostics. 340 Result.suppressDiagnostics(); 341 return ParsedType(); 342 } 343 return ParsedType::make(T); 344 } 345 346 /// isTagName() - This method is called *for error recovery purposes only* 347 /// to determine if the specified name is a valid tag name ("struct foo"). If 348 /// so, this returns the TST for the tag corresponding to it (TST_enum, 349 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 350 /// cases in C where the user forgot to specify the tag. 351 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 352 // Do a tag name lookup in this scope. 353 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 354 LookupName(R, S, false); 355 R.suppressDiagnostics(); 356 if (R.getResultKind() == LookupResult::Found) 357 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 358 switch (TD->getTagKind()) { 359 case TTK_Struct: return DeclSpec::TST_struct; 360 case TTK_Interface: return DeclSpec::TST_interface; 361 case TTK_Union: return DeclSpec::TST_union; 362 case TTK_Class: return DeclSpec::TST_class; 363 case TTK_Enum: return DeclSpec::TST_enum; 364 } 365 } 366 367 return DeclSpec::TST_unspecified; 368 } 369 370 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 371 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 372 /// then downgrade the missing typename error to a warning. 373 /// This is needed for MSVC compatibility; Example: 374 /// @code 375 /// template<class T> class A { 376 /// public: 377 /// typedef int TYPE; 378 /// }; 379 /// template<class T> class B : public A<T> { 380 /// public: 381 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 382 /// }; 383 /// @endcode 384 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 385 if (CurContext->isRecord()) { 386 const Type *Ty = SS->getScopeRep()->getAsType(); 387 388 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 389 for (const auto &Base : RD->bases()) 390 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 391 return true; 392 return S->isFunctionPrototypeScope(); 393 } 394 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 395 } 396 397 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 398 SourceLocation IILoc, 399 Scope *S, 400 CXXScopeSpec *SS, 401 ParsedType &SuggestedType, 402 bool AllowClassTemplates) { 403 // We don't have anything to suggest (yet). 404 SuggestedType = ParsedType(); 405 406 // There may have been a typo in the name of the type. Look up typo 407 // results, in case we have something that we can suggest. 408 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 409 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 410 LookupOrdinaryName, S, SS, 411 Validator)) { 412 if (Corrected.isKeyword()) { 413 // We corrected to a keyword. 414 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 415 II = Corrected.getCorrectionAsIdentifierInfo(); 416 } else { 417 // We found a similarly-named type or interface; suggest that. 418 if (!SS || !SS->isSet()) { 419 diagnoseTypo(Corrected, 420 PDiag(diag::err_unknown_typename_suggest) << II); 421 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 422 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 423 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 424 II->getName().equals(CorrectedStr); 425 diagnoseTypo(Corrected, 426 PDiag(diag::err_unknown_nested_typename_suggest) 427 << II << DC << DroppedSpecifier << SS->getRange()); 428 } else { 429 llvm_unreachable("could not have corrected a typo here"); 430 } 431 432 CXXScopeSpec tmpSS; 433 if (Corrected.getCorrectionSpecifier()) 434 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 435 SourceRange(IILoc)); 436 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 437 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 438 false, ParsedType(), 439 /*IsCtorOrDtorName=*/false, 440 /*NonTrivialTypeSourceInfo=*/true); 441 } 442 return true; 443 } 444 445 if (getLangOpts().CPlusPlus) { 446 // See if II is a class template that the user forgot to pass arguments to. 447 UnqualifiedId Name; 448 Name.setIdentifier(II, IILoc); 449 CXXScopeSpec EmptySS; 450 TemplateTy TemplateResult; 451 bool MemberOfUnknownSpecialization; 452 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 453 Name, ParsedType(), true, TemplateResult, 454 MemberOfUnknownSpecialization) == TNK_Type_template) { 455 TemplateName TplName = TemplateResult.get(); 456 Diag(IILoc, diag::err_template_missing_args) << TplName; 457 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 458 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 459 << TplDecl->getTemplateParameters()->getSourceRange(); 460 } 461 return true; 462 } 463 } 464 465 // FIXME: Should we move the logic that tries to recover from a missing tag 466 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 467 468 if (!SS || (!SS->isSet() && !SS->isInvalid())) 469 Diag(IILoc, diag::err_unknown_typename) << II; 470 else if (DeclContext *DC = computeDeclContext(*SS, false)) 471 Diag(IILoc, diag::err_typename_nested_not_found) 472 << II << DC << SS->getRange(); 473 else if (isDependentScopeSpecifier(*SS)) { 474 unsigned DiagID = diag::err_typename_missing; 475 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 476 DiagID = diag::warn_typename_missing; 477 478 Diag(SS->getRange().getBegin(), DiagID) 479 << SS->getScopeRep() << II->getName() 480 << SourceRange(SS->getRange().getBegin(), IILoc) 481 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 482 SuggestedType = ActOnTypenameType(S, SourceLocation(), 483 *SS, *II, IILoc).get(); 484 } else { 485 assert(SS && SS->isInvalid() && 486 "Invalid scope specifier has already been diagnosed"); 487 } 488 489 return true; 490 } 491 492 /// \brief Determine whether the given result set contains either a type name 493 /// or 494 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 495 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 496 NextToken.is(tok::less); 497 498 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 499 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 500 return true; 501 502 if (CheckTemplate && isa<TemplateDecl>(*I)) 503 return true; 504 } 505 506 return false; 507 } 508 509 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 510 Scope *S, CXXScopeSpec &SS, 511 IdentifierInfo *&Name, 512 SourceLocation NameLoc) { 513 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 514 SemaRef.LookupParsedName(R, S, &SS); 515 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 516 const char *TagName = 0; 517 const char *FixItTagName = 0; 518 switch (Tag->getTagKind()) { 519 case TTK_Class: 520 TagName = "class"; 521 FixItTagName = "class "; 522 break; 523 524 case TTK_Enum: 525 TagName = "enum"; 526 FixItTagName = "enum "; 527 break; 528 529 case TTK_Struct: 530 TagName = "struct"; 531 FixItTagName = "struct "; 532 break; 533 534 case TTK_Interface: 535 TagName = "__interface"; 536 FixItTagName = "__interface "; 537 break; 538 539 case TTK_Union: 540 TagName = "union"; 541 FixItTagName = "union "; 542 break; 543 } 544 545 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 546 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 547 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 548 549 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 550 I != IEnd; ++I) 551 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 552 << Name << TagName; 553 554 // Replace lookup results with just the tag decl. 555 Result.clear(Sema::LookupTagName); 556 SemaRef.LookupParsedName(Result, S, &SS); 557 return true; 558 } 559 560 return false; 561 } 562 563 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 564 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 565 QualType T, SourceLocation NameLoc) { 566 ASTContext &Context = S.Context; 567 568 TypeLocBuilder Builder; 569 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 570 571 T = S.getElaboratedType(ETK_None, SS, T); 572 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 573 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 574 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 575 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 576 } 577 578 Sema::NameClassification Sema::ClassifyName(Scope *S, 579 CXXScopeSpec &SS, 580 IdentifierInfo *&Name, 581 SourceLocation NameLoc, 582 const Token &NextToken, 583 bool IsAddressOfOperand, 584 CorrectionCandidateCallback *CCC) { 585 DeclarationNameInfo NameInfo(Name, NameLoc); 586 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 587 588 if (NextToken.is(tok::coloncolon)) { 589 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 590 QualType(), false, SS, 0, false); 591 } 592 593 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 594 LookupParsedName(Result, S, &SS, !CurMethod); 595 596 // Perform lookup for Objective-C instance variables (including automatically 597 // synthesized instance variables), if we're in an Objective-C method. 598 // FIXME: This lookup really, really needs to be folded in to the normal 599 // unqualified lookup mechanism. 600 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 601 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 602 if (E.get() || E.isInvalid()) 603 return E; 604 } 605 606 bool SecondTry = false; 607 bool IsFilteredTemplateName = false; 608 609 Corrected: 610 switch (Result.getResultKind()) { 611 case LookupResult::NotFound: 612 // If an unqualified-id is followed by a '(', then we have a function 613 // call. 614 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 615 // In C++, this is an ADL-only call. 616 // FIXME: Reference? 617 if (getLangOpts().CPlusPlus) 618 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 619 620 // C90 6.3.2.2: 621 // If the expression that precedes the parenthesized argument list in a 622 // function call consists solely of an identifier, and if no 623 // declaration is visible for this identifier, the identifier is 624 // implicitly declared exactly as if, in the innermost block containing 625 // the function call, the declaration 626 // 627 // extern int identifier (); 628 // 629 // appeared. 630 // 631 // We also allow this in C99 as an extension. 632 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 633 Result.addDecl(D); 634 Result.resolveKind(); 635 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 636 } 637 } 638 639 // In C, we first see whether there is a tag type by the same name, in 640 // which case it's likely that the user just forget to write "enum", 641 // "struct", or "union". 642 if (!getLangOpts().CPlusPlus && !SecondTry && 643 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 644 break; 645 } 646 647 // Perform typo correction to determine if there is another name that is 648 // close to this name. 649 if (!SecondTry && CCC) { 650 SecondTry = true; 651 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 652 Result.getLookupKind(), S, 653 &SS, *CCC)) { 654 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 655 unsigned QualifiedDiag = diag::err_no_member_suggest; 656 657 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 658 NamedDecl *UnderlyingFirstDecl 659 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 660 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 661 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 662 UnqualifiedDiag = diag::err_no_template_suggest; 663 QualifiedDiag = diag::err_no_member_template_suggest; 664 } else if (UnderlyingFirstDecl && 665 (isa<TypeDecl>(UnderlyingFirstDecl) || 666 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 667 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 668 UnqualifiedDiag = diag::err_unknown_typename_suggest; 669 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 670 } 671 672 if (SS.isEmpty()) { 673 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 674 } else {// FIXME: is this even reachable? Test it. 675 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 676 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 677 Name->getName().equals(CorrectedStr); 678 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 679 << Name << computeDeclContext(SS, false) 680 << DroppedSpecifier << SS.getRange()); 681 } 682 683 // Update the name, so that the caller has the new name. 684 Name = Corrected.getCorrectionAsIdentifierInfo(); 685 686 // Typo correction corrected to a keyword. 687 if (Corrected.isKeyword()) 688 return Name; 689 690 // Also update the LookupResult... 691 // FIXME: This should probably go away at some point 692 Result.clear(); 693 Result.setLookupName(Corrected.getCorrection()); 694 if (FirstDecl) 695 Result.addDecl(FirstDecl); 696 697 // If we found an Objective-C instance variable, let 698 // LookupInObjCMethod build the appropriate expression to 699 // reference the ivar. 700 // FIXME: This is a gross hack. 701 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 702 Result.clear(); 703 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 704 return E; 705 } 706 707 goto Corrected; 708 } 709 } 710 711 // We failed to correct; just fall through and let the parser deal with it. 712 Result.suppressDiagnostics(); 713 return NameClassification::Unknown(); 714 715 case LookupResult::NotFoundInCurrentInstantiation: { 716 // We performed name lookup into the current instantiation, and there were 717 // dependent bases, so we treat this result the same way as any other 718 // dependent nested-name-specifier. 719 720 // C++ [temp.res]p2: 721 // A name used in a template declaration or definition and that is 722 // dependent on a template-parameter is assumed not to name a type 723 // unless the applicable name lookup finds a type name or the name is 724 // qualified by the keyword typename. 725 // 726 // FIXME: If the next token is '<', we might want to ask the parser to 727 // perform some heroics to see if we actually have a 728 // template-argument-list, which would indicate a missing 'template' 729 // keyword here. 730 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 731 NameInfo, IsAddressOfOperand, 732 /*TemplateArgs=*/0); 733 } 734 735 case LookupResult::Found: 736 case LookupResult::FoundOverloaded: 737 case LookupResult::FoundUnresolvedValue: 738 break; 739 740 case LookupResult::Ambiguous: 741 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 742 hasAnyAcceptableTemplateNames(Result)) { 743 // C++ [temp.local]p3: 744 // A lookup that finds an injected-class-name (10.2) can result in an 745 // ambiguity in certain cases (for example, if it is found in more than 746 // one base class). If all of the injected-class-names that are found 747 // refer to specializations of the same class template, and if the name 748 // is followed by a template-argument-list, the reference refers to the 749 // class template itself and not a specialization thereof, and is not 750 // ambiguous. 751 // 752 // This filtering can make an ambiguous result into an unambiguous one, 753 // so try again after filtering out template names. 754 FilterAcceptableTemplateNames(Result); 755 if (!Result.isAmbiguous()) { 756 IsFilteredTemplateName = true; 757 break; 758 } 759 } 760 761 // Diagnose the ambiguity and return an error. 762 return NameClassification::Error(); 763 } 764 765 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 766 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 767 // C++ [temp.names]p3: 768 // After name lookup (3.4) finds that a name is a template-name or that 769 // an operator-function-id or a literal- operator-id refers to a set of 770 // overloaded functions any member of which is a function template if 771 // this is followed by a <, the < is always taken as the delimiter of a 772 // template-argument-list and never as the less-than operator. 773 if (!IsFilteredTemplateName) 774 FilterAcceptableTemplateNames(Result); 775 776 if (!Result.empty()) { 777 bool IsFunctionTemplate; 778 bool IsVarTemplate; 779 TemplateName Template; 780 if (Result.end() - Result.begin() > 1) { 781 IsFunctionTemplate = true; 782 Template = Context.getOverloadedTemplateName(Result.begin(), 783 Result.end()); 784 } else { 785 TemplateDecl *TD 786 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 787 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 788 IsVarTemplate = isa<VarTemplateDecl>(TD); 789 790 if (SS.isSet() && !SS.isInvalid()) 791 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 792 /*TemplateKeyword=*/false, 793 TD); 794 else 795 Template = TemplateName(TD); 796 } 797 798 if (IsFunctionTemplate) { 799 // Function templates always go through overload resolution, at which 800 // point we'll perform the various checks (e.g., accessibility) we need 801 // to based on which function we selected. 802 Result.suppressDiagnostics(); 803 804 return NameClassification::FunctionTemplate(Template); 805 } 806 807 return IsVarTemplate ? NameClassification::VarTemplate(Template) 808 : NameClassification::TypeTemplate(Template); 809 } 810 } 811 812 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 813 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 814 DiagnoseUseOfDecl(Type, NameLoc); 815 QualType T = Context.getTypeDeclType(Type); 816 if (SS.isNotEmpty()) 817 return buildNestedType(*this, SS, T, NameLoc); 818 return ParsedType::make(T); 819 } 820 821 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 822 if (!Class) { 823 // FIXME: It's unfortunate that we don't have a Type node for handling this. 824 if (ObjCCompatibleAliasDecl *Alias 825 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 826 Class = Alias->getClassInterface(); 827 } 828 829 if (Class) { 830 DiagnoseUseOfDecl(Class, NameLoc); 831 832 if (NextToken.is(tok::period)) { 833 // Interface. <something> is parsed as a property reference expression. 834 // Just return "unknown" as a fall-through for now. 835 Result.suppressDiagnostics(); 836 return NameClassification::Unknown(); 837 } 838 839 QualType T = Context.getObjCInterfaceType(Class); 840 return ParsedType::make(T); 841 } 842 843 // We can have a type template here if we're classifying a template argument. 844 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 845 return NameClassification::TypeTemplate( 846 TemplateName(cast<TemplateDecl>(FirstDecl))); 847 848 // Check for a tag type hidden by a non-type decl in a few cases where it 849 // seems likely a type is wanted instead of the non-type that was found. 850 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 851 if ((NextToken.is(tok::identifier) || 852 (NextIsOp && 853 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 854 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 855 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 856 DiagnoseUseOfDecl(Type, NameLoc); 857 QualType T = Context.getTypeDeclType(Type); 858 if (SS.isNotEmpty()) 859 return buildNestedType(*this, SS, T, NameLoc); 860 return ParsedType::make(T); 861 } 862 863 if (FirstDecl->isCXXClassMember()) 864 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 865 866 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 867 return BuildDeclarationNameExpr(SS, Result, ADL); 868 } 869 870 // Determines the context to return to after temporarily entering a 871 // context. This depends in an unnecessarily complicated way on the 872 // exact ordering of callbacks from the parser. 873 DeclContext *Sema::getContainingDC(DeclContext *DC) { 874 875 // Functions defined inline within classes aren't parsed until we've 876 // finished parsing the top-level class, so the top-level class is 877 // the context we'll need to return to. 878 // A Lambda call operator whose parent is a class must not be treated 879 // as an inline member function. A Lambda can be used legally 880 // either as an in-class member initializer or a default argument. These 881 // are parsed once the class has been marked complete and so the containing 882 // context would be the nested class (when the lambda is defined in one); 883 // If the class is not complete, then the lambda is being used in an 884 // ill-formed fashion (such as to specify the width of a bit-field, or 885 // in an array-bound) - in which case we still want to return the 886 // lexically containing DC (which could be a nested class). 887 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 888 DC = DC->getLexicalParent(); 889 890 // A function not defined within a class will always return to its 891 // lexical context. 892 if (!isa<CXXRecordDecl>(DC)) 893 return DC; 894 895 // A C++ inline method/friend is parsed *after* the topmost class 896 // it was declared in is fully parsed ("complete"); the topmost 897 // class is the context we need to return to. 898 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 899 DC = RD; 900 901 // Return the declaration context of the topmost class the inline method is 902 // declared in. 903 return DC; 904 } 905 906 return DC->getLexicalParent(); 907 } 908 909 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 910 assert(getContainingDC(DC) == CurContext && 911 "The next DeclContext should be lexically contained in the current one."); 912 CurContext = DC; 913 S->setEntity(DC); 914 } 915 916 void Sema::PopDeclContext() { 917 assert(CurContext && "DeclContext imbalance!"); 918 919 CurContext = getContainingDC(CurContext); 920 assert(CurContext && "Popped translation unit!"); 921 } 922 923 /// EnterDeclaratorContext - Used when we must lookup names in the context 924 /// of a declarator's nested name specifier. 925 /// 926 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 927 // C++0x [basic.lookup.unqual]p13: 928 // A name used in the definition of a static data member of class 929 // X (after the qualified-id of the static member) is looked up as 930 // if the name was used in a member function of X. 931 // C++0x [basic.lookup.unqual]p14: 932 // If a variable member of a namespace is defined outside of the 933 // scope of its namespace then any name used in the definition of 934 // the variable member (after the declarator-id) is looked up as 935 // if the definition of the variable member occurred in its 936 // namespace. 937 // Both of these imply that we should push a scope whose context 938 // is the semantic context of the declaration. We can't use 939 // PushDeclContext here because that context is not necessarily 940 // lexically contained in the current context. Fortunately, 941 // the containing scope should have the appropriate information. 942 943 assert(!S->getEntity() && "scope already has entity"); 944 945 #ifndef NDEBUG 946 Scope *Ancestor = S->getParent(); 947 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 948 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 949 #endif 950 951 CurContext = DC; 952 S->setEntity(DC); 953 } 954 955 void Sema::ExitDeclaratorContext(Scope *S) { 956 assert(S->getEntity() == CurContext && "Context imbalance!"); 957 958 // Switch back to the lexical context. The safety of this is 959 // enforced by an assert in EnterDeclaratorContext. 960 Scope *Ancestor = S->getParent(); 961 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 962 CurContext = Ancestor->getEntity(); 963 964 // We don't need to do anything with the scope, which is going to 965 // disappear. 966 } 967 968 969 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 970 // We assume that the caller has already called 971 // ActOnReenterTemplateScope so getTemplatedDecl() works. 972 FunctionDecl *FD = D->getAsFunction(); 973 if (!FD) 974 return; 975 976 // Same implementation as PushDeclContext, but enters the context 977 // from the lexical parent, rather than the top-level class. 978 assert(CurContext == FD->getLexicalParent() && 979 "The next DeclContext should be lexically contained in the current one."); 980 CurContext = FD; 981 S->setEntity(CurContext); 982 983 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 984 ParmVarDecl *Param = FD->getParamDecl(P); 985 // If the parameter has an identifier, then add it to the scope 986 if (Param->getIdentifier()) { 987 S->AddDecl(Param); 988 IdResolver.AddDecl(Param); 989 } 990 } 991 } 992 993 994 void Sema::ActOnExitFunctionContext() { 995 // Same implementation as PopDeclContext, but returns to the lexical parent, 996 // rather than the top-level class. 997 assert(CurContext && "DeclContext imbalance!"); 998 CurContext = CurContext->getLexicalParent(); 999 assert(CurContext && "Popped translation unit!"); 1000 } 1001 1002 1003 /// \brief Determine whether we allow overloading of the function 1004 /// PrevDecl with another declaration. 1005 /// 1006 /// This routine determines whether overloading is possible, not 1007 /// whether some new function is actually an overload. It will return 1008 /// true in C++ (where we can always provide overloads) or, as an 1009 /// extension, in C when the previous function is already an 1010 /// overloaded function declaration or has the "overloadable" 1011 /// attribute. 1012 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1013 ASTContext &Context) { 1014 if (Context.getLangOpts().CPlusPlus) 1015 return true; 1016 1017 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1018 return true; 1019 1020 return (Previous.getResultKind() == LookupResult::Found 1021 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1022 } 1023 1024 /// Add this decl to the scope shadowed decl chains. 1025 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1026 // Move up the scope chain until we find the nearest enclosing 1027 // non-transparent context. The declaration will be introduced into this 1028 // scope. 1029 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1030 S = S->getParent(); 1031 1032 // Add scoped declarations into their context, so that they can be 1033 // found later. Declarations without a context won't be inserted 1034 // into any context. 1035 if (AddToContext) 1036 CurContext->addDecl(D); 1037 1038 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1039 // are function-local declarations. 1040 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1041 !D->getDeclContext()->getRedeclContext()->Equals( 1042 D->getLexicalDeclContext()->getRedeclContext()) && 1043 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1044 return; 1045 1046 // Template instantiations should also not be pushed into scope. 1047 if (isa<FunctionDecl>(D) && 1048 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1049 return; 1050 1051 // If this replaces anything in the current scope, 1052 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1053 IEnd = IdResolver.end(); 1054 for (; I != IEnd; ++I) { 1055 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1056 S->RemoveDecl(*I); 1057 IdResolver.RemoveDecl(*I); 1058 1059 // Should only need to replace one decl. 1060 break; 1061 } 1062 } 1063 1064 S->AddDecl(D); 1065 1066 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1067 // Implicitly-generated labels may end up getting generated in an order that 1068 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1069 // the label at the appropriate place in the identifier chain. 1070 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1071 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1072 if (IDC == CurContext) { 1073 if (!S->isDeclScope(*I)) 1074 continue; 1075 } else if (IDC->Encloses(CurContext)) 1076 break; 1077 } 1078 1079 IdResolver.InsertDeclAfter(I, D); 1080 } else { 1081 IdResolver.AddDecl(D); 1082 } 1083 } 1084 1085 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1086 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1087 TUScope->AddDecl(D); 1088 } 1089 1090 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1091 bool AllowInlineNamespace) { 1092 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1093 } 1094 1095 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1096 DeclContext *TargetDC = DC->getPrimaryContext(); 1097 do { 1098 if (DeclContext *ScopeDC = S->getEntity()) 1099 if (ScopeDC->getPrimaryContext() == TargetDC) 1100 return S; 1101 } while ((S = S->getParent())); 1102 1103 return 0; 1104 } 1105 1106 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1107 DeclContext*, 1108 ASTContext&); 1109 1110 /// Filters out lookup results that don't fall within the given scope 1111 /// as determined by isDeclInScope. 1112 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1113 bool ConsiderLinkage, 1114 bool AllowInlineNamespace) { 1115 LookupResult::Filter F = R.makeFilter(); 1116 while (F.hasNext()) { 1117 NamedDecl *D = F.next(); 1118 1119 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1120 continue; 1121 1122 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1123 continue; 1124 1125 F.erase(); 1126 } 1127 1128 F.done(); 1129 } 1130 1131 static bool isUsingDecl(NamedDecl *D) { 1132 return isa<UsingShadowDecl>(D) || 1133 isa<UnresolvedUsingTypenameDecl>(D) || 1134 isa<UnresolvedUsingValueDecl>(D); 1135 } 1136 1137 /// Removes using shadow declarations from the lookup results. 1138 static void RemoveUsingDecls(LookupResult &R) { 1139 LookupResult::Filter F = R.makeFilter(); 1140 while (F.hasNext()) 1141 if (isUsingDecl(F.next())) 1142 F.erase(); 1143 1144 F.done(); 1145 } 1146 1147 /// \brief Check for this common pattern: 1148 /// @code 1149 /// class S { 1150 /// S(const S&); // DO NOT IMPLEMENT 1151 /// void operator=(const S&); // DO NOT IMPLEMENT 1152 /// }; 1153 /// @endcode 1154 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1155 // FIXME: Should check for private access too but access is set after we get 1156 // the decl here. 1157 if (D->doesThisDeclarationHaveABody()) 1158 return false; 1159 1160 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1161 return CD->isCopyConstructor(); 1162 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1163 return Method->isCopyAssignmentOperator(); 1164 return false; 1165 } 1166 1167 // We need this to handle 1168 // 1169 // typedef struct { 1170 // void *foo() { return 0; } 1171 // } A; 1172 // 1173 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1174 // for example. If 'A', foo will have external linkage. If we have '*A', 1175 // foo will have no linkage. Since we can't know until we get to the end 1176 // of the typedef, this function finds out if D might have non-external linkage. 1177 // Callers should verify at the end of the TU if it D has external linkage or 1178 // not. 1179 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1180 const DeclContext *DC = D->getDeclContext(); 1181 while (!DC->isTranslationUnit()) { 1182 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1183 if (!RD->hasNameForLinkage()) 1184 return true; 1185 } 1186 DC = DC->getParent(); 1187 } 1188 1189 return !D->isExternallyVisible(); 1190 } 1191 1192 // FIXME: This needs to be refactored; some other isInMainFile users want 1193 // these semantics. 1194 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1195 if (S.TUKind != TU_Complete) 1196 return false; 1197 return S.SourceMgr.isInMainFile(Loc); 1198 } 1199 1200 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1201 assert(D); 1202 1203 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1204 return false; 1205 1206 // Ignore all entities declared within templates, and out-of-line definitions 1207 // of members of class templates. 1208 if (D->getDeclContext()->isDependentContext() || 1209 D->getLexicalDeclContext()->isDependentContext()) 1210 return false; 1211 1212 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1213 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1214 return false; 1215 1216 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1217 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1218 return false; 1219 } else { 1220 // 'static inline' functions are defined in headers; don't warn. 1221 if (FD->isInlineSpecified() && 1222 !isMainFileLoc(*this, FD->getLocation())) 1223 return false; 1224 } 1225 1226 if (FD->doesThisDeclarationHaveABody() && 1227 Context.DeclMustBeEmitted(FD)) 1228 return false; 1229 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1230 // Constants and utility variables are defined in headers with internal 1231 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1232 // like "inline".) 1233 if (!isMainFileLoc(*this, VD->getLocation())) 1234 return false; 1235 1236 if (Context.DeclMustBeEmitted(VD)) 1237 return false; 1238 1239 if (VD->isStaticDataMember() && 1240 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1241 return false; 1242 } else { 1243 return false; 1244 } 1245 1246 // Only warn for unused decls internal to the translation unit. 1247 return mightHaveNonExternalLinkage(D); 1248 } 1249 1250 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1251 if (!D) 1252 return; 1253 1254 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1255 const FunctionDecl *First = FD->getFirstDecl(); 1256 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1257 return; // First should already be in the vector. 1258 } 1259 1260 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1261 const VarDecl *First = VD->getFirstDecl(); 1262 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1263 return; // First should already be in the vector. 1264 } 1265 1266 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1267 UnusedFileScopedDecls.push_back(D); 1268 } 1269 1270 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1271 if (D->isInvalidDecl()) 1272 return false; 1273 1274 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1275 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1276 return false; 1277 1278 if (isa<LabelDecl>(D)) 1279 return true; 1280 1281 // White-list anything that isn't a local variable. 1282 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1283 !D->getDeclContext()->isFunctionOrMethod()) 1284 return false; 1285 1286 // Types of valid local variables should be complete, so this should succeed. 1287 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1288 1289 // White-list anything with an __attribute__((unused)) type. 1290 QualType Ty = VD->getType(); 1291 1292 // Only look at the outermost level of typedef. 1293 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1294 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1295 return false; 1296 } 1297 1298 // If we failed to complete the type for some reason, or if the type is 1299 // dependent, don't diagnose the variable. 1300 if (Ty->isIncompleteType() || Ty->isDependentType()) 1301 return false; 1302 1303 if (const TagType *TT = Ty->getAs<TagType>()) { 1304 const TagDecl *Tag = TT->getDecl(); 1305 if (Tag->hasAttr<UnusedAttr>()) 1306 return false; 1307 1308 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1309 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1310 return false; 1311 1312 if (const Expr *Init = VD->getInit()) { 1313 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init)) 1314 Init = Cleanups->getSubExpr(); 1315 const CXXConstructExpr *Construct = 1316 dyn_cast<CXXConstructExpr>(Init); 1317 if (Construct && !Construct->isElidable()) { 1318 CXXConstructorDecl *CD = Construct->getConstructor(); 1319 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1320 return false; 1321 } 1322 } 1323 } 1324 } 1325 1326 // TODO: __attribute__((unused)) templates? 1327 } 1328 1329 return true; 1330 } 1331 1332 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1333 FixItHint &Hint) { 1334 if (isa<LabelDecl>(D)) { 1335 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1336 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1337 if (AfterColon.isInvalid()) 1338 return; 1339 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1340 getCharRange(D->getLocStart(), AfterColon)); 1341 } 1342 return; 1343 } 1344 1345 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1346 /// unless they are marked attr(unused). 1347 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1348 FixItHint Hint; 1349 if (!ShouldDiagnoseUnusedDecl(D)) 1350 return; 1351 1352 GenerateFixForUnusedDecl(D, Context, Hint); 1353 1354 unsigned DiagID; 1355 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1356 DiagID = diag::warn_unused_exception_param; 1357 else if (isa<LabelDecl>(D)) 1358 DiagID = diag::warn_unused_label; 1359 else 1360 DiagID = diag::warn_unused_variable; 1361 1362 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1363 } 1364 1365 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1366 // Verify that we have no forward references left. If so, there was a goto 1367 // or address of a label taken, but no definition of it. Label fwd 1368 // definitions are indicated with a null substmt. 1369 if (L->getStmt() == 0) 1370 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1371 } 1372 1373 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1374 if (S->decl_empty()) return; 1375 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1376 "Scope shouldn't contain decls!"); 1377 1378 for (auto *TmpD : S->decls()) { 1379 assert(TmpD && "This decl didn't get pushed??"); 1380 1381 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1382 NamedDecl *D = cast<NamedDecl>(TmpD); 1383 1384 if (!D->getDeclName()) continue; 1385 1386 // Diagnose unused variables in this scope. 1387 if (!S->hasUnrecoverableErrorOccurred()) 1388 DiagnoseUnusedDecl(D); 1389 1390 // If this was a forward reference to a label, verify it was defined. 1391 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1392 CheckPoppedLabel(LD, *this); 1393 1394 // Remove this name from our lexical scope. 1395 IdResolver.RemoveDecl(D); 1396 } 1397 } 1398 1399 /// \brief Look for an Objective-C class in the translation unit. 1400 /// 1401 /// \param Id The name of the Objective-C class we're looking for. If 1402 /// typo-correction fixes this name, the Id will be updated 1403 /// to the fixed name. 1404 /// 1405 /// \param IdLoc The location of the name in the translation unit. 1406 /// 1407 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1408 /// if there is no class with the given name. 1409 /// 1410 /// \returns The declaration of the named Objective-C class, or NULL if the 1411 /// class could not be found. 1412 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1413 SourceLocation IdLoc, 1414 bool DoTypoCorrection) { 1415 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1416 // creation from this context. 1417 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1418 1419 if (!IDecl && DoTypoCorrection) { 1420 // Perform typo correction at the given location, but only if we 1421 // find an Objective-C class name. 1422 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1423 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1424 LookupOrdinaryName, TUScope, NULL, 1425 Validator)) { 1426 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1427 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1428 Id = IDecl->getIdentifier(); 1429 } 1430 } 1431 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1432 // This routine must always return a class definition, if any. 1433 if (Def && Def->getDefinition()) 1434 Def = Def->getDefinition(); 1435 return Def; 1436 } 1437 1438 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1439 /// from S, where a non-field would be declared. This routine copes 1440 /// with the difference between C and C++ scoping rules in structs and 1441 /// unions. For example, the following code is well-formed in C but 1442 /// ill-formed in C++: 1443 /// @code 1444 /// struct S6 { 1445 /// enum { BAR } e; 1446 /// }; 1447 /// 1448 /// void test_S6() { 1449 /// struct S6 a; 1450 /// a.e = BAR; 1451 /// } 1452 /// @endcode 1453 /// For the declaration of BAR, this routine will return a different 1454 /// scope. The scope S will be the scope of the unnamed enumeration 1455 /// within S6. In C++, this routine will return the scope associated 1456 /// with S6, because the enumeration's scope is a transparent 1457 /// context but structures can contain non-field names. In C, this 1458 /// routine will return the translation unit scope, since the 1459 /// enumeration's scope is a transparent context and structures cannot 1460 /// contain non-field names. 1461 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1462 while (((S->getFlags() & Scope::DeclScope) == 0) || 1463 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1464 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1465 S = S->getParent(); 1466 return S; 1467 } 1468 1469 /// \brief Looks up the declaration of "struct objc_super" and 1470 /// saves it for later use in building builtin declaration of 1471 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1472 /// pre-existing declaration exists no action takes place. 1473 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1474 IdentifierInfo *II) { 1475 if (!II->isStr("objc_msgSendSuper")) 1476 return; 1477 ASTContext &Context = ThisSema.Context; 1478 1479 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1480 SourceLocation(), Sema::LookupTagName); 1481 ThisSema.LookupName(Result, S); 1482 if (Result.getResultKind() == LookupResult::Found) 1483 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1484 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1485 } 1486 1487 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1488 /// file scope. lazily create a decl for it. ForRedeclaration is true 1489 /// if we're creating this built-in in anticipation of redeclaring the 1490 /// built-in. 1491 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1492 Scope *S, bool ForRedeclaration, 1493 SourceLocation Loc) { 1494 LookupPredefedObjCSuperType(*this, S, II); 1495 1496 Builtin::ID BID = (Builtin::ID)bid; 1497 1498 ASTContext::GetBuiltinTypeError Error; 1499 QualType R = Context.GetBuiltinType(BID, Error); 1500 switch (Error) { 1501 case ASTContext::GE_None: 1502 // Okay 1503 break; 1504 1505 case ASTContext::GE_Missing_stdio: 1506 if (ForRedeclaration) 1507 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1508 << Context.BuiltinInfo.GetName(BID); 1509 return 0; 1510 1511 case ASTContext::GE_Missing_setjmp: 1512 if (ForRedeclaration) 1513 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1514 << Context.BuiltinInfo.GetName(BID); 1515 return 0; 1516 1517 case ASTContext::GE_Missing_ucontext: 1518 if (ForRedeclaration) 1519 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1520 << Context.BuiltinInfo.GetName(BID); 1521 return 0; 1522 } 1523 1524 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1525 Diag(Loc, diag::ext_implicit_lib_function_decl) 1526 << Context.BuiltinInfo.GetName(BID) 1527 << R; 1528 if (Context.BuiltinInfo.getHeaderName(BID) && 1529 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1530 != DiagnosticsEngine::Ignored) 1531 Diag(Loc, diag::note_please_include_header) 1532 << Context.BuiltinInfo.getHeaderName(BID) 1533 << Context.BuiltinInfo.GetName(BID); 1534 } 1535 1536 DeclContext *Parent = Context.getTranslationUnitDecl(); 1537 if (getLangOpts().CPlusPlus) { 1538 LinkageSpecDecl *CLinkageDecl = 1539 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1540 LinkageSpecDecl::lang_c, false); 1541 CLinkageDecl->setImplicit(); 1542 Parent->addDecl(CLinkageDecl); 1543 Parent = CLinkageDecl; 1544 } 1545 1546 FunctionDecl *New = FunctionDecl::Create(Context, 1547 Parent, 1548 Loc, Loc, II, R, /*TInfo=*/0, 1549 SC_Extern, 1550 false, 1551 /*hasPrototype=*/true); 1552 New->setImplicit(); 1553 1554 // Create Decl objects for each parameter, adding them to the 1555 // FunctionDecl. 1556 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1557 SmallVector<ParmVarDecl*, 16> Params; 1558 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1559 ParmVarDecl *parm = 1560 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1561 0, FT->getParamType(i), /*TInfo=*/0, SC_None, 0); 1562 parm->setScopeInfo(0, i); 1563 Params.push_back(parm); 1564 } 1565 New->setParams(Params); 1566 } 1567 1568 AddKnownFunctionAttributes(New); 1569 RegisterLocallyScopedExternCDecl(New, S); 1570 1571 // TUScope is the translation-unit scope to insert this function into. 1572 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1573 // relate Scopes to DeclContexts, and probably eliminate CurContext 1574 // entirely, but we're not there yet. 1575 DeclContext *SavedContext = CurContext; 1576 CurContext = Parent; 1577 PushOnScopeChains(New, TUScope); 1578 CurContext = SavedContext; 1579 return New; 1580 } 1581 1582 /// \brief Filter out any previous declarations that the given declaration 1583 /// should not consider because they are not permitted to conflict, e.g., 1584 /// because they come from hidden sub-modules and do not refer to the same 1585 /// entity. 1586 static void filterNonConflictingPreviousDecls(ASTContext &context, 1587 NamedDecl *decl, 1588 LookupResult &previous){ 1589 // This is only interesting when modules are enabled. 1590 if (!context.getLangOpts().Modules) 1591 return; 1592 1593 // Empty sets are uninteresting. 1594 if (previous.empty()) 1595 return; 1596 1597 LookupResult::Filter filter = previous.makeFilter(); 1598 while (filter.hasNext()) { 1599 NamedDecl *old = filter.next(); 1600 1601 // Non-hidden declarations are never ignored. 1602 if (!old->isHidden()) 1603 continue; 1604 1605 if (!old->isExternallyVisible()) 1606 filter.erase(); 1607 } 1608 1609 filter.done(); 1610 } 1611 1612 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1613 QualType OldType; 1614 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1615 OldType = OldTypedef->getUnderlyingType(); 1616 else 1617 OldType = Context.getTypeDeclType(Old); 1618 QualType NewType = New->getUnderlyingType(); 1619 1620 if (NewType->isVariablyModifiedType()) { 1621 // Must not redefine a typedef with a variably-modified type. 1622 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1623 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1624 << Kind << NewType; 1625 if (Old->getLocation().isValid()) 1626 Diag(Old->getLocation(), diag::note_previous_definition); 1627 New->setInvalidDecl(); 1628 return true; 1629 } 1630 1631 if (OldType != NewType && 1632 !OldType->isDependentType() && 1633 !NewType->isDependentType() && 1634 !Context.hasSameType(OldType, NewType)) { 1635 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1636 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1637 << Kind << NewType << OldType; 1638 if (Old->getLocation().isValid()) 1639 Diag(Old->getLocation(), diag::note_previous_definition); 1640 New->setInvalidDecl(); 1641 return true; 1642 } 1643 return false; 1644 } 1645 1646 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1647 /// same name and scope as a previous declaration 'Old'. Figure out 1648 /// how to resolve this situation, merging decls or emitting 1649 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1650 /// 1651 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1652 // If the new decl is known invalid already, don't bother doing any 1653 // merging checks. 1654 if (New->isInvalidDecl()) return; 1655 1656 // Allow multiple definitions for ObjC built-in typedefs. 1657 // FIXME: Verify the underlying types are equivalent! 1658 if (getLangOpts().ObjC1) { 1659 const IdentifierInfo *TypeID = New->getIdentifier(); 1660 switch (TypeID->getLength()) { 1661 default: break; 1662 case 2: 1663 { 1664 if (!TypeID->isStr("id")) 1665 break; 1666 QualType T = New->getUnderlyingType(); 1667 if (!T->isPointerType()) 1668 break; 1669 if (!T->isVoidPointerType()) { 1670 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1671 if (!PT->isStructureType()) 1672 break; 1673 } 1674 Context.setObjCIdRedefinitionType(T); 1675 // Install the built-in type for 'id', ignoring the current definition. 1676 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1677 return; 1678 } 1679 case 5: 1680 if (!TypeID->isStr("Class")) 1681 break; 1682 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1683 // Install the built-in type for 'Class', ignoring the current definition. 1684 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1685 return; 1686 case 3: 1687 if (!TypeID->isStr("SEL")) 1688 break; 1689 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1690 // Install the built-in type for 'SEL', ignoring the current definition. 1691 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1692 return; 1693 } 1694 // Fall through - the typedef name was not a builtin type. 1695 } 1696 1697 // Verify the old decl was also a type. 1698 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1699 if (!Old) { 1700 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1701 << New->getDeclName(); 1702 1703 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1704 if (OldD->getLocation().isValid()) 1705 Diag(OldD->getLocation(), diag::note_previous_definition); 1706 1707 return New->setInvalidDecl(); 1708 } 1709 1710 // If the old declaration is invalid, just give up here. 1711 if (Old->isInvalidDecl()) 1712 return New->setInvalidDecl(); 1713 1714 // If the typedef types are not identical, reject them in all languages and 1715 // with any extensions enabled. 1716 if (isIncompatibleTypedef(Old, New)) 1717 return; 1718 1719 // The types match. Link up the redeclaration chain and merge attributes if 1720 // the old declaration was a typedef. 1721 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1722 New->setPreviousDecl(Typedef); 1723 mergeDeclAttributes(New, Old); 1724 } 1725 1726 if (getLangOpts().MicrosoftExt) 1727 return; 1728 1729 if (getLangOpts().CPlusPlus) { 1730 // C++ [dcl.typedef]p2: 1731 // In a given non-class scope, a typedef specifier can be used to 1732 // redefine the name of any type declared in that scope to refer 1733 // to the type to which it already refers. 1734 if (!isa<CXXRecordDecl>(CurContext)) 1735 return; 1736 1737 // C++0x [dcl.typedef]p4: 1738 // In a given class scope, a typedef specifier can be used to redefine 1739 // any class-name declared in that scope that is not also a typedef-name 1740 // to refer to the type to which it already refers. 1741 // 1742 // This wording came in via DR424, which was a correction to the 1743 // wording in DR56, which accidentally banned code like: 1744 // 1745 // struct S { 1746 // typedef struct A { } A; 1747 // }; 1748 // 1749 // in the C++03 standard. We implement the C++0x semantics, which 1750 // allow the above but disallow 1751 // 1752 // struct S { 1753 // typedef int I; 1754 // typedef int I; 1755 // }; 1756 // 1757 // since that was the intent of DR56. 1758 if (!isa<TypedefNameDecl>(Old)) 1759 return; 1760 1761 Diag(New->getLocation(), diag::err_redefinition) 1762 << New->getDeclName(); 1763 Diag(Old->getLocation(), diag::note_previous_definition); 1764 return New->setInvalidDecl(); 1765 } 1766 1767 // Modules always permit redefinition of typedefs, as does C11. 1768 if (getLangOpts().Modules || getLangOpts().C11) 1769 return; 1770 1771 // If we have a redefinition of a typedef in C, emit a warning. This warning 1772 // is normally mapped to an error, but can be controlled with 1773 // -Wtypedef-redefinition. If either the original or the redefinition is 1774 // in a system header, don't emit this for compatibility with GCC. 1775 if (getDiagnostics().getSuppressSystemWarnings() && 1776 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1777 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1778 return; 1779 1780 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1781 << New->getDeclName(); 1782 Diag(Old->getLocation(), diag::note_previous_definition); 1783 return; 1784 } 1785 1786 /// DeclhasAttr - returns true if decl Declaration already has the target 1787 /// attribute. 1788 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1789 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1790 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1791 for (const auto *i : D->attrs()) 1792 if (i->getKind() == A->getKind()) { 1793 if (Ann) { 1794 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1795 return true; 1796 continue; 1797 } 1798 // FIXME: Don't hardcode this check 1799 if (OA && isa<OwnershipAttr>(i)) 1800 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1801 return true; 1802 } 1803 1804 return false; 1805 } 1806 1807 static bool isAttributeTargetADefinition(Decl *D) { 1808 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1809 return VD->isThisDeclarationADefinition(); 1810 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1811 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1812 return true; 1813 } 1814 1815 /// Merge alignment attributes from \p Old to \p New, taking into account the 1816 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1817 /// 1818 /// \return \c true if any attributes were added to \p New. 1819 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1820 // Look for alignas attributes on Old, and pick out whichever attribute 1821 // specifies the strictest alignment requirement. 1822 AlignedAttr *OldAlignasAttr = 0; 1823 AlignedAttr *OldStrictestAlignAttr = 0; 1824 unsigned OldAlign = 0; 1825 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 1826 // FIXME: We have no way of representing inherited dependent alignments 1827 // in a case like: 1828 // template<int A, int B> struct alignas(A) X; 1829 // template<int A, int B> struct alignas(B) X {}; 1830 // For now, we just ignore any alignas attributes which are not on the 1831 // definition in such a case. 1832 if (I->isAlignmentDependent()) 1833 return false; 1834 1835 if (I->isAlignas()) 1836 OldAlignasAttr = I; 1837 1838 unsigned Align = I->getAlignment(S.Context); 1839 if (Align > OldAlign) { 1840 OldAlign = Align; 1841 OldStrictestAlignAttr = I; 1842 } 1843 } 1844 1845 // Look for alignas attributes on New. 1846 AlignedAttr *NewAlignasAttr = 0; 1847 unsigned NewAlign = 0; 1848 for (auto *I : New->specific_attrs<AlignedAttr>()) { 1849 if (I->isAlignmentDependent()) 1850 return false; 1851 1852 if (I->isAlignas()) 1853 NewAlignasAttr = I; 1854 1855 unsigned Align = I->getAlignment(S.Context); 1856 if (Align > NewAlign) 1857 NewAlign = Align; 1858 } 1859 1860 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1861 // Both declarations have 'alignas' attributes. We require them to match. 1862 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1863 // fall short. (If two declarations both have alignas, they must both match 1864 // every definition, and so must match each other if there is a definition.) 1865 1866 // If either declaration only contains 'alignas(0)' specifiers, then it 1867 // specifies the natural alignment for the type. 1868 if (OldAlign == 0 || NewAlign == 0) { 1869 QualType Ty; 1870 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1871 Ty = VD->getType(); 1872 else 1873 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1874 1875 if (OldAlign == 0) 1876 OldAlign = S.Context.getTypeAlign(Ty); 1877 if (NewAlign == 0) 1878 NewAlign = S.Context.getTypeAlign(Ty); 1879 } 1880 1881 if (OldAlign != NewAlign) { 1882 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1883 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1884 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1885 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1886 } 1887 } 1888 1889 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1890 // C++11 [dcl.align]p6: 1891 // if any declaration of an entity has an alignment-specifier, 1892 // every defining declaration of that entity shall specify an 1893 // equivalent alignment. 1894 // C11 6.7.5/7: 1895 // If the definition of an object does not have an alignment 1896 // specifier, any other declaration of that object shall also 1897 // have no alignment specifier. 1898 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1899 << OldAlignasAttr; 1900 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1901 << OldAlignasAttr; 1902 } 1903 1904 bool AnyAdded = false; 1905 1906 // Ensure we have an attribute representing the strictest alignment. 1907 if (OldAlign > NewAlign) { 1908 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1909 Clone->setInherited(true); 1910 New->addAttr(Clone); 1911 AnyAdded = true; 1912 } 1913 1914 // Ensure we have an alignas attribute if the old declaration had one. 1915 if (OldAlignasAttr && !NewAlignasAttr && 1916 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1917 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1918 Clone->setInherited(true); 1919 New->addAttr(Clone); 1920 AnyAdded = true; 1921 } 1922 1923 return AnyAdded; 1924 } 1925 1926 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 1927 const InheritableAttr *Attr, bool Override) { 1928 InheritableAttr *NewAttr = nullptr; 1929 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1930 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 1931 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1932 AA->getIntroduced(), AA->getDeprecated(), 1933 AA->getObsoleted(), AA->getUnavailable(), 1934 AA->getMessage(), Override, 1935 AttrSpellingListIndex); 1936 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 1937 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1938 AttrSpellingListIndex); 1939 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1940 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1941 AttrSpellingListIndex); 1942 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1943 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1944 AttrSpellingListIndex); 1945 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1946 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1947 AttrSpellingListIndex); 1948 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 1949 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1950 FA->getFormatIdx(), FA->getFirstArg(), 1951 AttrSpellingListIndex); 1952 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 1953 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 1954 AttrSpellingListIndex); 1955 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 1956 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 1957 AttrSpellingListIndex, 1958 IA->getSemanticSpelling()); 1959 else if (isa<AlignedAttr>(Attr)) 1960 // AlignedAttrs are handled separately, because we need to handle all 1961 // such attributes on a declaration at the same time. 1962 NewAttr = nullptr; 1963 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 1964 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 1965 1966 if (NewAttr) { 1967 NewAttr->setInherited(true); 1968 D->addAttr(NewAttr); 1969 return true; 1970 } 1971 1972 return false; 1973 } 1974 1975 static const Decl *getDefinition(const Decl *D) { 1976 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 1977 return TD->getDefinition(); 1978 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1979 const VarDecl *Def = VD->getDefinition(); 1980 if (Def) 1981 return Def; 1982 return VD->getActingDefinition(); 1983 } 1984 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1985 const FunctionDecl* Def; 1986 if (FD->isDefined(Def)) 1987 return Def; 1988 } 1989 return NULL; 1990 } 1991 1992 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 1993 for (const auto *Attribute : D->attrs()) 1994 if (Attribute->getKind() == Kind) 1995 return true; 1996 return false; 1997 } 1998 1999 /// checkNewAttributesAfterDef - If we already have a definition, check that 2000 /// there are no new attributes in this declaration. 2001 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2002 if (!New->hasAttrs()) 2003 return; 2004 2005 const Decl *Def = getDefinition(Old); 2006 if (!Def || Def == New) 2007 return; 2008 2009 AttrVec &NewAttributes = New->getAttrs(); 2010 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2011 const Attr *NewAttribute = NewAttributes[I]; 2012 2013 if (isa<AliasAttr>(NewAttribute)) { 2014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2015 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2016 else { 2017 VarDecl *VD = cast<VarDecl>(New); 2018 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2019 VarDecl::TentativeDefinition 2020 ? diag::err_alias_after_tentative 2021 : diag::err_redefinition; 2022 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2023 S.Diag(Def->getLocation(), diag::note_previous_definition); 2024 VD->setInvalidDecl(); 2025 } 2026 ++I; 2027 continue; 2028 } 2029 2030 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2031 // Tentative definitions are only interesting for the alias check above. 2032 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2033 ++I; 2034 continue; 2035 } 2036 } 2037 2038 if (hasAttribute(Def, NewAttribute->getKind())) { 2039 ++I; 2040 continue; // regular attr merging will take care of validating this. 2041 } 2042 2043 if (isa<C11NoReturnAttr>(NewAttribute)) { 2044 // C's _Noreturn is allowed to be added to a function after it is defined. 2045 ++I; 2046 continue; 2047 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2048 if (AA->isAlignas()) { 2049 // C++11 [dcl.align]p6: 2050 // if any declaration of an entity has an alignment-specifier, 2051 // every defining declaration of that entity shall specify an 2052 // equivalent alignment. 2053 // C11 6.7.5/7: 2054 // If the definition of an object does not have an alignment 2055 // specifier, any other declaration of that object shall also 2056 // have no alignment specifier. 2057 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2058 << AA; 2059 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2060 << AA; 2061 NewAttributes.erase(NewAttributes.begin() + I); 2062 --E; 2063 continue; 2064 } 2065 } 2066 2067 S.Diag(NewAttribute->getLocation(), 2068 diag::warn_attribute_precede_definition); 2069 S.Diag(Def->getLocation(), diag::note_previous_definition); 2070 NewAttributes.erase(NewAttributes.begin() + I); 2071 --E; 2072 } 2073 } 2074 2075 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2076 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2077 AvailabilityMergeKind AMK) { 2078 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2079 UsedAttr *NewAttr = OldAttr->clone(Context); 2080 NewAttr->setInherited(true); 2081 New->addAttr(NewAttr); 2082 } 2083 2084 if (!Old->hasAttrs() && !New->hasAttrs()) 2085 return; 2086 2087 // attributes declared post-definition are currently ignored 2088 checkNewAttributesAfterDef(*this, New, Old); 2089 2090 if (!Old->hasAttrs()) 2091 return; 2092 2093 bool foundAny = New->hasAttrs(); 2094 2095 // Ensure that any moving of objects within the allocated map is done before 2096 // we process them. 2097 if (!foundAny) New->setAttrs(AttrVec()); 2098 2099 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2100 bool Override = false; 2101 // Ignore deprecated/unavailable/availability attributes if requested. 2102 if (isa<DeprecatedAttr>(I) || 2103 isa<UnavailableAttr>(I) || 2104 isa<AvailabilityAttr>(I)) { 2105 switch (AMK) { 2106 case AMK_None: 2107 continue; 2108 2109 case AMK_Redeclaration: 2110 break; 2111 2112 case AMK_Override: 2113 Override = true; 2114 break; 2115 } 2116 } 2117 2118 // Already handled. 2119 if (isa<UsedAttr>(I)) 2120 continue; 2121 2122 if (mergeDeclAttribute(*this, New, I, Override)) 2123 foundAny = true; 2124 } 2125 2126 if (mergeAlignedAttrs(*this, New, Old)) 2127 foundAny = true; 2128 2129 if (!foundAny) New->dropAttrs(); 2130 } 2131 2132 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2133 /// to the new one. 2134 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2135 const ParmVarDecl *oldDecl, 2136 Sema &S) { 2137 // C++11 [dcl.attr.depend]p2: 2138 // The first declaration of a function shall specify the 2139 // carries_dependency attribute for its declarator-id if any declaration 2140 // of the function specifies the carries_dependency attribute. 2141 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2142 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2143 S.Diag(CDA->getLocation(), 2144 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2145 // Find the first declaration of the parameter. 2146 // FIXME: Should we build redeclaration chains for function parameters? 2147 const FunctionDecl *FirstFD = 2148 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2149 const ParmVarDecl *FirstVD = 2150 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2151 S.Diag(FirstVD->getLocation(), 2152 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2153 } 2154 2155 if (!oldDecl->hasAttrs()) 2156 return; 2157 2158 bool foundAny = newDecl->hasAttrs(); 2159 2160 // Ensure that any moving of objects within the allocated map is 2161 // done before we process them. 2162 if (!foundAny) newDecl->setAttrs(AttrVec()); 2163 2164 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2165 if (!DeclHasAttr(newDecl, I)) { 2166 InheritableAttr *newAttr = 2167 cast<InheritableParamAttr>(I->clone(S.Context)); 2168 newAttr->setInherited(true); 2169 newDecl->addAttr(newAttr); 2170 foundAny = true; 2171 } 2172 } 2173 2174 if (!foundAny) newDecl->dropAttrs(); 2175 } 2176 2177 namespace { 2178 2179 /// Used in MergeFunctionDecl to keep track of function parameters in 2180 /// C. 2181 struct GNUCompatibleParamWarning { 2182 ParmVarDecl *OldParm; 2183 ParmVarDecl *NewParm; 2184 QualType PromotedType; 2185 }; 2186 2187 } 2188 2189 /// getSpecialMember - get the special member enum for a method. 2190 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2191 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2192 if (Ctor->isDefaultConstructor()) 2193 return Sema::CXXDefaultConstructor; 2194 2195 if (Ctor->isCopyConstructor()) 2196 return Sema::CXXCopyConstructor; 2197 2198 if (Ctor->isMoveConstructor()) 2199 return Sema::CXXMoveConstructor; 2200 } else if (isa<CXXDestructorDecl>(MD)) { 2201 return Sema::CXXDestructor; 2202 } else if (MD->isCopyAssignmentOperator()) { 2203 return Sema::CXXCopyAssignment; 2204 } else if (MD->isMoveAssignmentOperator()) { 2205 return Sema::CXXMoveAssignment; 2206 } 2207 2208 return Sema::CXXInvalid; 2209 } 2210 2211 /// canRedefineFunction - checks if a function can be redefined. Currently, 2212 /// only extern inline functions can be redefined, and even then only in 2213 /// GNU89 mode. 2214 static bool canRedefineFunction(const FunctionDecl *FD, 2215 const LangOptions& LangOpts) { 2216 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2217 !LangOpts.CPlusPlus && 2218 FD->isInlineSpecified() && 2219 FD->getStorageClass() == SC_Extern); 2220 } 2221 2222 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2223 const AttributedType *AT = T->getAs<AttributedType>(); 2224 while (AT && !AT->isCallingConv()) 2225 AT = AT->getModifiedType()->getAs<AttributedType>(); 2226 return AT; 2227 } 2228 2229 template <typename T> 2230 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2231 const DeclContext *DC = Old->getDeclContext(); 2232 if (DC->isRecord()) 2233 return false; 2234 2235 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2236 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2237 return true; 2238 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2239 return true; 2240 return false; 2241 } 2242 2243 /// MergeFunctionDecl - We just parsed a function 'New' from 2244 /// declarator D which has the same name and scope as a previous 2245 /// declaration 'Old'. Figure out how to resolve this situation, 2246 /// merging decls or emitting diagnostics as appropriate. 2247 /// 2248 /// In C++, New and Old must be declarations that are not 2249 /// overloaded. Use IsOverload to determine whether New and Old are 2250 /// overloaded, and to select the Old declaration that New should be 2251 /// merged with. 2252 /// 2253 /// Returns true if there was an error, false otherwise. 2254 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2255 Scope *S, bool MergeTypeWithOld) { 2256 // Verify the old decl was also a function. 2257 FunctionDecl *Old = OldD->getAsFunction(); 2258 if (!Old) { 2259 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2260 if (New->getFriendObjectKind()) { 2261 Diag(New->getLocation(), diag::err_using_decl_friend); 2262 Diag(Shadow->getTargetDecl()->getLocation(), 2263 diag::note_using_decl_target); 2264 Diag(Shadow->getUsingDecl()->getLocation(), 2265 diag::note_using_decl) << 0; 2266 return true; 2267 } 2268 2269 // C++11 [namespace.udecl]p14: 2270 // If a function declaration in namespace scope or block scope has the 2271 // same name and the same parameter-type-list as a function introduced 2272 // by a using-declaration, and the declarations do not declare the same 2273 // function, the program is ill-formed. 2274 2275 // Check whether the two declarations might declare the same function. 2276 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2277 if (Old && 2278 !Old->getDeclContext()->getRedeclContext()->Equals( 2279 New->getDeclContext()->getRedeclContext()) && 2280 !(Old->isExternC() && New->isExternC())) 2281 Old = 0; 2282 2283 if (!Old) { 2284 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2285 Diag(Shadow->getTargetDecl()->getLocation(), 2286 diag::note_using_decl_target); 2287 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2288 return true; 2289 } 2290 OldD = Old; 2291 } else { 2292 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2293 << New->getDeclName(); 2294 Diag(OldD->getLocation(), diag::note_previous_definition); 2295 return true; 2296 } 2297 } 2298 2299 // If the old declaration is invalid, just give up here. 2300 if (Old->isInvalidDecl()) 2301 return true; 2302 2303 // Determine whether the previous declaration was a definition, 2304 // implicit declaration, or a declaration. 2305 diag::kind PrevDiag; 2306 SourceLocation OldLocation = Old->getLocation(); 2307 if (Old->isThisDeclarationADefinition()) 2308 PrevDiag = diag::note_previous_definition; 2309 else if (Old->isImplicit()) { 2310 PrevDiag = diag::note_previous_implicit_declaration; 2311 if (OldLocation.isInvalid()) 2312 OldLocation = New->getLocation(); 2313 } else 2314 PrevDiag = diag::note_previous_declaration; 2315 2316 // Don't complain about this if we're in GNU89 mode and the old function 2317 // is an extern inline function. 2318 // Don't complain about specializations. They are not supposed to have 2319 // storage classes. 2320 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2321 New->getStorageClass() == SC_Static && 2322 Old->hasExternalFormalLinkage() && 2323 !New->getTemplateSpecializationInfo() && 2324 !canRedefineFunction(Old, getLangOpts())) { 2325 if (getLangOpts().MicrosoftExt) { 2326 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2327 Diag(OldLocation, PrevDiag); 2328 } else { 2329 Diag(New->getLocation(), diag::err_static_non_static) << New; 2330 Diag(OldLocation, PrevDiag); 2331 return true; 2332 } 2333 } 2334 2335 2336 // If a function is first declared with a calling convention, but is later 2337 // declared or defined without one, all following decls assume the calling 2338 // convention of the first. 2339 // 2340 // It's OK if a function is first declared without a calling convention, 2341 // but is later declared or defined with the default calling convention. 2342 // 2343 // To test if either decl has an explicit calling convention, we look for 2344 // AttributedType sugar nodes on the type as written. If they are missing or 2345 // were canonicalized away, we assume the calling convention was implicit. 2346 // 2347 // Note also that we DO NOT return at this point, because we still have 2348 // other tests to run. 2349 QualType OldQType = Context.getCanonicalType(Old->getType()); 2350 QualType NewQType = Context.getCanonicalType(New->getType()); 2351 const FunctionType *OldType = cast<FunctionType>(OldQType); 2352 const FunctionType *NewType = cast<FunctionType>(NewQType); 2353 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2354 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2355 bool RequiresAdjustment = false; 2356 2357 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2358 FunctionDecl *First = Old->getFirstDecl(); 2359 const FunctionType *FT = 2360 First->getType().getCanonicalType()->castAs<FunctionType>(); 2361 FunctionType::ExtInfo FI = FT->getExtInfo(); 2362 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2363 if (!NewCCExplicit) { 2364 // Inherit the CC from the previous declaration if it was specified 2365 // there but not here. 2366 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2367 RequiresAdjustment = true; 2368 } else { 2369 // Calling conventions aren't compatible, so complain. 2370 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2371 Diag(New->getLocation(), diag::err_cconv_change) 2372 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2373 << !FirstCCExplicit 2374 << (!FirstCCExplicit ? "" : 2375 FunctionType::getNameForCallConv(FI.getCC())); 2376 2377 // Put the note on the first decl, since it is the one that matters. 2378 Diag(First->getLocation(), diag::note_previous_declaration); 2379 return true; 2380 } 2381 } 2382 2383 // FIXME: diagnose the other way around? 2384 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2385 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2386 RequiresAdjustment = true; 2387 } 2388 2389 // Merge regparm attribute. 2390 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2391 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2392 if (NewTypeInfo.getHasRegParm()) { 2393 Diag(New->getLocation(), diag::err_regparm_mismatch) 2394 << NewType->getRegParmType() 2395 << OldType->getRegParmType(); 2396 Diag(OldLocation, diag::note_previous_declaration); 2397 return true; 2398 } 2399 2400 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2401 RequiresAdjustment = true; 2402 } 2403 2404 // Merge ns_returns_retained attribute. 2405 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2406 if (NewTypeInfo.getProducesResult()) { 2407 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2408 Diag(OldLocation, diag::note_previous_declaration); 2409 return true; 2410 } 2411 2412 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2413 RequiresAdjustment = true; 2414 } 2415 2416 if (RequiresAdjustment) { 2417 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2418 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2419 New->setType(QualType(AdjustedType, 0)); 2420 NewQType = Context.getCanonicalType(New->getType()); 2421 NewType = cast<FunctionType>(NewQType); 2422 } 2423 2424 // If this redeclaration makes the function inline, we may need to add it to 2425 // UndefinedButUsed. 2426 if (!Old->isInlined() && New->isInlined() && 2427 !New->hasAttr<GNUInlineAttr>() && 2428 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2429 Old->isUsed(false) && 2430 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2431 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2432 SourceLocation())); 2433 2434 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2435 // about it. 2436 if (New->hasAttr<GNUInlineAttr>() && 2437 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2438 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2439 } 2440 2441 if (getLangOpts().CPlusPlus) { 2442 // (C++98 13.1p2): 2443 // Certain function declarations cannot be overloaded: 2444 // -- Function declarations that differ only in the return type 2445 // cannot be overloaded. 2446 2447 // Go back to the type source info to compare the declared return types, 2448 // per C++1y [dcl.type.auto]p13: 2449 // Redeclarations or specializations of a function or function template 2450 // with a declared return type that uses a placeholder type shall also 2451 // use that placeholder, not a deduced type. 2452 QualType OldDeclaredReturnType = 2453 (Old->getTypeSourceInfo() 2454 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2455 : OldType)->getReturnType(); 2456 QualType NewDeclaredReturnType = 2457 (New->getTypeSourceInfo() 2458 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2459 : NewType)->getReturnType(); 2460 QualType ResQT; 2461 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2462 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2463 New->isLocalExternDecl())) { 2464 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2465 OldDeclaredReturnType->isObjCObjectPointerType()) 2466 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2467 if (ResQT.isNull()) { 2468 if (New->isCXXClassMember() && New->isOutOfLine()) 2469 Diag(New->getLocation(), 2470 diag::err_member_def_does_not_match_ret_type) << New; 2471 else 2472 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2473 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2474 return true; 2475 } 2476 else 2477 NewQType = ResQT; 2478 } 2479 2480 QualType OldReturnType = OldType->getReturnType(); 2481 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2482 if (OldReturnType != NewReturnType) { 2483 // If this function has a deduced return type and has already been 2484 // defined, copy the deduced value from the old declaration. 2485 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2486 if (OldAT && OldAT->isDeduced()) { 2487 New->setType( 2488 SubstAutoType(New->getType(), 2489 OldAT->isDependentType() ? Context.DependentTy 2490 : OldAT->getDeducedType())); 2491 NewQType = Context.getCanonicalType( 2492 SubstAutoType(NewQType, 2493 OldAT->isDependentType() ? Context.DependentTy 2494 : OldAT->getDeducedType())); 2495 } 2496 } 2497 2498 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2499 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2500 if (OldMethod && NewMethod) { 2501 // Preserve triviality. 2502 NewMethod->setTrivial(OldMethod->isTrivial()); 2503 2504 // MSVC allows explicit template specialization at class scope: 2505 // 2 CXXMethodDecls referring to the same function will be injected. 2506 // We don't want a redeclaration error. 2507 bool IsClassScopeExplicitSpecialization = 2508 OldMethod->isFunctionTemplateSpecialization() && 2509 NewMethod->isFunctionTemplateSpecialization(); 2510 bool isFriend = NewMethod->getFriendObjectKind(); 2511 2512 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2513 !IsClassScopeExplicitSpecialization) { 2514 // -- Member function declarations with the same name and the 2515 // same parameter types cannot be overloaded if any of them 2516 // is a static member function declaration. 2517 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2518 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2519 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2520 return true; 2521 } 2522 2523 // C++ [class.mem]p1: 2524 // [...] A member shall not be declared twice in the 2525 // member-specification, except that a nested class or member 2526 // class template can be declared and then later defined. 2527 if (ActiveTemplateInstantiations.empty()) { 2528 unsigned NewDiag; 2529 if (isa<CXXConstructorDecl>(OldMethod)) 2530 NewDiag = diag::err_constructor_redeclared; 2531 else if (isa<CXXDestructorDecl>(NewMethod)) 2532 NewDiag = diag::err_destructor_redeclared; 2533 else if (isa<CXXConversionDecl>(NewMethod)) 2534 NewDiag = diag::err_conv_function_redeclared; 2535 else 2536 NewDiag = diag::err_member_redeclared; 2537 2538 Diag(New->getLocation(), NewDiag); 2539 } else { 2540 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2541 << New << New->getType(); 2542 } 2543 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2544 2545 // Complain if this is an explicit declaration of a special 2546 // member that was initially declared implicitly. 2547 // 2548 // As an exception, it's okay to befriend such methods in order 2549 // to permit the implicit constructor/destructor/operator calls. 2550 } else if (OldMethod->isImplicit()) { 2551 if (isFriend) { 2552 NewMethod->setImplicit(); 2553 } else { 2554 Diag(NewMethod->getLocation(), 2555 diag::err_definition_of_implicitly_declared_member) 2556 << New << getSpecialMember(OldMethod); 2557 return true; 2558 } 2559 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2560 Diag(NewMethod->getLocation(), 2561 diag::err_definition_of_explicitly_defaulted_member) 2562 << getSpecialMember(OldMethod); 2563 return true; 2564 } 2565 } 2566 2567 // C++11 [dcl.attr.noreturn]p1: 2568 // The first declaration of a function shall specify the noreturn 2569 // attribute if any declaration of that function specifies the noreturn 2570 // attribute. 2571 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2572 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2573 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2574 Diag(Old->getFirstDecl()->getLocation(), 2575 diag::note_noreturn_missing_first_decl); 2576 } 2577 2578 // C++11 [dcl.attr.depend]p2: 2579 // The first declaration of a function shall specify the 2580 // carries_dependency attribute for its declarator-id if any declaration 2581 // of the function specifies the carries_dependency attribute. 2582 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2583 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2584 Diag(CDA->getLocation(), 2585 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2586 Diag(Old->getFirstDecl()->getLocation(), 2587 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2588 } 2589 2590 // (C++98 8.3.5p3): 2591 // All declarations for a function shall agree exactly in both the 2592 // return type and the parameter-type-list. 2593 // We also want to respect all the extended bits except noreturn. 2594 2595 // noreturn should now match unless the old type info didn't have it. 2596 QualType OldQTypeForComparison = OldQType; 2597 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2598 assert(OldQType == QualType(OldType, 0)); 2599 const FunctionType *OldTypeForComparison 2600 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2601 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2602 assert(OldQTypeForComparison.isCanonical()); 2603 } 2604 2605 if (haveIncompatibleLanguageLinkages(Old, New)) { 2606 // As a special case, retain the language linkage from previous 2607 // declarations of a friend function as an extension. 2608 // 2609 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2610 // and is useful because there's otherwise no way to specify language 2611 // linkage within class scope. 2612 // 2613 // Check cautiously as the friend object kind isn't yet complete. 2614 if (New->getFriendObjectKind() != Decl::FOK_None) { 2615 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2616 Diag(OldLocation, PrevDiag); 2617 } else { 2618 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2619 Diag(OldLocation, PrevDiag); 2620 return true; 2621 } 2622 } 2623 2624 if (OldQTypeForComparison == NewQType) 2625 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2626 2627 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2628 New->isLocalExternDecl()) { 2629 // It's OK if we couldn't merge types for a local function declaraton 2630 // if either the old or new type is dependent. We'll merge the types 2631 // when we instantiate the function. 2632 return false; 2633 } 2634 2635 // Fall through for conflicting redeclarations and redefinitions. 2636 } 2637 2638 // C: Function types need to be compatible, not identical. This handles 2639 // duplicate function decls like "void f(int); void f(enum X);" properly. 2640 if (!getLangOpts().CPlusPlus && 2641 Context.typesAreCompatible(OldQType, NewQType)) { 2642 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2643 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2644 const FunctionProtoType *OldProto = 0; 2645 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2646 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2647 // The old declaration provided a function prototype, but the 2648 // new declaration does not. Merge in the prototype. 2649 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2650 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2651 NewQType = 2652 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2653 OldProto->getExtProtoInfo()); 2654 New->setType(NewQType); 2655 New->setHasInheritedPrototype(); 2656 2657 // Synthesize a parameter for each argument type. 2658 SmallVector<ParmVarDecl*, 16> Params; 2659 for (const auto &ParamType : OldProto->param_types()) { 2660 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2661 SourceLocation(), 0, ParamType, 2662 /*TInfo=*/0, SC_None, 0); 2663 Param->setScopeInfo(0, Params.size()); 2664 Param->setImplicit(); 2665 Params.push_back(Param); 2666 } 2667 2668 New->setParams(Params); 2669 } 2670 2671 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2672 } 2673 2674 // GNU C permits a K&R definition to follow a prototype declaration 2675 // if the declared types of the parameters in the K&R definition 2676 // match the types in the prototype declaration, even when the 2677 // promoted types of the parameters from the K&R definition differ 2678 // from the types in the prototype. GCC then keeps the types from 2679 // the prototype. 2680 // 2681 // If a variadic prototype is followed by a non-variadic K&R definition, 2682 // the K&R definition becomes variadic. This is sort of an edge case, but 2683 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2684 // C99 6.9.1p8. 2685 if (!getLangOpts().CPlusPlus && 2686 Old->hasPrototype() && !New->hasPrototype() && 2687 New->getType()->getAs<FunctionProtoType>() && 2688 Old->getNumParams() == New->getNumParams()) { 2689 SmallVector<QualType, 16> ArgTypes; 2690 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2691 const FunctionProtoType *OldProto 2692 = Old->getType()->getAs<FunctionProtoType>(); 2693 const FunctionProtoType *NewProto 2694 = New->getType()->getAs<FunctionProtoType>(); 2695 2696 // Determine whether this is the GNU C extension. 2697 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2698 NewProto->getReturnType()); 2699 bool LooseCompatible = !MergedReturn.isNull(); 2700 for (unsigned Idx = 0, End = Old->getNumParams(); 2701 LooseCompatible && Idx != End; ++Idx) { 2702 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2703 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2704 if (Context.typesAreCompatible(OldParm->getType(), 2705 NewProto->getParamType(Idx))) { 2706 ArgTypes.push_back(NewParm->getType()); 2707 } else if (Context.typesAreCompatible(OldParm->getType(), 2708 NewParm->getType(), 2709 /*CompareUnqualified=*/true)) { 2710 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2711 NewProto->getParamType(Idx) }; 2712 Warnings.push_back(Warn); 2713 ArgTypes.push_back(NewParm->getType()); 2714 } else 2715 LooseCompatible = false; 2716 } 2717 2718 if (LooseCompatible) { 2719 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2720 Diag(Warnings[Warn].NewParm->getLocation(), 2721 diag::ext_param_promoted_not_compatible_with_prototype) 2722 << Warnings[Warn].PromotedType 2723 << Warnings[Warn].OldParm->getType(); 2724 if (Warnings[Warn].OldParm->getLocation().isValid()) 2725 Diag(Warnings[Warn].OldParm->getLocation(), 2726 diag::note_previous_declaration); 2727 } 2728 2729 if (MergeTypeWithOld) 2730 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2731 OldProto->getExtProtoInfo())); 2732 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2733 } 2734 2735 // Fall through to diagnose conflicting types. 2736 } 2737 2738 // A function that has already been declared has been redeclared or 2739 // defined with a different type; show an appropriate diagnostic. 2740 2741 // If the previous declaration was an implicitly-generated builtin 2742 // declaration, then at the very least we should use a specialized note. 2743 unsigned BuiltinID; 2744 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2745 // If it's actually a library-defined builtin function like 'malloc' 2746 // or 'printf', just warn about the incompatible redeclaration. 2747 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2748 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2749 Diag(OldLocation, diag::note_previous_builtin_declaration) 2750 << Old << Old->getType(); 2751 2752 // If this is a global redeclaration, just forget hereafter 2753 // about the "builtin-ness" of the function. 2754 // 2755 // Doing this for local extern declarations is problematic. If 2756 // the builtin declaration remains visible, a second invalid 2757 // local declaration will produce a hard error; if it doesn't 2758 // remain visible, a single bogus local redeclaration (which is 2759 // actually only a warning) could break all the downstream code. 2760 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2761 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2762 2763 return false; 2764 } 2765 2766 PrevDiag = diag::note_previous_builtin_declaration; 2767 } 2768 2769 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2770 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2771 return true; 2772 } 2773 2774 /// \brief Completes the merge of two function declarations that are 2775 /// known to be compatible. 2776 /// 2777 /// This routine handles the merging of attributes and other 2778 /// properties of function declarations from the old declaration to 2779 /// the new declaration, once we know that New is in fact a 2780 /// redeclaration of Old. 2781 /// 2782 /// \returns false 2783 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2784 Scope *S, bool MergeTypeWithOld) { 2785 // Merge the attributes 2786 mergeDeclAttributes(New, Old); 2787 2788 // Merge "pure" flag. 2789 if (Old->isPure()) 2790 New->setPure(); 2791 2792 // Merge "used" flag. 2793 if (Old->getMostRecentDecl()->isUsed(false)) 2794 New->setIsUsed(); 2795 2796 // Merge attributes from the parameters. These can mismatch with K&R 2797 // declarations. 2798 if (New->getNumParams() == Old->getNumParams()) 2799 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2800 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2801 *this); 2802 2803 if (getLangOpts().CPlusPlus) 2804 return MergeCXXFunctionDecl(New, Old, S); 2805 2806 // Merge the function types so the we get the composite types for the return 2807 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2808 // was visible. 2809 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2810 if (!Merged.isNull() && MergeTypeWithOld) 2811 New->setType(Merged); 2812 2813 return false; 2814 } 2815 2816 2817 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2818 ObjCMethodDecl *oldMethod) { 2819 2820 // Merge the attributes, including deprecated/unavailable 2821 AvailabilityMergeKind MergeKind = 2822 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2823 : AMK_Override; 2824 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2825 2826 // Merge attributes from the parameters. 2827 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2828 oe = oldMethod->param_end(); 2829 for (ObjCMethodDecl::param_iterator 2830 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2831 ni != ne && oi != oe; ++ni, ++oi) 2832 mergeParamDeclAttributes(*ni, *oi, *this); 2833 2834 CheckObjCMethodOverride(newMethod, oldMethod); 2835 } 2836 2837 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2838 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2839 /// emitting diagnostics as appropriate. 2840 /// 2841 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2842 /// to here in AddInitializerToDecl. We can't check them before the initializer 2843 /// is attached. 2844 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2845 bool MergeTypeWithOld) { 2846 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2847 return; 2848 2849 QualType MergedT; 2850 if (getLangOpts().CPlusPlus) { 2851 if (New->getType()->isUndeducedType()) { 2852 // We don't know what the new type is until the initializer is attached. 2853 return; 2854 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2855 // These could still be something that needs exception specs checked. 2856 return MergeVarDeclExceptionSpecs(New, Old); 2857 } 2858 // C++ [basic.link]p10: 2859 // [...] the types specified by all declarations referring to a given 2860 // object or function shall be identical, except that declarations for an 2861 // array object can specify array types that differ by the presence or 2862 // absence of a major array bound (8.3.4). 2863 else if (Old->getType()->isIncompleteArrayType() && 2864 New->getType()->isArrayType()) { 2865 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2866 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2867 if (Context.hasSameType(OldArray->getElementType(), 2868 NewArray->getElementType())) 2869 MergedT = New->getType(); 2870 } else if (Old->getType()->isArrayType() && 2871 New->getType()->isIncompleteArrayType()) { 2872 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2873 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2874 if (Context.hasSameType(OldArray->getElementType(), 2875 NewArray->getElementType())) 2876 MergedT = Old->getType(); 2877 } else if (New->getType()->isObjCObjectPointerType() && 2878 Old->getType()->isObjCObjectPointerType()) { 2879 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2880 Old->getType()); 2881 } 2882 } else { 2883 // C 6.2.7p2: 2884 // All declarations that refer to the same object or function shall have 2885 // compatible type. 2886 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2887 } 2888 if (MergedT.isNull()) { 2889 // It's OK if we couldn't merge types if either type is dependent, for a 2890 // block-scope variable. In other cases (static data members of class 2891 // templates, variable templates, ...), we require the types to be 2892 // equivalent. 2893 // FIXME: The C++ standard doesn't say anything about this. 2894 if ((New->getType()->isDependentType() || 2895 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2896 // If the old type was dependent, we can't merge with it, so the new type 2897 // becomes dependent for now. We'll reproduce the original type when we 2898 // instantiate the TypeSourceInfo for the variable. 2899 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2900 New->setType(Context.DependentTy); 2901 return; 2902 } 2903 2904 // FIXME: Even if this merging succeeds, some other non-visible declaration 2905 // of this variable might have an incompatible type. For instance: 2906 // 2907 // extern int arr[]; 2908 // void f() { extern int arr[2]; } 2909 // void g() { extern int arr[3]; } 2910 // 2911 // Neither C nor C++ requires a diagnostic for this, but we should still try 2912 // to diagnose it. 2913 Diag(New->getLocation(), diag::err_redefinition_different_type) 2914 << New->getDeclName() << New->getType() << Old->getType(); 2915 Diag(Old->getLocation(), diag::note_previous_definition); 2916 return New->setInvalidDecl(); 2917 } 2918 2919 // Don't actually update the type on the new declaration if the old 2920 // declaration was an extern declaration in a different scope. 2921 if (MergeTypeWithOld) 2922 New->setType(MergedT); 2923 } 2924 2925 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2926 LookupResult &Previous) { 2927 // C11 6.2.7p4: 2928 // For an identifier with internal or external linkage declared 2929 // in a scope in which a prior declaration of that identifier is 2930 // visible, if the prior declaration specifies internal or 2931 // external linkage, the type of the identifier at the later 2932 // declaration becomes the composite type. 2933 // 2934 // If the variable isn't visible, we do not merge with its type. 2935 if (Previous.isShadowed()) 2936 return false; 2937 2938 if (S.getLangOpts().CPlusPlus) { 2939 // C++11 [dcl.array]p3: 2940 // If there is a preceding declaration of the entity in the same 2941 // scope in which the bound was specified, an omitted array bound 2942 // is taken to be the same as in that earlier declaration. 2943 return NewVD->isPreviousDeclInSameBlockScope() || 2944 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2945 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2946 } else { 2947 // If the old declaration was function-local, don't merge with its 2948 // type unless we're in the same function. 2949 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2950 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2951 } 2952 } 2953 2954 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 2955 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 2956 /// situation, merging decls or emitting diagnostics as appropriate. 2957 /// 2958 /// Tentative definition rules (C99 6.9.2p2) are checked by 2959 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 2960 /// definitions here, since the initializer hasn't been attached. 2961 /// 2962 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 2963 // If the new decl is already invalid, don't do any other checking. 2964 if (New->isInvalidDecl()) 2965 return; 2966 2967 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 2968 2969 // Verify the old decl was also a variable or variable template. 2970 VarDecl *Old = 0; 2971 VarTemplateDecl *OldTemplate = 0; 2972 if (Previous.isSingleResult()) { 2973 if (NewTemplate) { 2974 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 2975 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0; 2976 } else 2977 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2978 } 2979 if (!Old) { 2980 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2981 << New->getDeclName(); 2982 Diag(Previous.getRepresentativeDecl()->getLocation(), 2983 diag::note_previous_definition); 2984 return New->setInvalidDecl(); 2985 } 2986 2987 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 2988 return; 2989 2990 // Ensure the template parameters are compatible. 2991 if (NewTemplate && 2992 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 2993 OldTemplate->getTemplateParameters(), 2994 /*Complain=*/true, TPL_TemplateMatch)) 2995 return; 2996 2997 // C++ [class.mem]p1: 2998 // A member shall not be declared twice in the member-specification [...] 2999 // 3000 // Here, we need only consider static data members. 3001 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3002 Diag(New->getLocation(), diag::err_duplicate_member) 3003 << New->getIdentifier(); 3004 Diag(Old->getLocation(), diag::note_previous_declaration); 3005 New->setInvalidDecl(); 3006 } 3007 3008 mergeDeclAttributes(New, Old); 3009 // Warn if an already-declared variable is made a weak_import in a subsequent 3010 // declaration 3011 if (New->hasAttr<WeakImportAttr>() && 3012 Old->getStorageClass() == SC_None && 3013 !Old->hasAttr<WeakImportAttr>()) { 3014 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3015 Diag(Old->getLocation(), diag::note_previous_definition); 3016 // Remove weak_import attribute on new declaration. 3017 New->dropAttr<WeakImportAttr>(); 3018 } 3019 3020 // Merge the types. 3021 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3022 3023 if (New->isInvalidDecl()) 3024 return; 3025 3026 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3027 if (New->getStorageClass() == SC_Static && 3028 !New->isStaticDataMember() && 3029 Old->hasExternalFormalLinkage()) { 3030 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3031 Diag(Old->getLocation(), diag::note_previous_definition); 3032 return New->setInvalidDecl(); 3033 } 3034 // C99 6.2.2p4: 3035 // For an identifier declared with the storage-class specifier 3036 // extern in a scope in which a prior declaration of that 3037 // identifier is visible,23) if the prior declaration specifies 3038 // internal or external linkage, the linkage of the identifier at 3039 // the later declaration is the same as the linkage specified at 3040 // the prior declaration. If no prior declaration is visible, or 3041 // if the prior declaration specifies no linkage, then the 3042 // identifier has external linkage. 3043 if (New->hasExternalStorage() && Old->hasLinkage()) 3044 /* Okay */; 3045 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3046 !New->isStaticDataMember() && 3047 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3048 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3049 Diag(Old->getLocation(), diag::note_previous_definition); 3050 return New->setInvalidDecl(); 3051 } 3052 3053 // Check if extern is followed by non-extern and vice-versa. 3054 if (New->hasExternalStorage() && 3055 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3056 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3057 Diag(Old->getLocation(), diag::note_previous_definition); 3058 return New->setInvalidDecl(); 3059 } 3060 if (Old->hasLinkage() && New->isLocalVarDecl() && 3061 !New->hasExternalStorage()) { 3062 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3063 Diag(Old->getLocation(), diag::note_previous_definition); 3064 return New->setInvalidDecl(); 3065 } 3066 3067 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3068 3069 // FIXME: The test for external storage here seems wrong? We still 3070 // need to check for mismatches. 3071 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3072 // Don't complain about out-of-line definitions of static members. 3073 !(Old->getLexicalDeclContext()->isRecord() && 3074 !New->getLexicalDeclContext()->isRecord())) { 3075 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3076 Diag(Old->getLocation(), diag::note_previous_definition); 3077 return New->setInvalidDecl(); 3078 } 3079 3080 if (New->getTLSKind() != Old->getTLSKind()) { 3081 if (!Old->getTLSKind()) { 3082 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3083 Diag(Old->getLocation(), diag::note_previous_declaration); 3084 } else if (!New->getTLSKind()) { 3085 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3086 Diag(Old->getLocation(), diag::note_previous_declaration); 3087 } else { 3088 // Do not allow redeclaration to change the variable between requiring 3089 // static and dynamic initialization. 3090 // FIXME: GCC allows this, but uses the TLS keyword on the first 3091 // declaration to determine the kind. Do we need to be compatible here? 3092 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3093 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3094 Diag(Old->getLocation(), diag::note_previous_declaration); 3095 } 3096 } 3097 3098 // C++ doesn't have tentative definitions, so go right ahead and check here. 3099 const VarDecl *Def; 3100 if (getLangOpts().CPlusPlus && 3101 New->isThisDeclarationADefinition() == VarDecl::Definition && 3102 (Def = Old->getDefinition())) { 3103 Diag(New->getLocation(), diag::err_redefinition) << New; 3104 Diag(Def->getLocation(), diag::note_previous_definition); 3105 New->setInvalidDecl(); 3106 return; 3107 } 3108 3109 if (haveIncompatibleLanguageLinkages(Old, New)) { 3110 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3111 Diag(Old->getLocation(), diag::note_previous_definition); 3112 New->setInvalidDecl(); 3113 return; 3114 } 3115 3116 // Merge "used" flag. 3117 if (Old->getMostRecentDecl()->isUsed(false)) 3118 New->setIsUsed(); 3119 3120 // Keep a chain of previous declarations. 3121 New->setPreviousDecl(Old); 3122 if (NewTemplate) 3123 NewTemplate->setPreviousDecl(OldTemplate); 3124 3125 // Inherit access appropriately. 3126 New->setAccess(Old->getAccess()); 3127 if (NewTemplate) 3128 NewTemplate->setAccess(New->getAccess()); 3129 } 3130 3131 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3132 /// no declarator (e.g. "struct foo;") is parsed. 3133 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3134 DeclSpec &DS) { 3135 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3136 } 3137 3138 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3139 if (!S.Context.getLangOpts().CPlusPlus) 3140 return; 3141 3142 if (isa<CXXRecordDecl>(Tag->getParent())) { 3143 // If this tag is the direct child of a class, number it if 3144 // it is anonymous. 3145 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3146 return; 3147 MangleNumberingContext &MCtx = 3148 S.Context.getManglingNumberContext(Tag->getParent()); 3149 S.Context.setManglingNumber( 3150 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3151 return; 3152 } 3153 3154 // If this tag isn't a direct child of a class, number it if it is local. 3155 Decl *ManglingContextDecl; 3156 if (MangleNumberingContext *MCtx = 3157 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3158 ManglingContextDecl)) { 3159 S.Context.setManglingNumber( 3160 Tag, 3161 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3162 } 3163 } 3164 3165 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3166 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3167 /// parameters to cope with template friend declarations. 3168 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3169 DeclSpec &DS, 3170 MultiTemplateParamsArg TemplateParams, 3171 bool IsExplicitInstantiation) { 3172 Decl *TagD = 0; 3173 TagDecl *Tag = 0; 3174 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3175 DS.getTypeSpecType() == DeclSpec::TST_struct || 3176 DS.getTypeSpecType() == DeclSpec::TST_interface || 3177 DS.getTypeSpecType() == DeclSpec::TST_union || 3178 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3179 TagD = DS.getRepAsDecl(); 3180 3181 if (!TagD) // We probably had an error 3182 return 0; 3183 3184 // Note that the above type specs guarantee that the 3185 // type rep is a Decl, whereas in many of the others 3186 // it's a Type. 3187 if (isa<TagDecl>(TagD)) 3188 Tag = cast<TagDecl>(TagD); 3189 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3190 Tag = CTD->getTemplatedDecl(); 3191 } 3192 3193 if (Tag) { 3194 HandleTagNumbering(*this, Tag, S); 3195 Tag->setFreeStanding(); 3196 if (Tag->isInvalidDecl()) 3197 return Tag; 3198 } 3199 3200 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3201 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3202 // or incomplete types shall not be restrict-qualified." 3203 if (TypeQuals & DeclSpec::TQ_restrict) 3204 Diag(DS.getRestrictSpecLoc(), 3205 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3206 << DS.getSourceRange(); 3207 } 3208 3209 if (DS.isConstexprSpecified()) { 3210 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3211 // and definitions of functions and variables. 3212 if (Tag) 3213 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3214 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3215 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3216 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3217 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3218 else 3219 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3220 // Don't emit warnings after this error. 3221 return TagD; 3222 } 3223 3224 DiagnoseFunctionSpecifiers(DS); 3225 3226 if (DS.isFriendSpecified()) { 3227 // If we're dealing with a decl but not a TagDecl, assume that 3228 // whatever routines created it handled the friendship aspect. 3229 if (TagD && !Tag) 3230 return 0; 3231 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3232 } 3233 3234 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3235 bool IsExplicitSpecialization = 3236 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3237 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3238 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3239 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3240 // nested-name-specifier unless it is an explicit instantiation 3241 // or an explicit specialization. 3242 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3243 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3244 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3245 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3246 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3247 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3248 << SS.getRange(); 3249 return 0; 3250 } 3251 3252 // Track whether this decl-specifier declares anything. 3253 bool DeclaresAnything = true; 3254 3255 // Handle anonymous struct definitions. 3256 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3257 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3258 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3259 if (getLangOpts().CPlusPlus || 3260 Record->getDeclContext()->isRecord()) 3261 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3262 3263 DeclaresAnything = false; 3264 } 3265 } 3266 3267 // Check for Microsoft C extension: anonymous struct member. 3268 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3269 CurContext->isRecord() && 3270 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3271 // Handle 2 kinds of anonymous struct: 3272 // struct STRUCT; 3273 // and 3274 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3275 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3276 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3277 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3278 DS.getRepAsType().get()->isStructureType())) { 3279 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3280 << DS.getSourceRange(); 3281 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3282 } 3283 } 3284 3285 // Skip all the checks below if we have a type error. 3286 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3287 (TagD && TagD->isInvalidDecl())) 3288 return TagD; 3289 3290 if (getLangOpts().CPlusPlus && 3291 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3292 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3293 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3294 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3295 DeclaresAnything = false; 3296 3297 if (!DS.isMissingDeclaratorOk()) { 3298 // Customize diagnostic for a typedef missing a name. 3299 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3300 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3301 << DS.getSourceRange(); 3302 else 3303 DeclaresAnything = false; 3304 } 3305 3306 if (DS.isModulePrivateSpecified() && 3307 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3308 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3309 << Tag->getTagKind() 3310 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3311 3312 ActOnDocumentableDecl(TagD); 3313 3314 // C 6.7/2: 3315 // A declaration [...] shall declare at least a declarator [...], a tag, 3316 // or the members of an enumeration. 3317 // C++ [dcl.dcl]p3: 3318 // [If there are no declarators], and except for the declaration of an 3319 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3320 // names into the program, or shall redeclare a name introduced by a 3321 // previous declaration. 3322 if (!DeclaresAnything) { 3323 // In C, we allow this as a (popular) extension / bug. Don't bother 3324 // producing further diagnostics for redundant qualifiers after this. 3325 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3326 return TagD; 3327 } 3328 3329 // C++ [dcl.stc]p1: 3330 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3331 // init-declarator-list of the declaration shall not be empty. 3332 // C++ [dcl.fct.spec]p1: 3333 // If a cv-qualifier appears in a decl-specifier-seq, the 3334 // init-declarator-list of the declaration shall not be empty. 3335 // 3336 // Spurious qualifiers here appear to be valid in C. 3337 unsigned DiagID = diag::warn_standalone_specifier; 3338 if (getLangOpts().CPlusPlus) 3339 DiagID = diag::ext_standalone_specifier; 3340 3341 // Note that a linkage-specification sets a storage class, but 3342 // 'extern "C" struct foo;' is actually valid and not theoretically 3343 // useless. 3344 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) 3345 if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3346 Diag(DS.getStorageClassSpecLoc(), DiagID) 3347 << DeclSpec::getSpecifierName(SCS); 3348 3349 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3350 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3351 << DeclSpec::getSpecifierName(TSCS); 3352 if (DS.getTypeQualifiers()) { 3353 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3354 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3355 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3356 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3357 // Restrict is covered above. 3358 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3359 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3360 } 3361 3362 // Warn about ignored type attributes, for example: 3363 // __attribute__((aligned)) struct A; 3364 // Attributes should be placed after tag to apply to type declaration. 3365 if (!DS.getAttributes().empty()) { 3366 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3367 if (TypeSpecType == DeclSpec::TST_class || 3368 TypeSpecType == DeclSpec::TST_struct || 3369 TypeSpecType == DeclSpec::TST_interface || 3370 TypeSpecType == DeclSpec::TST_union || 3371 TypeSpecType == DeclSpec::TST_enum) { 3372 AttributeList* attrs = DS.getAttributes().getList(); 3373 while (attrs) { 3374 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3375 << attrs->getName() 3376 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3377 TypeSpecType == DeclSpec::TST_struct ? 1 : 3378 TypeSpecType == DeclSpec::TST_union ? 2 : 3379 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3380 attrs = attrs->getNext(); 3381 } 3382 } 3383 } 3384 3385 return TagD; 3386 } 3387 3388 /// We are trying to inject an anonymous member into the given scope; 3389 /// check if there's an existing declaration that can't be overloaded. 3390 /// 3391 /// \return true if this is a forbidden redeclaration 3392 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3393 Scope *S, 3394 DeclContext *Owner, 3395 DeclarationName Name, 3396 SourceLocation NameLoc, 3397 unsigned diagnostic) { 3398 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3399 Sema::ForRedeclaration); 3400 if (!SemaRef.LookupName(R, S)) return false; 3401 3402 if (R.getAsSingle<TagDecl>()) 3403 return false; 3404 3405 // Pick a representative declaration. 3406 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3407 assert(PrevDecl && "Expected a non-null Decl"); 3408 3409 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3410 return false; 3411 3412 SemaRef.Diag(NameLoc, diagnostic) << Name; 3413 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3414 3415 return true; 3416 } 3417 3418 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3419 /// anonymous struct or union AnonRecord into the owning context Owner 3420 /// and scope S. This routine will be invoked just after we realize 3421 /// that an unnamed union or struct is actually an anonymous union or 3422 /// struct, e.g., 3423 /// 3424 /// @code 3425 /// union { 3426 /// int i; 3427 /// float f; 3428 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3429 /// // f into the surrounding scope.x 3430 /// @endcode 3431 /// 3432 /// This routine is recursive, injecting the names of nested anonymous 3433 /// structs/unions into the owning context and scope as well. 3434 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3435 DeclContext *Owner, 3436 RecordDecl *AnonRecord, 3437 AccessSpecifier AS, 3438 SmallVectorImpl<NamedDecl *> &Chaining, 3439 bool MSAnonStruct) { 3440 unsigned diagKind 3441 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3442 : diag::err_anonymous_struct_member_redecl; 3443 3444 bool Invalid = false; 3445 3446 // Look every FieldDecl and IndirectFieldDecl with a name. 3447 for (auto *D : AnonRecord->decls()) { 3448 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3449 cast<NamedDecl>(D)->getDeclName()) { 3450 ValueDecl *VD = cast<ValueDecl>(D); 3451 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3452 VD->getLocation(), diagKind)) { 3453 // C++ [class.union]p2: 3454 // The names of the members of an anonymous union shall be 3455 // distinct from the names of any other entity in the 3456 // scope in which the anonymous union is declared. 3457 Invalid = true; 3458 } else { 3459 // C++ [class.union]p2: 3460 // For the purpose of name lookup, after the anonymous union 3461 // definition, the members of the anonymous union are 3462 // considered to have been defined in the scope in which the 3463 // anonymous union is declared. 3464 unsigned OldChainingSize = Chaining.size(); 3465 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3466 for (auto *PI : IF->chain()) 3467 Chaining.push_back(PI); 3468 else 3469 Chaining.push_back(VD); 3470 3471 assert(Chaining.size() >= 2); 3472 NamedDecl **NamedChain = 3473 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3474 for (unsigned i = 0; i < Chaining.size(); i++) 3475 NamedChain[i] = Chaining[i]; 3476 3477 IndirectFieldDecl* IndirectField = 3478 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3479 VD->getIdentifier(), VD->getType(), 3480 NamedChain, Chaining.size()); 3481 3482 IndirectField->setAccess(AS); 3483 IndirectField->setImplicit(); 3484 SemaRef.PushOnScopeChains(IndirectField, S); 3485 3486 // That includes picking up the appropriate access specifier. 3487 if (AS != AS_none) IndirectField->setAccess(AS); 3488 3489 Chaining.resize(OldChainingSize); 3490 } 3491 } 3492 } 3493 3494 return Invalid; 3495 } 3496 3497 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3498 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3499 /// illegal input values are mapped to SC_None. 3500 static StorageClass 3501 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3502 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3503 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3504 "Parser allowed 'typedef' as storage class VarDecl."); 3505 switch (StorageClassSpec) { 3506 case DeclSpec::SCS_unspecified: return SC_None; 3507 case DeclSpec::SCS_extern: 3508 if (DS.isExternInLinkageSpec()) 3509 return SC_None; 3510 return SC_Extern; 3511 case DeclSpec::SCS_static: return SC_Static; 3512 case DeclSpec::SCS_auto: return SC_Auto; 3513 case DeclSpec::SCS_register: return SC_Register; 3514 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3515 // Illegal SCSs map to None: error reporting is up to the caller. 3516 case DeclSpec::SCS_mutable: // Fall through. 3517 case DeclSpec::SCS_typedef: return SC_None; 3518 } 3519 llvm_unreachable("unknown storage class specifier"); 3520 } 3521 3522 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3523 assert(Record->hasInClassInitializer()); 3524 3525 for (const auto *I : Record->decls()) { 3526 const auto *FD = dyn_cast<FieldDecl>(I); 3527 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3528 FD = IFD->getAnonField(); 3529 if (FD && FD->hasInClassInitializer()) 3530 return FD->getLocation(); 3531 } 3532 3533 llvm_unreachable("couldn't find in-class initializer"); 3534 } 3535 3536 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3537 SourceLocation DefaultInitLoc) { 3538 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3539 return; 3540 3541 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3542 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3543 } 3544 3545 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3546 CXXRecordDecl *AnonUnion) { 3547 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3548 return; 3549 3550 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3551 } 3552 3553 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3554 /// anonymous structure or union. Anonymous unions are a C++ feature 3555 /// (C++ [class.union]) and a C11 feature; anonymous structures 3556 /// are a C11 feature and GNU C++ extension. 3557 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3558 AccessSpecifier AS, 3559 RecordDecl *Record, 3560 const PrintingPolicy &Policy) { 3561 DeclContext *Owner = Record->getDeclContext(); 3562 3563 // Diagnose whether this anonymous struct/union is an extension. 3564 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3565 Diag(Record->getLocation(), diag::ext_anonymous_union); 3566 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3567 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3568 else if (!Record->isUnion() && !getLangOpts().C11) 3569 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3570 3571 // C and C++ require different kinds of checks for anonymous 3572 // structs/unions. 3573 bool Invalid = false; 3574 if (getLangOpts().CPlusPlus) { 3575 const char* PrevSpec = 0; 3576 unsigned DiagID; 3577 if (Record->isUnion()) { 3578 // C++ [class.union]p6: 3579 // Anonymous unions declared in a named namespace or in the 3580 // global namespace shall be declared static. 3581 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3582 (isa<TranslationUnitDecl>(Owner) || 3583 (isa<NamespaceDecl>(Owner) && 3584 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3585 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3586 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3587 3588 // Recover by adding 'static'. 3589 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3590 PrevSpec, DiagID, Policy); 3591 } 3592 // C++ [class.union]p6: 3593 // A storage class is not allowed in a declaration of an 3594 // anonymous union in a class scope. 3595 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3596 isa<RecordDecl>(Owner)) { 3597 Diag(DS.getStorageClassSpecLoc(), 3598 diag::err_anonymous_union_with_storage_spec) 3599 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3600 3601 // Recover by removing the storage specifier. 3602 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3603 SourceLocation(), 3604 PrevSpec, DiagID, Context.getPrintingPolicy()); 3605 } 3606 } 3607 3608 // Ignore const/volatile/restrict qualifiers. 3609 if (DS.getTypeQualifiers()) { 3610 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3611 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3612 << Record->isUnion() << "const" 3613 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3614 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3615 Diag(DS.getVolatileSpecLoc(), 3616 diag::ext_anonymous_struct_union_qualified) 3617 << Record->isUnion() << "volatile" 3618 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3619 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3620 Diag(DS.getRestrictSpecLoc(), 3621 diag::ext_anonymous_struct_union_qualified) 3622 << Record->isUnion() << "restrict" 3623 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3624 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3625 Diag(DS.getAtomicSpecLoc(), 3626 diag::ext_anonymous_struct_union_qualified) 3627 << Record->isUnion() << "_Atomic" 3628 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3629 3630 DS.ClearTypeQualifiers(); 3631 } 3632 3633 // C++ [class.union]p2: 3634 // The member-specification of an anonymous union shall only 3635 // define non-static data members. [Note: nested types and 3636 // functions cannot be declared within an anonymous union. ] 3637 for (auto *Mem : Record->decls()) { 3638 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3639 // C++ [class.union]p3: 3640 // An anonymous union shall not have private or protected 3641 // members (clause 11). 3642 assert(FD->getAccess() != AS_none); 3643 if (FD->getAccess() != AS_public) { 3644 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3645 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3646 Invalid = true; 3647 } 3648 3649 // C++ [class.union]p1 3650 // An object of a class with a non-trivial constructor, a non-trivial 3651 // copy constructor, a non-trivial destructor, or a non-trivial copy 3652 // assignment operator cannot be a member of a union, nor can an 3653 // array of such objects. 3654 if (CheckNontrivialField(FD)) 3655 Invalid = true; 3656 } else if (Mem->isImplicit()) { 3657 // Any implicit members are fine. 3658 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3659 // This is a type that showed up in an 3660 // elaborated-type-specifier inside the anonymous struct or 3661 // union, but which actually declares a type outside of the 3662 // anonymous struct or union. It's okay. 3663 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3664 if (!MemRecord->isAnonymousStructOrUnion() && 3665 MemRecord->getDeclName()) { 3666 // Visual C++ allows type definition in anonymous struct or union. 3667 if (getLangOpts().MicrosoftExt) 3668 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3669 << (int)Record->isUnion(); 3670 else { 3671 // This is a nested type declaration. 3672 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3673 << (int)Record->isUnion(); 3674 Invalid = true; 3675 } 3676 } else { 3677 // This is an anonymous type definition within another anonymous type. 3678 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3679 // not part of standard C++. 3680 Diag(MemRecord->getLocation(), 3681 diag::ext_anonymous_record_with_anonymous_type) 3682 << (int)Record->isUnion(); 3683 } 3684 } else if (isa<AccessSpecDecl>(Mem)) { 3685 // Any access specifier is fine. 3686 } else { 3687 // We have something that isn't a non-static data 3688 // member. Complain about it. 3689 unsigned DK = diag::err_anonymous_record_bad_member; 3690 if (isa<TypeDecl>(Mem)) 3691 DK = diag::err_anonymous_record_with_type; 3692 else if (isa<FunctionDecl>(Mem)) 3693 DK = diag::err_anonymous_record_with_function; 3694 else if (isa<VarDecl>(Mem)) 3695 DK = diag::err_anonymous_record_with_static; 3696 3697 // Visual C++ allows type definition in anonymous struct or union. 3698 if (getLangOpts().MicrosoftExt && 3699 DK == diag::err_anonymous_record_with_type) 3700 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3701 << (int)Record->isUnion(); 3702 else { 3703 Diag(Mem->getLocation(), DK) 3704 << (int)Record->isUnion(); 3705 Invalid = true; 3706 } 3707 } 3708 } 3709 3710 // C++11 [class.union]p8 (DR1460): 3711 // At most one variant member of a union may have a 3712 // brace-or-equal-initializer. 3713 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3714 Owner->isRecord()) 3715 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3716 cast<CXXRecordDecl>(Record)); 3717 } 3718 3719 if (!Record->isUnion() && !Owner->isRecord()) { 3720 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3721 << (int)getLangOpts().CPlusPlus; 3722 Invalid = true; 3723 } 3724 3725 // Mock up a declarator. 3726 Declarator Dc(DS, Declarator::MemberContext); 3727 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3728 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3729 3730 // Create a declaration for this anonymous struct/union. 3731 NamedDecl *Anon = 0; 3732 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3733 Anon = FieldDecl::Create(Context, OwningClass, 3734 DS.getLocStart(), 3735 Record->getLocation(), 3736 /*IdentifierInfo=*/0, 3737 Context.getTypeDeclType(Record), 3738 TInfo, 3739 /*BitWidth=*/0, /*Mutable=*/false, 3740 /*InitStyle=*/ICIS_NoInit); 3741 Anon->setAccess(AS); 3742 if (getLangOpts().CPlusPlus) 3743 FieldCollector->Add(cast<FieldDecl>(Anon)); 3744 } else { 3745 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3746 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3747 if (SCSpec == DeclSpec::SCS_mutable) { 3748 // mutable can only appear on non-static class members, so it's always 3749 // an error here 3750 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3751 Invalid = true; 3752 SC = SC_None; 3753 } 3754 3755 Anon = VarDecl::Create(Context, Owner, 3756 DS.getLocStart(), 3757 Record->getLocation(), /*IdentifierInfo=*/0, 3758 Context.getTypeDeclType(Record), 3759 TInfo, SC); 3760 3761 // Default-initialize the implicit variable. This initialization will be 3762 // trivial in almost all cases, except if a union member has an in-class 3763 // initializer: 3764 // union { int n = 0; }; 3765 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3766 } 3767 Anon->setImplicit(); 3768 3769 // Mark this as an anonymous struct/union type. 3770 Record->setAnonymousStructOrUnion(true); 3771 3772 // Add the anonymous struct/union object to the current 3773 // context. We'll be referencing this object when we refer to one of 3774 // its members. 3775 Owner->addDecl(Anon); 3776 3777 // Inject the members of the anonymous struct/union into the owning 3778 // context and into the identifier resolver chain for name lookup 3779 // purposes. 3780 SmallVector<NamedDecl*, 2> Chain; 3781 Chain.push_back(Anon); 3782 3783 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3784 Chain, false)) 3785 Invalid = true; 3786 3787 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3788 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3789 Decl *ManglingContextDecl; 3790 if (MangleNumberingContext *MCtx = 3791 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3792 ManglingContextDecl)) { 3793 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3794 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3795 } 3796 } 3797 } 3798 3799 if (Invalid) 3800 Anon->setInvalidDecl(); 3801 3802 return Anon; 3803 } 3804 3805 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3806 /// Microsoft C anonymous structure. 3807 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3808 /// Example: 3809 /// 3810 /// struct A { int a; }; 3811 /// struct B { struct A; int b; }; 3812 /// 3813 /// void foo() { 3814 /// B var; 3815 /// var.a = 3; 3816 /// } 3817 /// 3818 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3819 RecordDecl *Record) { 3820 3821 // If there is no Record, get the record via the typedef. 3822 if (!Record) 3823 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3824 3825 // Mock up a declarator. 3826 Declarator Dc(DS, Declarator::TypeNameContext); 3827 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3828 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3829 3830 // Create a declaration for this anonymous struct. 3831 NamedDecl* Anon = FieldDecl::Create(Context, 3832 cast<RecordDecl>(CurContext), 3833 DS.getLocStart(), 3834 DS.getLocStart(), 3835 /*IdentifierInfo=*/0, 3836 Context.getTypeDeclType(Record), 3837 TInfo, 3838 /*BitWidth=*/0, /*Mutable=*/false, 3839 /*InitStyle=*/ICIS_NoInit); 3840 Anon->setImplicit(); 3841 3842 // Add the anonymous struct object to the current context. 3843 CurContext->addDecl(Anon); 3844 3845 // Inject the members of the anonymous struct into the current 3846 // context and into the identifier resolver chain for name lookup 3847 // purposes. 3848 SmallVector<NamedDecl*, 2> Chain; 3849 Chain.push_back(Anon); 3850 3851 RecordDecl *RecordDef = Record->getDefinition(); 3852 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3853 RecordDef, AS_none, 3854 Chain, true)) 3855 Anon->setInvalidDecl(); 3856 3857 return Anon; 3858 } 3859 3860 /// GetNameForDeclarator - Determine the full declaration name for the 3861 /// given Declarator. 3862 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3863 return GetNameFromUnqualifiedId(D.getName()); 3864 } 3865 3866 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3867 DeclarationNameInfo 3868 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3869 DeclarationNameInfo NameInfo; 3870 NameInfo.setLoc(Name.StartLocation); 3871 3872 switch (Name.getKind()) { 3873 3874 case UnqualifiedId::IK_ImplicitSelfParam: 3875 case UnqualifiedId::IK_Identifier: 3876 NameInfo.setName(Name.Identifier); 3877 NameInfo.setLoc(Name.StartLocation); 3878 return NameInfo; 3879 3880 case UnqualifiedId::IK_OperatorFunctionId: 3881 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3882 Name.OperatorFunctionId.Operator)); 3883 NameInfo.setLoc(Name.StartLocation); 3884 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3885 = Name.OperatorFunctionId.SymbolLocations[0]; 3886 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3887 = Name.EndLocation.getRawEncoding(); 3888 return NameInfo; 3889 3890 case UnqualifiedId::IK_LiteralOperatorId: 3891 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3892 Name.Identifier)); 3893 NameInfo.setLoc(Name.StartLocation); 3894 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3895 return NameInfo; 3896 3897 case UnqualifiedId::IK_ConversionFunctionId: { 3898 TypeSourceInfo *TInfo; 3899 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3900 if (Ty.isNull()) 3901 return DeclarationNameInfo(); 3902 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3903 Context.getCanonicalType(Ty))); 3904 NameInfo.setLoc(Name.StartLocation); 3905 NameInfo.setNamedTypeInfo(TInfo); 3906 return NameInfo; 3907 } 3908 3909 case UnqualifiedId::IK_ConstructorName: { 3910 TypeSourceInfo *TInfo; 3911 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3912 if (Ty.isNull()) 3913 return DeclarationNameInfo(); 3914 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3915 Context.getCanonicalType(Ty))); 3916 NameInfo.setLoc(Name.StartLocation); 3917 NameInfo.setNamedTypeInfo(TInfo); 3918 return NameInfo; 3919 } 3920 3921 case UnqualifiedId::IK_ConstructorTemplateId: { 3922 // In well-formed code, we can only have a constructor 3923 // template-id that refers to the current context, so go there 3924 // to find the actual type being constructed. 3925 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3926 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3927 return DeclarationNameInfo(); 3928 3929 // Determine the type of the class being constructed. 3930 QualType CurClassType = Context.getTypeDeclType(CurClass); 3931 3932 // FIXME: Check two things: that the template-id names the same type as 3933 // CurClassType, and that the template-id does not occur when the name 3934 // was qualified. 3935 3936 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3937 Context.getCanonicalType(CurClassType))); 3938 NameInfo.setLoc(Name.StartLocation); 3939 // FIXME: should we retrieve TypeSourceInfo? 3940 NameInfo.setNamedTypeInfo(0); 3941 return NameInfo; 3942 } 3943 3944 case UnqualifiedId::IK_DestructorName: { 3945 TypeSourceInfo *TInfo; 3946 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3947 if (Ty.isNull()) 3948 return DeclarationNameInfo(); 3949 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 3950 Context.getCanonicalType(Ty))); 3951 NameInfo.setLoc(Name.StartLocation); 3952 NameInfo.setNamedTypeInfo(TInfo); 3953 return NameInfo; 3954 } 3955 3956 case UnqualifiedId::IK_TemplateId: { 3957 TemplateName TName = Name.TemplateId->Template.get(); 3958 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 3959 return Context.getNameForTemplate(TName, TNameLoc); 3960 } 3961 3962 } // switch (Name.getKind()) 3963 3964 llvm_unreachable("Unknown name kind"); 3965 } 3966 3967 static QualType getCoreType(QualType Ty) { 3968 do { 3969 if (Ty->isPointerType() || Ty->isReferenceType()) 3970 Ty = Ty->getPointeeType(); 3971 else if (Ty->isArrayType()) 3972 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 3973 else 3974 return Ty.withoutLocalFastQualifiers(); 3975 } while (true); 3976 } 3977 3978 /// hasSimilarParameters - Determine whether the C++ functions Declaration 3979 /// and Definition have "nearly" matching parameters. This heuristic is 3980 /// used to improve diagnostics in the case where an out-of-line function 3981 /// definition doesn't match any declaration within the class or namespace. 3982 /// Also sets Params to the list of indices to the parameters that differ 3983 /// between the declaration and the definition. If hasSimilarParameters 3984 /// returns true and Params is empty, then all of the parameters match. 3985 static bool hasSimilarParameters(ASTContext &Context, 3986 FunctionDecl *Declaration, 3987 FunctionDecl *Definition, 3988 SmallVectorImpl<unsigned> &Params) { 3989 Params.clear(); 3990 if (Declaration->param_size() != Definition->param_size()) 3991 return false; 3992 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 3993 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 3994 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 3995 3996 // The parameter types are identical 3997 if (Context.hasSameType(DefParamTy, DeclParamTy)) 3998 continue; 3999 4000 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4001 QualType DefParamBaseTy = getCoreType(DefParamTy); 4002 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4003 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4004 4005 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4006 (DeclTyName && DeclTyName == DefTyName)) 4007 Params.push_back(Idx); 4008 else // The two parameters aren't even close 4009 return false; 4010 } 4011 4012 return true; 4013 } 4014 4015 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4016 /// declarator needs to be rebuilt in the current instantiation. 4017 /// Any bits of declarator which appear before the name are valid for 4018 /// consideration here. That's specifically the type in the decl spec 4019 /// and the base type in any member-pointer chunks. 4020 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4021 DeclarationName Name) { 4022 // The types we specifically need to rebuild are: 4023 // - typenames, typeofs, and decltypes 4024 // - types which will become injected class names 4025 // Of course, we also need to rebuild any type referencing such a 4026 // type. It's safest to just say "dependent", but we call out a 4027 // few cases here. 4028 4029 DeclSpec &DS = D.getMutableDeclSpec(); 4030 switch (DS.getTypeSpecType()) { 4031 case DeclSpec::TST_typename: 4032 case DeclSpec::TST_typeofType: 4033 case DeclSpec::TST_underlyingType: 4034 case DeclSpec::TST_atomic: { 4035 // Grab the type from the parser. 4036 TypeSourceInfo *TSI = 0; 4037 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4038 if (T.isNull() || !T->isDependentType()) break; 4039 4040 // Make sure there's a type source info. This isn't really much 4041 // of a waste; most dependent types should have type source info 4042 // attached already. 4043 if (!TSI) 4044 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4045 4046 // Rebuild the type in the current instantiation. 4047 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4048 if (!TSI) return true; 4049 4050 // Store the new type back in the decl spec. 4051 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4052 DS.UpdateTypeRep(LocType); 4053 break; 4054 } 4055 4056 case DeclSpec::TST_decltype: 4057 case DeclSpec::TST_typeofExpr: { 4058 Expr *E = DS.getRepAsExpr(); 4059 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4060 if (Result.isInvalid()) return true; 4061 DS.UpdateExprRep(Result.get()); 4062 break; 4063 } 4064 4065 default: 4066 // Nothing to do for these decl specs. 4067 break; 4068 } 4069 4070 // It doesn't matter what order we do this in. 4071 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4072 DeclaratorChunk &Chunk = D.getTypeObject(I); 4073 4074 // The only type information in the declarator which can come 4075 // before the declaration name is the base type of a member 4076 // pointer. 4077 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4078 continue; 4079 4080 // Rebuild the scope specifier in-place. 4081 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4082 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4083 return true; 4084 } 4085 4086 return false; 4087 } 4088 4089 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4090 D.setFunctionDefinitionKind(FDK_Declaration); 4091 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4092 4093 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4094 Dcl && Dcl->getDeclContext()->isFileContext()) 4095 Dcl->setTopLevelDeclInObjCContainer(); 4096 4097 return Dcl; 4098 } 4099 4100 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4101 /// If T is the name of a class, then each of the following shall have a 4102 /// name different from T: 4103 /// - every static data member of class T; 4104 /// - every member function of class T 4105 /// - every member of class T that is itself a type; 4106 /// \returns true if the declaration name violates these rules. 4107 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4108 DeclarationNameInfo NameInfo) { 4109 DeclarationName Name = NameInfo.getName(); 4110 4111 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4112 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4113 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4114 return true; 4115 } 4116 4117 return false; 4118 } 4119 4120 /// \brief Diagnose a declaration whose declarator-id has the given 4121 /// nested-name-specifier. 4122 /// 4123 /// \param SS The nested-name-specifier of the declarator-id. 4124 /// 4125 /// \param DC The declaration context to which the nested-name-specifier 4126 /// resolves. 4127 /// 4128 /// \param Name The name of the entity being declared. 4129 /// 4130 /// \param Loc The location of the name of the entity being declared. 4131 /// 4132 /// \returns true if we cannot safely recover from this error, false otherwise. 4133 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4134 DeclarationName Name, 4135 SourceLocation Loc) { 4136 DeclContext *Cur = CurContext; 4137 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4138 Cur = Cur->getParent(); 4139 4140 // If the user provided a superfluous scope specifier that refers back to the 4141 // class in which the entity is already declared, diagnose and ignore it. 4142 // 4143 // class X { 4144 // void X::f(); 4145 // }; 4146 // 4147 // Note, it was once ill-formed to give redundant qualification in all 4148 // contexts, but that rule was removed by DR482. 4149 if (Cur->Equals(DC)) { 4150 if (Cur->isRecord()) { 4151 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4152 : diag::err_member_extra_qualification) 4153 << Name << FixItHint::CreateRemoval(SS.getRange()); 4154 SS.clear(); 4155 } else { 4156 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4157 } 4158 return false; 4159 } 4160 4161 // Check whether the qualifying scope encloses the scope of the original 4162 // declaration. 4163 if (!Cur->Encloses(DC)) { 4164 if (Cur->isRecord()) 4165 Diag(Loc, diag::err_member_qualification) 4166 << Name << SS.getRange(); 4167 else if (isa<TranslationUnitDecl>(DC)) 4168 Diag(Loc, diag::err_invalid_declarator_global_scope) 4169 << Name << SS.getRange(); 4170 else if (isa<FunctionDecl>(Cur)) 4171 Diag(Loc, diag::err_invalid_declarator_in_function) 4172 << Name << SS.getRange(); 4173 else if (isa<BlockDecl>(Cur)) 4174 Diag(Loc, diag::err_invalid_declarator_in_block) 4175 << Name << SS.getRange(); 4176 else 4177 Diag(Loc, diag::err_invalid_declarator_scope) 4178 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4179 4180 return true; 4181 } 4182 4183 if (Cur->isRecord()) { 4184 // Cannot qualify members within a class. 4185 Diag(Loc, diag::err_member_qualification) 4186 << Name << SS.getRange(); 4187 SS.clear(); 4188 4189 // C++ constructors and destructors with incorrect scopes can break 4190 // our AST invariants by having the wrong underlying types. If 4191 // that's the case, then drop this declaration entirely. 4192 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4193 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4194 !Context.hasSameType(Name.getCXXNameType(), 4195 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4196 return true; 4197 4198 return false; 4199 } 4200 4201 // C++11 [dcl.meaning]p1: 4202 // [...] "The nested-name-specifier of the qualified declarator-id shall 4203 // not begin with a decltype-specifer" 4204 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4205 while (SpecLoc.getPrefix()) 4206 SpecLoc = SpecLoc.getPrefix(); 4207 if (dyn_cast_or_null<DecltypeType>( 4208 SpecLoc.getNestedNameSpecifier()->getAsType())) 4209 Diag(Loc, diag::err_decltype_in_declarator) 4210 << SpecLoc.getTypeLoc().getSourceRange(); 4211 4212 return false; 4213 } 4214 4215 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4216 MultiTemplateParamsArg TemplateParamLists) { 4217 // TODO: consider using NameInfo for diagnostic. 4218 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4219 DeclarationName Name = NameInfo.getName(); 4220 4221 // All of these full declarators require an identifier. If it doesn't have 4222 // one, the ParsedFreeStandingDeclSpec action should be used. 4223 if (!Name) { 4224 if (!D.isInvalidType()) // Reject this if we think it is valid. 4225 Diag(D.getDeclSpec().getLocStart(), 4226 diag::err_declarator_need_ident) 4227 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4228 return 0; 4229 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4230 return 0; 4231 4232 // The scope passed in may not be a decl scope. Zip up the scope tree until 4233 // we find one that is. 4234 while ((S->getFlags() & Scope::DeclScope) == 0 || 4235 (S->getFlags() & Scope::TemplateParamScope) != 0) 4236 S = S->getParent(); 4237 4238 DeclContext *DC = CurContext; 4239 if (D.getCXXScopeSpec().isInvalid()) 4240 D.setInvalidType(); 4241 else if (D.getCXXScopeSpec().isSet()) { 4242 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4243 UPPC_DeclarationQualifier)) 4244 return 0; 4245 4246 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4247 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4248 if (!DC || isa<EnumDecl>(DC)) { 4249 // If we could not compute the declaration context, it's because the 4250 // declaration context is dependent but does not refer to a class, 4251 // class template, or class template partial specialization. Complain 4252 // and return early, to avoid the coming semantic disaster. 4253 Diag(D.getIdentifierLoc(), 4254 diag::err_template_qualified_declarator_no_match) 4255 << D.getCXXScopeSpec().getScopeRep() 4256 << D.getCXXScopeSpec().getRange(); 4257 return 0; 4258 } 4259 bool IsDependentContext = DC->isDependentContext(); 4260 4261 if (!IsDependentContext && 4262 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4263 return 0; 4264 4265 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4266 Diag(D.getIdentifierLoc(), 4267 diag::err_member_def_undefined_record) 4268 << Name << DC << D.getCXXScopeSpec().getRange(); 4269 D.setInvalidType(); 4270 } else if (!D.getDeclSpec().isFriendSpecified()) { 4271 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4272 Name, D.getIdentifierLoc())) { 4273 if (DC->isRecord()) 4274 return 0; 4275 4276 D.setInvalidType(); 4277 } 4278 } 4279 4280 // Check whether we need to rebuild the type of the given 4281 // declaration in the current instantiation. 4282 if (EnteringContext && IsDependentContext && 4283 TemplateParamLists.size() != 0) { 4284 ContextRAII SavedContext(*this, DC); 4285 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4286 D.setInvalidType(); 4287 } 4288 } 4289 4290 if (DiagnoseClassNameShadow(DC, NameInfo)) 4291 // If this is a typedef, we'll end up spewing multiple diagnostics. 4292 // Just return early; it's safer. 4293 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4294 return 0; 4295 4296 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4297 QualType R = TInfo->getType(); 4298 4299 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4300 UPPC_DeclarationType)) 4301 D.setInvalidType(); 4302 4303 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4304 ForRedeclaration); 4305 4306 // See if this is a redefinition of a variable in the same scope. 4307 if (!D.getCXXScopeSpec().isSet()) { 4308 bool IsLinkageLookup = false; 4309 bool CreateBuiltins = false; 4310 4311 // If the declaration we're planning to build will be a function 4312 // or object with linkage, then look for another declaration with 4313 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4314 // 4315 // If the declaration we're planning to build will be declared with 4316 // external linkage in the translation unit, create any builtin with 4317 // the same name. 4318 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4319 /* Do nothing*/; 4320 else if (CurContext->isFunctionOrMethod() && 4321 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4322 R->isFunctionType())) { 4323 IsLinkageLookup = true; 4324 CreateBuiltins = 4325 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4326 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4327 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4328 CreateBuiltins = true; 4329 4330 if (IsLinkageLookup) 4331 Previous.clear(LookupRedeclarationWithLinkage); 4332 4333 LookupName(Previous, S, CreateBuiltins); 4334 } else { // Something like "int foo::x;" 4335 LookupQualifiedName(Previous, DC); 4336 4337 // C++ [dcl.meaning]p1: 4338 // When the declarator-id is qualified, the declaration shall refer to a 4339 // previously declared member of the class or namespace to which the 4340 // qualifier refers (or, in the case of a namespace, of an element of the 4341 // inline namespace set of that namespace (7.3.1)) or to a specialization 4342 // thereof; [...] 4343 // 4344 // Note that we already checked the context above, and that we do not have 4345 // enough information to make sure that Previous contains the declaration 4346 // we want to match. For example, given: 4347 // 4348 // class X { 4349 // void f(); 4350 // void f(float); 4351 // }; 4352 // 4353 // void X::f(int) { } // ill-formed 4354 // 4355 // In this case, Previous will point to the overload set 4356 // containing the two f's declared in X, but neither of them 4357 // matches. 4358 4359 // C++ [dcl.meaning]p1: 4360 // [...] the member shall not merely have been introduced by a 4361 // using-declaration in the scope of the class or namespace nominated by 4362 // the nested-name-specifier of the declarator-id. 4363 RemoveUsingDecls(Previous); 4364 } 4365 4366 if (Previous.isSingleResult() && 4367 Previous.getFoundDecl()->isTemplateParameter()) { 4368 // Maybe we will complain about the shadowed template parameter. 4369 if (!D.isInvalidType()) 4370 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4371 Previous.getFoundDecl()); 4372 4373 // Just pretend that we didn't see the previous declaration. 4374 Previous.clear(); 4375 } 4376 4377 // In C++, the previous declaration we find might be a tag type 4378 // (class or enum). In this case, the new declaration will hide the 4379 // tag type. Note that this does does not apply if we're declaring a 4380 // typedef (C++ [dcl.typedef]p4). 4381 if (Previous.isSingleTagDecl() && 4382 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4383 Previous.clear(); 4384 4385 // Check that there are no default arguments other than in the parameters 4386 // of a function declaration (C++ only). 4387 if (getLangOpts().CPlusPlus) 4388 CheckExtraCXXDefaultArguments(D); 4389 4390 NamedDecl *New; 4391 4392 bool AddToScope = true; 4393 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4394 if (TemplateParamLists.size()) { 4395 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4396 return 0; 4397 } 4398 4399 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4400 } else if (R->isFunctionType()) { 4401 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4402 TemplateParamLists, 4403 AddToScope); 4404 } else { 4405 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4406 AddToScope); 4407 } 4408 4409 if (New == 0) 4410 return 0; 4411 4412 // If this has an identifier and is not an invalid redeclaration or 4413 // function template specialization, add it to the scope stack. 4414 if (New->getDeclName() && AddToScope && 4415 !(D.isRedeclaration() && New->isInvalidDecl())) { 4416 // Only make a locally-scoped extern declaration visible if it is the first 4417 // declaration of this entity. Qualified lookup for such an entity should 4418 // only find this declaration if there is no visible declaration of it. 4419 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4420 PushOnScopeChains(New, S, AddToContext); 4421 if (!AddToContext) 4422 CurContext->addHiddenDecl(New); 4423 } 4424 4425 return New; 4426 } 4427 4428 /// Helper method to turn variable array types into constant array 4429 /// types in certain situations which would otherwise be errors (for 4430 /// GCC compatibility). 4431 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4432 ASTContext &Context, 4433 bool &SizeIsNegative, 4434 llvm::APSInt &Oversized) { 4435 // This method tries to turn a variable array into a constant 4436 // array even when the size isn't an ICE. This is necessary 4437 // for compatibility with code that depends on gcc's buggy 4438 // constant expression folding, like struct {char x[(int)(char*)2];} 4439 SizeIsNegative = false; 4440 Oversized = 0; 4441 4442 if (T->isDependentType()) 4443 return QualType(); 4444 4445 QualifierCollector Qs; 4446 const Type *Ty = Qs.strip(T); 4447 4448 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4449 QualType Pointee = PTy->getPointeeType(); 4450 QualType FixedType = 4451 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4452 Oversized); 4453 if (FixedType.isNull()) return FixedType; 4454 FixedType = Context.getPointerType(FixedType); 4455 return Qs.apply(Context, FixedType); 4456 } 4457 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4458 QualType Inner = PTy->getInnerType(); 4459 QualType FixedType = 4460 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4461 Oversized); 4462 if (FixedType.isNull()) return FixedType; 4463 FixedType = Context.getParenType(FixedType); 4464 return Qs.apply(Context, FixedType); 4465 } 4466 4467 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4468 if (!VLATy) 4469 return QualType(); 4470 // FIXME: We should probably handle this case 4471 if (VLATy->getElementType()->isVariablyModifiedType()) 4472 return QualType(); 4473 4474 llvm::APSInt Res; 4475 if (!VLATy->getSizeExpr() || 4476 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4477 return QualType(); 4478 4479 // Check whether the array size is negative. 4480 if (Res.isSigned() && Res.isNegative()) { 4481 SizeIsNegative = true; 4482 return QualType(); 4483 } 4484 4485 // Check whether the array is too large to be addressed. 4486 unsigned ActiveSizeBits 4487 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4488 Res); 4489 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4490 Oversized = Res; 4491 return QualType(); 4492 } 4493 4494 return Context.getConstantArrayType(VLATy->getElementType(), 4495 Res, ArrayType::Normal, 0); 4496 } 4497 4498 static void 4499 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4500 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4501 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4502 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4503 DstPTL.getPointeeLoc()); 4504 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4505 return; 4506 } 4507 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4508 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4509 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4510 DstPTL.getInnerLoc()); 4511 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4512 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4513 return; 4514 } 4515 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4516 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4517 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4518 TypeLoc DstElemTL = DstATL.getElementLoc(); 4519 DstElemTL.initializeFullCopy(SrcElemTL); 4520 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4521 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4522 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4523 } 4524 4525 /// Helper method to turn variable array types into constant array 4526 /// types in certain situations which would otherwise be errors (for 4527 /// GCC compatibility). 4528 static TypeSourceInfo* 4529 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4530 ASTContext &Context, 4531 bool &SizeIsNegative, 4532 llvm::APSInt &Oversized) { 4533 QualType FixedTy 4534 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4535 SizeIsNegative, Oversized); 4536 if (FixedTy.isNull()) 4537 return 0; 4538 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4539 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4540 FixedTInfo->getTypeLoc()); 4541 return FixedTInfo; 4542 } 4543 4544 /// \brief Register the given locally-scoped extern "C" declaration so 4545 /// that it can be found later for redeclarations. We include any extern "C" 4546 /// declaration that is not visible in the translation unit here, not just 4547 /// function-scope declarations. 4548 void 4549 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4550 if (!getLangOpts().CPlusPlus && 4551 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4552 // Don't need to track declarations in the TU in C. 4553 return; 4554 4555 // Note that we have a locally-scoped external with this name. 4556 // FIXME: There can be multiple such declarations if they are functions marked 4557 // __attribute__((overloadable)) declared in function scope in C. 4558 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4559 } 4560 4561 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4562 if (ExternalSource) { 4563 // Load locally-scoped external decls from the external source. 4564 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4565 SmallVector<NamedDecl *, 4> Decls; 4566 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4567 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4568 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4569 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4570 if (Pos == LocallyScopedExternCDecls.end()) 4571 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4572 } 4573 } 4574 4575 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4576 return D ? D->getMostRecentDecl() : 0; 4577 } 4578 4579 /// \brief Diagnose function specifiers on a declaration of an identifier that 4580 /// does not identify a function. 4581 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4582 // FIXME: We should probably indicate the identifier in question to avoid 4583 // confusion for constructs like "inline int a(), b;" 4584 if (DS.isInlineSpecified()) 4585 Diag(DS.getInlineSpecLoc(), 4586 diag::err_inline_non_function); 4587 4588 if (DS.isVirtualSpecified()) 4589 Diag(DS.getVirtualSpecLoc(), 4590 diag::err_virtual_non_function); 4591 4592 if (DS.isExplicitSpecified()) 4593 Diag(DS.getExplicitSpecLoc(), 4594 diag::err_explicit_non_function); 4595 4596 if (DS.isNoreturnSpecified()) 4597 Diag(DS.getNoreturnSpecLoc(), 4598 diag::err_noreturn_non_function); 4599 } 4600 4601 NamedDecl* 4602 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4603 TypeSourceInfo *TInfo, LookupResult &Previous) { 4604 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4605 if (D.getCXXScopeSpec().isSet()) { 4606 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4607 << D.getCXXScopeSpec().getRange(); 4608 D.setInvalidType(); 4609 // Pretend we didn't see the scope specifier. 4610 DC = CurContext; 4611 Previous.clear(); 4612 } 4613 4614 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4615 4616 if (D.getDeclSpec().isConstexprSpecified()) 4617 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4618 << 1; 4619 4620 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4621 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4622 << D.getName().getSourceRange(); 4623 return 0; 4624 } 4625 4626 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4627 if (!NewTD) return 0; 4628 4629 // Handle attributes prior to checking for duplicates in MergeVarDecl 4630 ProcessDeclAttributes(S, NewTD, D); 4631 4632 CheckTypedefForVariablyModifiedType(S, NewTD); 4633 4634 bool Redeclaration = D.isRedeclaration(); 4635 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4636 D.setRedeclaration(Redeclaration); 4637 return ND; 4638 } 4639 4640 void 4641 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4642 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4643 // then it shall have block scope. 4644 // Note that variably modified types must be fixed before merging the decl so 4645 // that redeclarations will match. 4646 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4647 QualType T = TInfo->getType(); 4648 if (T->isVariablyModifiedType()) { 4649 getCurFunction()->setHasBranchProtectedScope(); 4650 4651 if (S->getFnParent() == 0) { 4652 bool SizeIsNegative; 4653 llvm::APSInt Oversized; 4654 TypeSourceInfo *FixedTInfo = 4655 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4656 SizeIsNegative, 4657 Oversized); 4658 if (FixedTInfo) { 4659 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4660 NewTD->setTypeSourceInfo(FixedTInfo); 4661 } else { 4662 if (SizeIsNegative) 4663 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4664 else if (T->isVariableArrayType()) 4665 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4666 else if (Oversized.getBoolValue()) 4667 Diag(NewTD->getLocation(), diag::err_array_too_large) 4668 << Oversized.toString(10); 4669 else 4670 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4671 NewTD->setInvalidDecl(); 4672 } 4673 } 4674 } 4675 } 4676 4677 4678 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4679 /// declares a typedef-name, either using the 'typedef' type specifier or via 4680 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4681 NamedDecl* 4682 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4683 LookupResult &Previous, bool &Redeclaration) { 4684 // Merge the decl with the existing one if appropriate. If the decl is 4685 // in an outer scope, it isn't the same thing. 4686 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4687 /*AllowInlineNamespace*/false); 4688 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4689 if (!Previous.empty()) { 4690 Redeclaration = true; 4691 MergeTypedefNameDecl(NewTD, Previous); 4692 } 4693 4694 // If this is the C FILE type, notify the AST context. 4695 if (IdentifierInfo *II = NewTD->getIdentifier()) 4696 if (!NewTD->isInvalidDecl() && 4697 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4698 if (II->isStr("FILE")) 4699 Context.setFILEDecl(NewTD); 4700 else if (II->isStr("jmp_buf")) 4701 Context.setjmp_bufDecl(NewTD); 4702 else if (II->isStr("sigjmp_buf")) 4703 Context.setsigjmp_bufDecl(NewTD); 4704 else if (II->isStr("ucontext_t")) 4705 Context.setucontext_tDecl(NewTD); 4706 } 4707 4708 return NewTD; 4709 } 4710 4711 /// \brief Determines whether the given declaration is an out-of-scope 4712 /// previous declaration. 4713 /// 4714 /// This routine should be invoked when name lookup has found a 4715 /// previous declaration (PrevDecl) that is not in the scope where a 4716 /// new declaration by the same name is being introduced. If the new 4717 /// declaration occurs in a local scope, previous declarations with 4718 /// linkage may still be considered previous declarations (C99 4719 /// 6.2.2p4-5, C++ [basic.link]p6). 4720 /// 4721 /// \param PrevDecl the previous declaration found by name 4722 /// lookup 4723 /// 4724 /// \param DC the context in which the new declaration is being 4725 /// declared. 4726 /// 4727 /// \returns true if PrevDecl is an out-of-scope previous declaration 4728 /// for a new delcaration with the same name. 4729 static bool 4730 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4731 ASTContext &Context) { 4732 if (!PrevDecl) 4733 return false; 4734 4735 if (!PrevDecl->hasLinkage()) 4736 return false; 4737 4738 if (Context.getLangOpts().CPlusPlus) { 4739 // C++ [basic.link]p6: 4740 // If there is a visible declaration of an entity with linkage 4741 // having the same name and type, ignoring entities declared 4742 // outside the innermost enclosing namespace scope, the block 4743 // scope declaration declares that same entity and receives the 4744 // linkage of the previous declaration. 4745 DeclContext *OuterContext = DC->getRedeclContext(); 4746 if (!OuterContext->isFunctionOrMethod()) 4747 // This rule only applies to block-scope declarations. 4748 return false; 4749 4750 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4751 if (PrevOuterContext->isRecord()) 4752 // We found a member function: ignore it. 4753 return false; 4754 4755 // Find the innermost enclosing namespace for the new and 4756 // previous declarations. 4757 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4758 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4759 4760 // The previous declaration is in a different namespace, so it 4761 // isn't the same function. 4762 if (!OuterContext->Equals(PrevOuterContext)) 4763 return false; 4764 } 4765 4766 return true; 4767 } 4768 4769 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4770 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4771 if (!SS.isSet()) return; 4772 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4773 } 4774 4775 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4776 QualType type = decl->getType(); 4777 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4778 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4779 // Various kinds of declaration aren't allowed to be __autoreleasing. 4780 unsigned kind = -1U; 4781 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4782 if (var->hasAttr<BlocksAttr>()) 4783 kind = 0; // __block 4784 else if (!var->hasLocalStorage()) 4785 kind = 1; // global 4786 } else if (isa<ObjCIvarDecl>(decl)) { 4787 kind = 3; // ivar 4788 } else if (isa<FieldDecl>(decl)) { 4789 kind = 2; // field 4790 } 4791 4792 if (kind != -1U) { 4793 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4794 << kind; 4795 } 4796 } else if (lifetime == Qualifiers::OCL_None) { 4797 // Try to infer lifetime. 4798 if (!type->isObjCLifetimeType()) 4799 return false; 4800 4801 lifetime = type->getObjCARCImplicitLifetime(); 4802 type = Context.getLifetimeQualifiedType(type, lifetime); 4803 decl->setType(type); 4804 } 4805 4806 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4807 // Thread-local variables cannot have lifetime. 4808 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4809 var->getTLSKind()) { 4810 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4811 << var->getType(); 4812 return true; 4813 } 4814 } 4815 4816 return false; 4817 } 4818 4819 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4820 // Ensure that an auto decl is deduced otherwise the checks below might cache 4821 // the wrong linkage. 4822 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4823 4824 // 'weak' only applies to declarations with external linkage. 4825 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4826 if (!ND.isExternallyVisible()) { 4827 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4828 ND.dropAttr<WeakAttr>(); 4829 } 4830 } 4831 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4832 if (ND.isExternallyVisible()) { 4833 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4834 ND.dropAttr<WeakRefAttr>(); 4835 } 4836 } 4837 4838 // 'selectany' only applies to externally visible varable declarations. 4839 // It does not apply to functions. 4840 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4841 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4842 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4843 ND.dropAttr<SelectAnyAttr>(); 4844 } 4845 } 4846 4847 // dll attributes require external linkage. 4848 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 4849 if (!ND.isExternallyVisible()) { 4850 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4851 << &ND << Attr; 4852 ND.setInvalidDecl(); 4853 } 4854 } 4855 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 4856 if (!ND.isExternallyVisible()) { 4857 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4858 << &ND << Attr; 4859 ND.setInvalidDecl(); 4860 } 4861 } 4862 } 4863 4864 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 4865 NamedDecl *NewDecl, 4866 bool IsSpecialization) { 4867 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 4868 OldDecl = OldTD->getTemplatedDecl(); 4869 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 4870 NewDecl = NewTD->getTemplatedDecl(); 4871 4872 if (!OldDecl || !NewDecl) 4873 return; 4874 4875 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 4876 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 4877 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 4878 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 4879 4880 // dllimport and dllexport are inheritable attributes so we have to exclude 4881 // inherited attribute instances. 4882 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 4883 (NewExportAttr && !NewExportAttr->isInherited()); 4884 4885 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 4886 // the only exception being explicit specializations. 4887 // Implicitly generated declarations are also excluded for now because there 4888 // is no other way to switch these to use dllimport or dllexport. 4889 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 4890 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 4891 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration) 4892 << NewDecl 4893 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 4894 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4895 NewDecl->setInvalidDecl(); 4896 return; 4897 } 4898 4899 // A redeclaration is not allowed to drop a dllimport attribute, the only 4900 // exception being inline function definitions. 4901 // FIXME: Handle inline functions. 4902 // NB: MSVC converts such a declaration to dllexport. 4903 if (OldImportAttr && !HasNewAttr) { 4904 S.Diag(NewDecl->getLocation(), 4905 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4906 << NewDecl << OldImportAttr; 4907 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4908 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 4909 OldDecl->dropAttr<DLLImportAttr>(); 4910 NewDecl->dropAttr<DLLImportAttr>(); 4911 } 4912 } 4913 4914 /// Given that we are within the definition of the given function, 4915 /// will that definition behave like C99's 'inline', where the 4916 /// definition is discarded except for optimization purposes? 4917 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4918 // Try to avoid calling GetGVALinkageForFunction. 4919 4920 // All cases of this require the 'inline' keyword. 4921 if (!FD->isInlined()) return false; 4922 4923 // This is only possible in C++ with the gnu_inline attribute. 4924 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4925 return false; 4926 4927 // Okay, go ahead and call the relatively-more-expensive function. 4928 4929 #ifndef NDEBUG 4930 // AST quite reasonably asserts that it's working on a function 4931 // definition. We don't really have a way to tell it that we're 4932 // currently defining the function, so just lie to it in +Asserts 4933 // builds. This is an awful hack. 4934 FD->setLazyBody(1); 4935 #endif 4936 4937 bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline); 4938 4939 #ifndef NDEBUG 4940 FD->setLazyBody(0); 4941 #endif 4942 4943 return isC99Inline; 4944 } 4945 4946 /// Determine whether a variable is extern "C" prior to attaching 4947 /// an initializer. We can't just call isExternC() here, because that 4948 /// will also compute and cache whether the declaration is externally 4949 /// visible, which might change when we attach the initializer. 4950 /// 4951 /// This can only be used if the declaration is known to not be a 4952 /// redeclaration of an internal linkage declaration. 4953 /// 4954 /// For instance: 4955 /// 4956 /// auto x = []{}; 4957 /// 4958 /// Attaching the initializer here makes this declaration not externally 4959 /// visible, because its type has internal linkage. 4960 /// 4961 /// FIXME: This is a hack. 4962 template<typename T> 4963 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 4964 if (S.getLangOpts().CPlusPlus) { 4965 // In C++, the overloadable attribute negates the effects of extern "C". 4966 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 4967 return false; 4968 } 4969 return D->isExternC(); 4970 } 4971 4972 static bool shouldConsiderLinkage(const VarDecl *VD) { 4973 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 4974 if (DC->isFunctionOrMethod()) 4975 return VD->hasExternalStorage(); 4976 if (DC->isFileContext()) 4977 return true; 4978 if (DC->isRecord()) 4979 return false; 4980 llvm_unreachable("Unexpected context"); 4981 } 4982 4983 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 4984 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 4985 if (DC->isFileContext() || DC->isFunctionOrMethod()) 4986 return true; 4987 if (DC->isRecord()) 4988 return false; 4989 llvm_unreachable("Unexpected context"); 4990 } 4991 4992 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 4993 AttributeList::Kind Kind) { 4994 for (const AttributeList *L = AttrList; L; L = L->getNext()) 4995 if (L->getKind() == Kind) 4996 return true; 4997 return false; 4998 } 4999 5000 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5001 AttributeList::Kind Kind) { 5002 // Check decl attributes on the DeclSpec. 5003 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5004 return true; 5005 5006 // Walk the declarator structure, checking decl attributes that were in a type 5007 // position to the decl itself. 5008 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5009 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5010 return true; 5011 } 5012 5013 // Finally, check attributes on the decl itself. 5014 return hasParsedAttr(S, PD.getAttributes(), Kind); 5015 } 5016 5017 /// Adjust the \c DeclContext for a function or variable that might be a 5018 /// function-local external declaration. 5019 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5020 if (!DC->isFunctionOrMethod()) 5021 return false; 5022 5023 // If this is a local extern function or variable declared within a function 5024 // template, don't add it into the enclosing namespace scope until it is 5025 // instantiated; it might have a dependent type right now. 5026 if (DC->isDependentContext()) 5027 return true; 5028 5029 // C++11 [basic.link]p7: 5030 // When a block scope declaration of an entity with linkage is not found to 5031 // refer to some other declaration, then that entity is a member of the 5032 // innermost enclosing namespace. 5033 // 5034 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5035 // semantically-enclosing namespace, not a lexically-enclosing one. 5036 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5037 DC = DC->getParent(); 5038 return true; 5039 } 5040 5041 NamedDecl * 5042 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5043 TypeSourceInfo *TInfo, LookupResult &Previous, 5044 MultiTemplateParamsArg TemplateParamLists, 5045 bool &AddToScope) { 5046 QualType R = TInfo->getType(); 5047 DeclarationName Name = GetNameForDeclarator(D).getName(); 5048 5049 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5050 VarDecl::StorageClass SC = 5051 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5052 5053 // dllimport globals without explicit storage class are treated as extern. We 5054 // have to change the storage class this early to get the right DeclContext. 5055 if (SC == SC_None && !DC->isRecord() && 5056 hasParsedAttr(S, D, AttributeList::AT_DLLImport)) 5057 SC = SC_Extern; 5058 5059 DeclContext *OriginalDC = DC; 5060 bool IsLocalExternDecl = SC == SC_Extern && 5061 adjustContextForLocalExternDecl(DC); 5062 5063 if (getLangOpts().OpenCL) { 5064 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5065 QualType NR = R; 5066 while (NR->isPointerType()) { 5067 if (NR->isFunctionPointerType()) { 5068 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5069 D.setInvalidType(); 5070 break; 5071 } 5072 NR = NR->getPointeeType(); 5073 } 5074 5075 if (!getOpenCLOptions().cl_khr_fp16) { 5076 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5077 // half array type (unless the cl_khr_fp16 extension is enabled). 5078 if (Context.getBaseElementType(R)->isHalfType()) { 5079 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5080 D.setInvalidType(); 5081 } 5082 } 5083 } 5084 5085 if (SCSpec == DeclSpec::SCS_mutable) { 5086 // mutable can only appear on non-static class members, so it's always 5087 // an error here 5088 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5089 D.setInvalidType(); 5090 SC = SC_None; 5091 } 5092 5093 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5094 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5095 D.getDeclSpec().getStorageClassSpecLoc())) { 5096 // In C++11, the 'register' storage class specifier is deprecated. 5097 // Suppress the warning in system macros, it's used in macros in some 5098 // popular C system headers, such as in glibc's htonl() macro. 5099 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5100 diag::warn_deprecated_register) 5101 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5102 } 5103 5104 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5105 if (!II) { 5106 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5107 << Name; 5108 return 0; 5109 } 5110 5111 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5112 5113 if (!DC->isRecord() && S->getFnParent() == 0) { 5114 // C99 6.9p2: The storage-class specifiers auto and register shall not 5115 // appear in the declaration specifiers in an external declaration. 5116 if (SC == SC_Auto || SC == SC_Register) { 5117 // If this is a register variable with an asm label specified, then this 5118 // is a GNU extension. 5119 if (SC == SC_Register && D.getAsmLabel()) 5120 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 5121 else 5122 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5123 D.setInvalidType(); 5124 } 5125 } 5126 5127 if (getLangOpts().OpenCL) { 5128 // Set up the special work-group-local storage class for variables in the 5129 // OpenCL __local address space. 5130 if (R.getAddressSpace() == LangAS::opencl_local) { 5131 SC = SC_OpenCLWorkGroupLocal; 5132 } 5133 5134 // OpenCL v1.2 s6.9.b p4: 5135 // The sampler type cannot be used with the __local and __global address 5136 // space qualifiers. 5137 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5138 R.getAddressSpace() == LangAS::opencl_global)) { 5139 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5140 } 5141 5142 // OpenCL 1.2 spec, p6.9 r: 5143 // The event type cannot be used to declare a program scope variable. 5144 // The event type cannot be used with the __local, __constant and __global 5145 // address space qualifiers. 5146 if (R->isEventT()) { 5147 if (S->getParent() == 0) { 5148 Diag(D.getLocStart(), diag::err_event_t_global_var); 5149 D.setInvalidType(); 5150 } 5151 5152 if (R.getAddressSpace()) { 5153 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5154 D.setInvalidType(); 5155 } 5156 } 5157 } 5158 5159 bool IsExplicitSpecialization = false; 5160 bool IsVariableTemplateSpecialization = false; 5161 bool IsPartialSpecialization = false; 5162 bool IsVariableTemplate = false; 5163 VarDecl *NewVD = 0; 5164 VarTemplateDecl *NewTemplate = 0; 5165 TemplateParameterList *TemplateParams = 0; 5166 if (!getLangOpts().CPlusPlus) { 5167 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5168 D.getIdentifierLoc(), II, 5169 R, TInfo, SC); 5170 5171 if (D.isInvalidType()) 5172 NewVD->setInvalidDecl(); 5173 } else { 5174 bool Invalid = false; 5175 5176 if (DC->isRecord() && !CurContext->isRecord()) { 5177 // This is an out-of-line definition of a static data member. 5178 switch (SC) { 5179 case SC_None: 5180 break; 5181 case SC_Static: 5182 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5183 diag::err_static_out_of_line) 5184 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5185 break; 5186 case SC_Auto: 5187 case SC_Register: 5188 case SC_Extern: 5189 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5190 // to names of variables declared in a block or to function parameters. 5191 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5192 // of class members 5193 5194 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5195 diag::err_storage_class_for_static_member) 5196 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5197 break; 5198 case SC_PrivateExtern: 5199 llvm_unreachable("C storage class in c++!"); 5200 case SC_OpenCLWorkGroupLocal: 5201 llvm_unreachable("OpenCL storage class in c++!"); 5202 } 5203 } 5204 5205 if (SC == SC_Static && CurContext->isRecord()) { 5206 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5207 if (RD->isLocalClass()) 5208 Diag(D.getIdentifierLoc(), 5209 diag::err_static_data_member_not_allowed_in_local_class) 5210 << Name << RD->getDeclName(); 5211 5212 // C++98 [class.union]p1: If a union contains a static data member, 5213 // the program is ill-formed. C++11 drops this restriction. 5214 if (RD->isUnion()) 5215 Diag(D.getIdentifierLoc(), 5216 getLangOpts().CPlusPlus11 5217 ? diag::warn_cxx98_compat_static_data_member_in_union 5218 : diag::ext_static_data_member_in_union) << Name; 5219 // We conservatively disallow static data members in anonymous structs. 5220 else if (!RD->getDeclName()) 5221 Diag(D.getIdentifierLoc(), 5222 diag::err_static_data_member_not_allowed_in_anon_struct) 5223 << Name << RD->isUnion(); 5224 } 5225 } 5226 5227 // Match up the template parameter lists with the scope specifier, then 5228 // determine whether we have a template or a template specialization. 5229 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5230 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5231 D.getCXXScopeSpec(), 5232 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5233 ? D.getName().TemplateId 5234 : 0, 5235 TemplateParamLists, 5236 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5237 5238 if (TemplateParams) { 5239 if (!TemplateParams->size() && 5240 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5241 // There is an extraneous 'template<>' for this variable. Complain 5242 // about it, but allow the declaration of the variable. 5243 Diag(TemplateParams->getTemplateLoc(), 5244 diag::err_template_variable_noparams) 5245 << II 5246 << SourceRange(TemplateParams->getTemplateLoc(), 5247 TemplateParams->getRAngleLoc()); 5248 TemplateParams = 0; 5249 } else { 5250 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5251 // This is an explicit specialization or a partial specialization. 5252 // FIXME: Check that we can declare a specialization here. 5253 IsVariableTemplateSpecialization = true; 5254 IsPartialSpecialization = TemplateParams->size() > 0; 5255 } else { // if (TemplateParams->size() > 0) 5256 // This is a template declaration. 5257 IsVariableTemplate = true; 5258 5259 // Check that we can declare a template here. 5260 if (CheckTemplateDeclScope(S, TemplateParams)) 5261 return 0; 5262 5263 // Only C++1y supports variable templates (N3651). 5264 Diag(D.getIdentifierLoc(), 5265 getLangOpts().CPlusPlus1y 5266 ? diag::warn_cxx11_compat_variable_template 5267 : diag::ext_variable_template); 5268 } 5269 } 5270 } else { 5271 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5272 "should have a 'template<>' for this decl"); 5273 } 5274 5275 if (IsVariableTemplateSpecialization) { 5276 SourceLocation TemplateKWLoc = 5277 TemplateParamLists.size() > 0 5278 ? TemplateParamLists[0]->getTemplateLoc() 5279 : SourceLocation(); 5280 DeclResult Res = ActOnVarTemplateSpecialization( 5281 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5282 IsPartialSpecialization); 5283 if (Res.isInvalid()) 5284 return 0; 5285 NewVD = cast<VarDecl>(Res.get()); 5286 AddToScope = false; 5287 } else 5288 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5289 D.getIdentifierLoc(), II, R, TInfo, SC); 5290 5291 // If this is supposed to be a variable template, create it as such. 5292 if (IsVariableTemplate) { 5293 NewTemplate = 5294 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5295 TemplateParams, NewVD); 5296 NewVD->setDescribedVarTemplate(NewTemplate); 5297 } 5298 5299 // If this decl has an auto type in need of deduction, make a note of the 5300 // Decl so we can diagnose uses of it in its own initializer. 5301 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5302 ParsingInitForAutoVars.insert(NewVD); 5303 5304 if (D.isInvalidType() || Invalid) { 5305 NewVD->setInvalidDecl(); 5306 if (NewTemplate) 5307 NewTemplate->setInvalidDecl(); 5308 } 5309 5310 SetNestedNameSpecifier(NewVD, D); 5311 5312 // If we have any template parameter lists that don't directly belong to 5313 // the variable (matching the scope specifier), store them. 5314 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5315 if (TemplateParamLists.size() > VDTemplateParamLists) 5316 NewVD->setTemplateParameterListsInfo( 5317 Context, TemplateParamLists.size() - VDTemplateParamLists, 5318 TemplateParamLists.data()); 5319 5320 if (D.getDeclSpec().isConstexprSpecified()) 5321 NewVD->setConstexpr(true); 5322 } 5323 5324 // Set the lexical context. If the declarator has a C++ scope specifier, the 5325 // lexical context will be different from the semantic context. 5326 NewVD->setLexicalDeclContext(CurContext); 5327 if (NewTemplate) 5328 NewTemplate->setLexicalDeclContext(CurContext); 5329 5330 if (IsLocalExternDecl) 5331 NewVD->setLocalExternDecl(); 5332 5333 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5334 if (NewVD->hasLocalStorage()) { 5335 // C++11 [dcl.stc]p4: 5336 // When thread_local is applied to a variable of block scope the 5337 // storage-class-specifier static is implied if it does not appear 5338 // explicitly. 5339 // Core issue: 'static' is not implied if the variable is declared 5340 // 'extern'. 5341 if (SCSpec == DeclSpec::SCS_unspecified && 5342 TSCS == DeclSpec::TSCS_thread_local && 5343 DC->isFunctionOrMethod()) 5344 NewVD->setTSCSpec(TSCS); 5345 else 5346 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5347 diag::err_thread_non_global) 5348 << DeclSpec::getSpecifierName(TSCS); 5349 } else if (!Context.getTargetInfo().isTLSSupported()) 5350 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5351 diag::err_thread_unsupported); 5352 else 5353 NewVD->setTSCSpec(TSCS); 5354 } 5355 5356 // C99 6.7.4p3 5357 // An inline definition of a function with external linkage shall 5358 // not contain a definition of a modifiable object with static or 5359 // thread storage duration... 5360 // We only apply this when the function is required to be defined 5361 // elsewhere, i.e. when the function is not 'extern inline'. Note 5362 // that a local variable with thread storage duration still has to 5363 // be marked 'static'. Also note that it's possible to get these 5364 // semantics in C++ using __attribute__((gnu_inline)). 5365 if (SC == SC_Static && S->getFnParent() != 0 && 5366 !NewVD->getType().isConstQualified()) { 5367 FunctionDecl *CurFD = getCurFunctionDecl(); 5368 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5369 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5370 diag::warn_static_local_in_extern_inline); 5371 MaybeSuggestAddingStaticToDecl(CurFD); 5372 } 5373 } 5374 5375 if (D.getDeclSpec().isModulePrivateSpecified()) { 5376 if (IsVariableTemplateSpecialization) 5377 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5378 << (IsPartialSpecialization ? 1 : 0) 5379 << FixItHint::CreateRemoval( 5380 D.getDeclSpec().getModulePrivateSpecLoc()); 5381 else if (IsExplicitSpecialization) 5382 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5383 << 2 5384 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5385 else if (NewVD->hasLocalStorage()) 5386 Diag(NewVD->getLocation(), diag::err_module_private_local) 5387 << 0 << NewVD->getDeclName() 5388 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5389 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5390 else { 5391 NewVD->setModulePrivate(); 5392 if (NewTemplate) 5393 NewTemplate->setModulePrivate(); 5394 } 5395 } 5396 5397 // Handle attributes prior to checking for duplicates in MergeVarDecl 5398 ProcessDeclAttributes(S, NewVD, D); 5399 5400 if (getLangOpts().CUDA) { 5401 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5402 // storage [duration]." 5403 if (SC == SC_None && S->getFnParent() != 0 && 5404 (NewVD->hasAttr<CUDASharedAttr>() || 5405 NewVD->hasAttr<CUDAConstantAttr>())) { 5406 NewVD->setStorageClass(SC_Static); 5407 } 5408 } 5409 5410 // Ensure that dllimport globals without explicit storage class are treated as 5411 // extern. The storage class is set above using parsed attributes. Now we can 5412 // check the VarDecl itself. 5413 assert(!NewVD->hasAttr<DLLImportAttr>() || 5414 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5415 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5416 5417 // In auto-retain/release, infer strong retension for variables of 5418 // retainable type. 5419 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5420 NewVD->setInvalidDecl(); 5421 5422 // Handle GNU asm-label extension (encoded as an attribute). 5423 if (Expr *E = (Expr*)D.getAsmLabel()) { 5424 // The parser guarantees this is a string. 5425 StringLiteral *SE = cast<StringLiteral>(E); 5426 StringRef Label = SE->getString(); 5427 if (S->getFnParent() != 0) { 5428 switch (SC) { 5429 case SC_None: 5430 case SC_Auto: 5431 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5432 break; 5433 case SC_Register: 5434 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5435 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5436 break; 5437 case SC_Static: 5438 case SC_Extern: 5439 case SC_PrivateExtern: 5440 case SC_OpenCLWorkGroupLocal: 5441 break; 5442 } 5443 } 5444 5445 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5446 Context, Label, 0)); 5447 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5448 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5449 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5450 if (I != ExtnameUndeclaredIdentifiers.end()) { 5451 NewVD->addAttr(I->second); 5452 ExtnameUndeclaredIdentifiers.erase(I); 5453 } 5454 } 5455 5456 // Diagnose shadowed variables before filtering for scope. 5457 if (D.getCXXScopeSpec().isEmpty()) 5458 CheckShadow(S, NewVD, Previous); 5459 5460 // Don't consider existing declarations that are in a different 5461 // scope and are out-of-semantic-context declarations (if the new 5462 // declaration has linkage). 5463 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5464 D.getCXXScopeSpec().isNotEmpty() || 5465 IsExplicitSpecialization || 5466 IsVariableTemplateSpecialization); 5467 5468 // Check whether the previous declaration is in the same block scope. This 5469 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5470 if (getLangOpts().CPlusPlus && 5471 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5472 NewVD->setPreviousDeclInSameBlockScope( 5473 Previous.isSingleResult() && !Previous.isShadowed() && 5474 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5475 5476 if (!getLangOpts().CPlusPlus) { 5477 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5478 } else { 5479 // If this is an explicit specialization of a static data member, check it. 5480 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5481 CheckMemberSpecialization(NewVD, Previous)) 5482 NewVD->setInvalidDecl(); 5483 5484 // Merge the decl with the existing one if appropriate. 5485 if (!Previous.empty()) { 5486 if (Previous.isSingleResult() && 5487 isa<FieldDecl>(Previous.getFoundDecl()) && 5488 D.getCXXScopeSpec().isSet()) { 5489 // The user tried to define a non-static data member 5490 // out-of-line (C++ [dcl.meaning]p1). 5491 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5492 << D.getCXXScopeSpec().getRange(); 5493 Previous.clear(); 5494 NewVD->setInvalidDecl(); 5495 } 5496 } else if (D.getCXXScopeSpec().isSet()) { 5497 // No previous declaration in the qualifying scope. 5498 Diag(D.getIdentifierLoc(), diag::err_no_member) 5499 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5500 << D.getCXXScopeSpec().getRange(); 5501 NewVD->setInvalidDecl(); 5502 } 5503 5504 if (!IsVariableTemplateSpecialization) 5505 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5506 5507 if (NewTemplate) { 5508 VarTemplateDecl *PrevVarTemplate = 5509 NewVD->getPreviousDecl() 5510 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5511 : 0; 5512 5513 // Check the template parameter list of this declaration, possibly 5514 // merging in the template parameter list from the previous variable 5515 // template declaration. 5516 if (CheckTemplateParameterList( 5517 TemplateParams, 5518 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5519 : 0, 5520 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5521 DC->isDependentContext()) 5522 ? TPC_ClassTemplateMember 5523 : TPC_VarTemplate)) 5524 NewVD->setInvalidDecl(); 5525 5526 // If we are providing an explicit specialization of a static variable 5527 // template, make a note of that. 5528 if (PrevVarTemplate && 5529 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5530 PrevVarTemplate->setMemberSpecialization(); 5531 } 5532 } 5533 5534 ProcessPragmaWeak(S, NewVD); 5535 5536 // If this is the first declaration of an extern C variable, update 5537 // the map of such variables. 5538 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5539 isIncompleteDeclExternC(*this, NewVD)) 5540 RegisterLocallyScopedExternCDecl(NewVD, S); 5541 5542 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5543 Decl *ManglingContextDecl; 5544 if (MangleNumberingContext *MCtx = 5545 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5546 ManglingContextDecl)) { 5547 Context.setManglingNumber( 5548 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5549 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5550 } 5551 } 5552 5553 if (D.isRedeclaration() && !Previous.empty()) { 5554 checkDLLAttributeRedeclaration( 5555 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5556 IsExplicitSpecialization); 5557 } 5558 5559 if (NewTemplate) { 5560 if (NewVD->isInvalidDecl()) 5561 NewTemplate->setInvalidDecl(); 5562 ActOnDocumentableDecl(NewTemplate); 5563 return NewTemplate; 5564 } 5565 5566 return NewVD; 5567 } 5568 5569 /// \brief Diagnose variable or built-in function shadowing. Implements 5570 /// -Wshadow. 5571 /// 5572 /// This method is called whenever a VarDecl is added to a "useful" 5573 /// scope. 5574 /// 5575 /// \param S the scope in which the shadowing name is being declared 5576 /// \param R the lookup of the name 5577 /// 5578 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5579 // Return if warning is ignored. 5580 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5581 DiagnosticsEngine::Ignored) 5582 return; 5583 5584 // Don't diagnose declarations at file scope. 5585 if (D->hasGlobalStorage()) 5586 return; 5587 5588 DeclContext *NewDC = D->getDeclContext(); 5589 5590 // Only diagnose if we're shadowing an unambiguous field or variable. 5591 if (R.getResultKind() != LookupResult::Found) 5592 return; 5593 5594 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5595 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5596 return; 5597 5598 // Fields are not shadowed by variables in C++ static methods. 5599 if (isa<FieldDecl>(ShadowedDecl)) 5600 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5601 if (MD->isStatic()) 5602 return; 5603 5604 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5605 if (shadowedVar->isExternC()) { 5606 // For shadowing external vars, make sure that we point to the global 5607 // declaration, not a locally scoped extern declaration. 5608 for (auto I : shadowedVar->redecls()) 5609 if (I->isFileVarDecl()) { 5610 ShadowedDecl = I; 5611 break; 5612 } 5613 } 5614 5615 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5616 5617 // Only warn about certain kinds of shadowing for class members. 5618 if (NewDC && NewDC->isRecord()) { 5619 // In particular, don't warn about shadowing non-class members. 5620 if (!OldDC->isRecord()) 5621 return; 5622 5623 // TODO: should we warn about static data members shadowing 5624 // static data members from base classes? 5625 5626 // TODO: don't diagnose for inaccessible shadowed members. 5627 // This is hard to do perfectly because we might friend the 5628 // shadowing context, but that's just a false negative. 5629 } 5630 5631 // Determine what kind of declaration we're shadowing. 5632 unsigned Kind; 5633 if (isa<RecordDecl>(OldDC)) { 5634 if (isa<FieldDecl>(ShadowedDecl)) 5635 Kind = 3; // field 5636 else 5637 Kind = 2; // static data member 5638 } else if (OldDC->isFileContext()) 5639 Kind = 1; // global 5640 else 5641 Kind = 0; // local 5642 5643 DeclarationName Name = R.getLookupName(); 5644 5645 // Emit warning and note. 5646 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5647 return; 5648 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5649 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5650 } 5651 5652 /// \brief Check -Wshadow without the advantage of a previous lookup. 5653 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5654 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5655 DiagnosticsEngine::Ignored) 5656 return; 5657 5658 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5659 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5660 LookupName(R, S); 5661 CheckShadow(S, D, R); 5662 } 5663 5664 /// Check for conflict between this global or extern "C" declaration and 5665 /// previous global or extern "C" declarations. This is only used in C++. 5666 template<typename T> 5667 static bool checkGlobalOrExternCConflict( 5668 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5669 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5670 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5671 5672 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5673 // The common case: this global doesn't conflict with any extern "C" 5674 // declaration. 5675 return false; 5676 } 5677 5678 if (Prev) { 5679 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5680 // Both the old and new declarations have C language linkage. This is a 5681 // redeclaration. 5682 Previous.clear(); 5683 Previous.addDecl(Prev); 5684 return true; 5685 } 5686 5687 // This is a global, non-extern "C" declaration, and there is a previous 5688 // non-global extern "C" declaration. Diagnose if this is a variable 5689 // declaration. 5690 if (!isa<VarDecl>(ND)) 5691 return false; 5692 } else { 5693 // The declaration is extern "C". Check for any declaration in the 5694 // translation unit which might conflict. 5695 if (IsGlobal) { 5696 // We have already performed the lookup into the translation unit. 5697 IsGlobal = false; 5698 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5699 I != E; ++I) { 5700 if (isa<VarDecl>(*I)) { 5701 Prev = *I; 5702 break; 5703 } 5704 } 5705 } else { 5706 DeclContext::lookup_result R = 5707 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5708 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5709 I != E; ++I) { 5710 if (isa<VarDecl>(*I)) { 5711 Prev = *I; 5712 break; 5713 } 5714 // FIXME: If we have any other entity with this name in global scope, 5715 // the declaration is ill-formed, but that is a defect: it breaks the 5716 // 'stat' hack, for instance. Only variables can have mangled name 5717 // clashes with extern "C" declarations, so only they deserve a 5718 // diagnostic. 5719 } 5720 } 5721 5722 if (!Prev) 5723 return false; 5724 } 5725 5726 // Use the first declaration's location to ensure we point at something which 5727 // is lexically inside an extern "C" linkage-spec. 5728 assert(Prev && "should have found a previous declaration to diagnose"); 5729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5730 Prev = FD->getFirstDecl(); 5731 else 5732 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5733 5734 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5735 << IsGlobal << ND; 5736 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5737 << IsGlobal; 5738 return false; 5739 } 5740 5741 /// Apply special rules for handling extern "C" declarations. Returns \c true 5742 /// if we have found that this is a redeclaration of some prior entity. 5743 /// 5744 /// Per C++ [dcl.link]p6: 5745 /// Two declarations [for a function or variable] with C language linkage 5746 /// with the same name that appear in different scopes refer to the same 5747 /// [entity]. An entity with C language linkage shall not be declared with 5748 /// the same name as an entity in global scope. 5749 template<typename T> 5750 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5751 LookupResult &Previous) { 5752 if (!S.getLangOpts().CPlusPlus) { 5753 // In C, when declaring a global variable, look for a corresponding 'extern' 5754 // variable declared in function scope. We don't need this in C++, because 5755 // we find local extern decls in the surrounding file-scope DeclContext. 5756 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5757 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5758 Previous.clear(); 5759 Previous.addDecl(Prev); 5760 return true; 5761 } 5762 } 5763 return false; 5764 } 5765 5766 // A declaration in the translation unit can conflict with an extern "C" 5767 // declaration. 5768 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5769 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5770 5771 // An extern "C" declaration can conflict with a declaration in the 5772 // translation unit or can be a redeclaration of an extern "C" declaration 5773 // in another scope. 5774 if (isIncompleteDeclExternC(S,ND)) 5775 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5776 5777 // Neither global nor extern "C": nothing to do. 5778 return false; 5779 } 5780 5781 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5782 // If the decl is already known invalid, don't check it. 5783 if (NewVD->isInvalidDecl()) 5784 return; 5785 5786 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5787 QualType T = TInfo->getType(); 5788 5789 // Defer checking an 'auto' type until its initializer is attached. 5790 if (T->isUndeducedType()) 5791 return; 5792 5793 if (NewVD->hasAttrs()) 5794 CheckAlignasUnderalignment(NewVD); 5795 5796 if (T->isObjCObjectType()) { 5797 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5798 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5799 T = Context.getObjCObjectPointerType(T); 5800 NewVD->setType(T); 5801 } 5802 5803 // Emit an error if an address space was applied to decl with local storage. 5804 // This includes arrays of objects with address space qualifiers, but not 5805 // automatic variables that point to other address spaces. 5806 // ISO/IEC TR 18037 S5.1.2 5807 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5808 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5809 NewVD->setInvalidDecl(); 5810 return; 5811 } 5812 5813 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5814 // __constant address space. 5815 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5816 && T.getAddressSpace() != LangAS::opencl_constant 5817 && !T->isSamplerT()){ 5818 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5819 NewVD->setInvalidDecl(); 5820 return; 5821 } 5822 5823 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5824 // scope. 5825 if ((getLangOpts().OpenCLVersion >= 120) 5826 && NewVD->isStaticLocal()) { 5827 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5828 NewVD->setInvalidDecl(); 5829 return; 5830 } 5831 5832 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5833 && !NewVD->hasAttr<BlocksAttr>()) { 5834 if (getLangOpts().getGC() != LangOptions::NonGC) 5835 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5836 else { 5837 assert(!getLangOpts().ObjCAutoRefCount); 5838 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5839 } 5840 } 5841 5842 bool isVM = T->isVariablyModifiedType(); 5843 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5844 NewVD->hasAttr<BlocksAttr>()) 5845 getCurFunction()->setHasBranchProtectedScope(); 5846 5847 if ((isVM && NewVD->hasLinkage()) || 5848 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5849 bool SizeIsNegative; 5850 llvm::APSInt Oversized; 5851 TypeSourceInfo *FixedTInfo = 5852 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5853 SizeIsNegative, Oversized); 5854 if (FixedTInfo == 0 && T->isVariableArrayType()) { 5855 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5856 // FIXME: This won't give the correct result for 5857 // int a[10][n]; 5858 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5859 5860 if (NewVD->isFileVarDecl()) 5861 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5862 << SizeRange; 5863 else if (NewVD->isStaticLocal()) 5864 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5865 << SizeRange; 5866 else 5867 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5868 << SizeRange; 5869 NewVD->setInvalidDecl(); 5870 return; 5871 } 5872 5873 if (FixedTInfo == 0) { 5874 if (NewVD->isFileVarDecl()) 5875 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5876 else 5877 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5878 NewVD->setInvalidDecl(); 5879 return; 5880 } 5881 5882 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5883 NewVD->setType(FixedTInfo->getType()); 5884 NewVD->setTypeSourceInfo(FixedTInfo); 5885 } 5886 5887 if (T->isVoidType()) { 5888 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5889 // of objects and functions. 5890 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5891 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5892 << T; 5893 NewVD->setInvalidDecl(); 5894 return; 5895 } 5896 } 5897 5898 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5899 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5900 NewVD->setInvalidDecl(); 5901 return; 5902 } 5903 5904 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5905 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5906 NewVD->setInvalidDecl(); 5907 return; 5908 } 5909 5910 if (NewVD->isConstexpr() && !T->isDependentType() && 5911 RequireLiteralType(NewVD->getLocation(), T, 5912 diag::err_constexpr_var_non_literal)) { 5913 NewVD->setInvalidDecl(); 5914 return; 5915 } 5916 } 5917 5918 /// \brief Perform semantic checking on a newly-created variable 5919 /// declaration. 5920 /// 5921 /// This routine performs all of the type-checking required for a 5922 /// variable declaration once it has been built. It is used both to 5923 /// check variables after they have been parsed and their declarators 5924 /// have been translated into a declaration, and to check variables 5925 /// that have been instantiated from a template. 5926 /// 5927 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5928 /// 5929 /// Returns true if the variable declaration is a redeclaration. 5930 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5931 CheckVariableDeclarationType(NewVD); 5932 5933 // If the decl is already known invalid, don't check it. 5934 if (NewVD->isInvalidDecl()) 5935 return false; 5936 5937 // If we did not find anything by this name, look for a non-visible 5938 // extern "C" declaration with the same name. 5939 if (Previous.empty() && 5940 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 5941 Previous.setShadowed(); 5942 5943 // Filter out any non-conflicting previous declarations. 5944 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 5945 5946 if (!Previous.empty()) { 5947 MergeVarDecl(NewVD, Previous); 5948 return true; 5949 } 5950 return false; 5951 } 5952 5953 /// \brief Data used with FindOverriddenMethod 5954 struct FindOverriddenMethodData { 5955 Sema *S; 5956 CXXMethodDecl *Method; 5957 }; 5958 5959 /// \brief Member lookup function that determines whether a given C++ 5960 /// method overrides a method in a base class, to be used with 5961 /// CXXRecordDecl::lookupInBases(). 5962 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 5963 CXXBasePath &Path, 5964 void *UserData) { 5965 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5966 5967 FindOverriddenMethodData *Data 5968 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 5969 5970 DeclarationName Name = Data->Method->getDeclName(); 5971 5972 // FIXME: Do we care about other names here too? 5973 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 5974 // We really want to find the base class destructor here. 5975 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 5976 CanQualType CT = Data->S->Context.getCanonicalType(T); 5977 5978 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 5979 } 5980 5981 for (Path.Decls = BaseRecord->lookup(Name); 5982 !Path.Decls.empty(); 5983 Path.Decls = Path.Decls.slice(1)) { 5984 NamedDecl *D = Path.Decls.front(); 5985 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5986 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 5987 return true; 5988 } 5989 } 5990 5991 return false; 5992 } 5993 5994 namespace { 5995 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 5996 } 5997 /// \brief Report an error regarding overriding, along with any relevant 5998 /// overriden methods. 5999 /// 6000 /// \param DiagID the primary error to report. 6001 /// \param MD the overriding method. 6002 /// \param OEK which overrides to include as notes. 6003 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6004 OverrideErrorKind OEK = OEK_All) { 6005 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6006 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6007 E = MD->end_overridden_methods(); 6008 I != E; ++I) { 6009 // This check (& the OEK parameter) could be replaced by a predicate, but 6010 // without lambdas that would be overkill. This is still nicer than writing 6011 // out the diag loop 3 times. 6012 if ((OEK == OEK_All) || 6013 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6014 (OEK == OEK_Deleted && (*I)->isDeleted())) 6015 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6016 } 6017 } 6018 6019 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6020 /// and if so, check that it's a valid override and remember it. 6021 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6022 // Look for virtual methods in base classes that this method might override. 6023 CXXBasePaths Paths; 6024 FindOverriddenMethodData Data; 6025 Data.Method = MD; 6026 Data.S = this; 6027 bool hasDeletedOverridenMethods = false; 6028 bool hasNonDeletedOverridenMethods = false; 6029 bool AddedAny = false; 6030 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6031 for (auto *I : Paths.found_decls()) { 6032 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6033 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6034 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6035 !CheckOverridingFunctionAttributes(MD, OldMD) && 6036 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6037 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6038 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6039 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6040 AddedAny = true; 6041 } 6042 } 6043 } 6044 } 6045 6046 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6047 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6048 } 6049 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6050 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6051 } 6052 6053 return AddedAny; 6054 } 6055 6056 namespace { 6057 // Struct for holding all of the extra arguments needed by 6058 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6059 struct ActOnFDArgs { 6060 Scope *S; 6061 Declarator &D; 6062 MultiTemplateParamsArg TemplateParamLists; 6063 bool AddToScope; 6064 }; 6065 } 6066 6067 namespace { 6068 6069 // Callback to only accept typo corrections that have a non-zero edit distance. 6070 // Also only accept corrections that have the same parent decl. 6071 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6072 public: 6073 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6074 CXXRecordDecl *Parent) 6075 : Context(Context), OriginalFD(TypoFD), 6076 ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 6077 6078 bool ValidateCandidate(const TypoCorrection &candidate) override { 6079 if (candidate.getEditDistance() == 0) 6080 return false; 6081 6082 SmallVector<unsigned, 1> MismatchedParams; 6083 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6084 CDeclEnd = candidate.end(); 6085 CDecl != CDeclEnd; ++CDecl) { 6086 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6087 6088 if (FD && !FD->hasBody() && 6089 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6090 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6091 CXXRecordDecl *Parent = MD->getParent(); 6092 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6093 return true; 6094 } else if (!ExpectedParent) { 6095 return true; 6096 } 6097 } 6098 } 6099 6100 return false; 6101 } 6102 6103 private: 6104 ASTContext &Context; 6105 FunctionDecl *OriginalFD; 6106 CXXRecordDecl *ExpectedParent; 6107 }; 6108 6109 } 6110 6111 /// \brief Generate diagnostics for an invalid function redeclaration. 6112 /// 6113 /// This routine handles generating the diagnostic messages for an invalid 6114 /// function redeclaration, including finding possible similar declarations 6115 /// or performing typo correction if there are no previous declarations with 6116 /// the same name. 6117 /// 6118 /// Returns a NamedDecl iff typo correction was performed and substituting in 6119 /// the new declaration name does not cause new errors. 6120 static NamedDecl *DiagnoseInvalidRedeclaration( 6121 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6122 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6123 DeclarationName Name = NewFD->getDeclName(); 6124 DeclContext *NewDC = NewFD->getDeclContext(); 6125 SmallVector<unsigned, 1> MismatchedParams; 6126 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6127 TypoCorrection Correction; 6128 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6129 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6130 : diag::err_member_decl_does_not_match; 6131 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6132 IsLocalFriend ? Sema::LookupLocalFriendName 6133 : Sema::LookupOrdinaryName, 6134 Sema::ForRedeclaration); 6135 6136 NewFD->setInvalidDecl(); 6137 if (IsLocalFriend) 6138 SemaRef.LookupName(Prev, S); 6139 else 6140 SemaRef.LookupQualifiedName(Prev, NewDC); 6141 assert(!Prev.isAmbiguous() && 6142 "Cannot have an ambiguity in previous-declaration lookup"); 6143 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6144 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6145 MD ? MD->getParent() : 0); 6146 if (!Prev.empty()) { 6147 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6148 Func != FuncEnd; ++Func) { 6149 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6150 if (FD && 6151 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6152 // Add 1 to the index so that 0 can mean the mismatch didn't 6153 // involve a parameter 6154 unsigned ParamNum = 6155 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6156 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6157 } 6158 } 6159 // If the qualified name lookup yielded nothing, try typo correction 6160 } else if ((Correction = SemaRef.CorrectTypo( 6161 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6162 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6163 IsLocalFriend ? 0 : NewDC))) { 6164 // Set up everything for the call to ActOnFunctionDeclarator 6165 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6166 ExtraArgs.D.getIdentifierLoc()); 6167 Previous.clear(); 6168 Previous.setLookupName(Correction.getCorrection()); 6169 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6170 CDeclEnd = Correction.end(); 6171 CDecl != CDeclEnd; ++CDecl) { 6172 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6173 if (FD && !FD->hasBody() && 6174 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6175 Previous.addDecl(FD); 6176 } 6177 } 6178 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6179 6180 NamedDecl *Result; 6181 // Retry building the function declaration with the new previous 6182 // declarations, and with errors suppressed. 6183 { 6184 // Trap errors. 6185 Sema::SFINAETrap Trap(SemaRef); 6186 6187 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6188 // pieces need to verify the typo-corrected C++ declaration and hopefully 6189 // eliminate the need for the parameter pack ExtraArgs. 6190 Result = SemaRef.ActOnFunctionDeclarator( 6191 ExtraArgs.S, ExtraArgs.D, 6192 Correction.getCorrectionDecl()->getDeclContext(), 6193 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6194 ExtraArgs.AddToScope); 6195 6196 if (Trap.hasErrorOccurred()) 6197 Result = 0; 6198 } 6199 6200 if (Result) { 6201 // Determine which correction we picked. 6202 Decl *Canonical = Result->getCanonicalDecl(); 6203 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6204 I != E; ++I) 6205 if ((*I)->getCanonicalDecl() == Canonical) 6206 Correction.setCorrectionDecl(*I); 6207 6208 SemaRef.diagnoseTypo( 6209 Correction, 6210 SemaRef.PDiag(IsLocalFriend 6211 ? diag::err_no_matching_local_friend_suggest 6212 : diag::err_member_decl_does_not_match_suggest) 6213 << Name << NewDC << IsDefinition); 6214 return Result; 6215 } 6216 6217 // Pretend the typo correction never occurred 6218 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6219 ExtraArgs.D.getIdentifierLoc()); 6220 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6221 Previous.clear(); 6222 Previous.setLookupName(Name); 6223 } 6224 6225 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6226 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6227 6228 bool NewFDisConst = false; 6229 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6230 NewFDisConst = NewMD->isConst(); 6231 6232 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6233 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6234 NearMatch != NearMatchEnd; ++NearMatch) { 6235 FunctionDecl *FD = NearMatch->first; 6236 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6237 bool FDisConst = MD && MD->isConst(); 6238 bool IsMember = MD || !IsLocalFriend; 6239 6240 // FIXME: These notes are poorly worded for the local friend case. 6241 if (unsigned Idx = NearMatch->second) { 6242 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6243 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6244 if (Loc.isInvalid()) Loc = FD->getLocation(); 6245 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6246 : diag::note_local_decl_close_param_match) 6247 << Idx << FDParam->getType() 6248 << NewFD->getParamDecl(Idx - 1)->getType(); 6249 } else if (FDisConst != NewFDisConst) { 6250 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6251 << NewFDisConst << FD->getSourceRange().getEnd(); 6252 } else 6253 SemaRef.Diag(FD->getLocation(), 6254 IsMember ? diag::note_member_def_close_match 6255 : diag::note_local_decl_close_match); 6256 } 6257 return 0; 6258 } 6259 6260 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6261 Declarator &D) { 6262 switch (D.getDeclSpec().getStorageClassSpec()) { 6263 default: llvm_unreachable("Unknown storage class!"); 6264 case DeclSpec::SCS_auto: 6265 case DeclSpec::SCS_register: 6266 case DeclSpec::SCS_mutable: 6267 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6268 diag::err_typecheck_sclass_func); 6269 D.setInvalidType(); 6270 break; 6271 case DeclSpec::SCS_unspecified: break; 6272 case DeclSpec::SCS_extern: 6273 if (D.getDeclSpec().isExternInLinkageSpec()) 6274 return SC_None; 6275 return SC_Extern; 6276 case DeclSpec::SCS_static: { 6277 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6278 // C99 6.7.1p5: 6279 // The declaration of an identifier for a function that has 6280 // block scope shall have no explicit storage-class specifier 6281 // other than extern 6282 // See also (C++ [dcl.stc]p4). 6283 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6284 diag::err_static_block_func); 6285 break; 6286 } else 6287 return SC_Static; 6288 } 6289 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6290 } 6291 6292 // No explicit storage class has already been returned 6293 return SC_None; 6294 } 6295 6296 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6297 DeclContext *DC, QualType &R, 6298 TypeSourceInfo *TInfo, 6299 FunctionDecl::StorageClass SC, 6300 bool &IsVirtualOkay) { 6301 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6302 DeclarationName Name = NameInfo.getName(); 6303 6304 FunctionDecl *NewFD = 0; 6305 bool isInline = D.getDeclSpec().isInlineSpecified(); 6306 6307 if (!SemaRef.getLangOpts().CPlusPlus) { 6308 // Determine whether the function was written with a 6309 // prototype. This true when: 6310 // - there is a prototype in the declarator, or 6311 // - the type R of the function is some kind of typedef or other reference 6312 // to a type name (which eventually refers to a function type). 6313 bool HasPrototype = 6314 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6315 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6316 6317 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6318 D.getLocStart(), NameInfo, R, 6319 TInfo, SC, isInline, 6320 HasPrototype, false); 6321 if (D.isInvalidType()) 6322 NewFD->setInvalidDecl(); 6323 6324 // Set the lexical context. 6325 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6326 6327 return NewFD; 6328 } 6329 6330 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6331 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6332 6333 // Check that the return type is not an abstract class type. 6334 // For record types, this is done by the AbstractClassUsageDiagnoser once 6335 // the class has been completely parsed. 6336 if (!DC->isRecord() && 6337 SemaRef.RequireNonAbstractType( 6338 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6339 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6340 D.setInvalidType(); 6341 6342 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6343 // This is a C++ constructor declaration. 6344 assert(DC->isRecord() && 6345 "Constructors can only be declared in a member context"); 6346 6347 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6348 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6349 D.getLocStart(), NameInfo, 6350 R, TInfo, isExplicit, isInline, 6351 /*isImplicitlyDeclared=*/false, 6352 isConstexpr); 6353 6354 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6355 // This is a C++ destructor declaration. 6356 if (DC->isRecord()) { 6357 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6358 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6359 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6360 SemaRef.Context, Record, 6361 D.getLocStart(), 6362 NameInfo, R, TInfo, isInline, 6363 /*isImplicitlyDeclared=*/false); 6364 6365 // If the class is complete, then we now create the implicit exception 6366 // specification. If the class is incomplete or dependent, we can't do 6367 // it yet. 6368 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6369 Record->getDefinition() && !Record->isBeingDefined() && 6370 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6371 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6372 } 6373 6374 IsVirtualOkay = true; 6375 return NewDD; 6376 6377 } else { 6378 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6379 D.setInvalidType(); 6380 6381 // Create a FunctionDecl to satisfy the function definition parsing 6382 // code path. 6383 return FunctionDecl::Create(SemaRef.Context, DC, 6384 D.getLocStart(), 6385 D.getIdentifierLoc(), Name, R, TInfo, 6386 SC, isInline, 6387 /*hasPrototype=*/true, isConstexpr); 6388 } 6389 6390 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6391 if (!DC->isRecord()) { 6392 SemaRef.Diag(D.getIdentifierLoc(), 6393 diag::err_conv_function_not_member); 6394 return 0; 6395 } 6396 6397 SemaRef.CheckConversionDeclarator(D, R, SC); 6398 IsVirtualOkay = true; 6399 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6400 D.getLocStart(), NameInfo, 6401 R, TInfo, isInline, isExplicit, 6402 isConstexpr, SourceLocation()); 6403 6404 } else if (DC->isRecord()) { 6405 // If the name of the function is the same as the name of the record, 6406 // then this must be an invalid constructor that has a return type. 6407 // (The parser checks for a return type and makes the declarator a 6408 // constructor if it has no return type). 6409 if (Name.getAsIdentifierInfo() && 6410 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6411 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6412 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6413 << SourceRange(D.getIdentifierLoc()); 6414 return 0; 6415 } 6416 6417 // This is a C++ method declaration. 6418 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6419 cast<CXXRecordDecl>(DC), 6420 D.getLocStart(), NameInfo, R, 6421 TInfo, SC, isInline, 6422 isConstexpr, SourceLocation()); 6423 IsVirtualOkay = !Ret->isStatic(); 6424 return Ret; 6425 } else { 6426 // Determine whether the function was written with a 6427 // prototype. This true when: 6428 // - we're in C++ (where every function has a prototype), 6429 return FunctionDecl::Create(SemaRef.Context, DC, 6430 D.getLocStart(), 6431 NameInfo, R, TInfo, SC, isInline, 6432 true/*HasPrototype*/, isConstexpr); 6433 } 6434 } 6435 6436 enum OpenCLParamType { 6437 ValidKernelParam, 6438 PtrPtrKernelParam, 6439 PtrKernelParam, 6440 PrivatePtrKernelParam, 6441 InvalidKernelParam, 6442 RecordKernelParam 6443 }; 6444 6445 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6446 if (PT->isPointerType()) { 6447 QualType PointeeType = PT->getPointeeType(); 6448 if (PointeeType->isPointerType()) 6449 return PtrPtrKernelParam; 6450 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6451 : PtrKernelParam; 6452 } 6453 6454 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6455 // be used as builtin types. 6456 6457 if (PT->isImageType()) 6458 return PtrKernelParam; 6459 6460 if (PT->isBooleanType()) 6461 return InvalidKernelParam; 6462 6463 if (PT->isEventT()) 6464 return InvalidKernelParam; 6465 6466 if (PT->isHalfType()) 6467 return InvalidKernelParam; 6468 6469 if (PT->isRecordType()) 6470 return RecordKernelParam; 6471 6472 return ValidKernelParam; 6473 } 6474 6475 static void checkIsValidOpenCLKernelParameter( 6476 Sema &S, 6477 Declarator &D, 6478 ParmVarDecl *Param, 6479 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6480 QualType PT = Param->getType(); 6481 6482 // Cache the valid types we encounter to avoid rechecking structs that are 6483 // used again 6484 if (ValidTypes.count(PT.getTypePtr())) 6485 return; 6486 6487 switch (getOpenCLKernelParameterType(PT)) { 6488 case PtrPtrKernelParam: 6489 // OpenCL v1.2 s6.9.a: 6490 // A kernel function argument cannot be declared as a 6491 // pointer to a pointer type. 6492 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6493 D.setInvalidType(); 6494 return; 6495 6496 case PrivatePtrKernelParam: 6497 // OpenCL v1.2 s6.9.a: 6498 // A kernel function argument cannot be declared as a 6499 // pointer to the private address space. 6500 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6501 D.setInvalidType(); 6502 return; 6503 6504 // OpenCL v1.2 s6.9.k: 6505 // Arguments to kernel functions in a program cannot be declared with the 6506 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6507 // uintptr_t or a struct and/or union that contain fields declared to be 6508 // one of these built-in scalar types. 6509 6510 case InvalidKernelParam: 6511 // OpenCL v1.2 s6.8 n: 6512 // A kernel function argument cannot be declared 6513 // of event_t type. 6514 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6515 D.setInvalidType(); 6516 return; 6517 6518 case PtrKernelParam: 6519 case ValidKernelParam: 6520 ValidTypes.insert(PT.getTypePtr()); 6521 return; 6522 6523 case RecordKernelParam: 6524 break; 6525 } 6526 6527 // Track nested structs we will inspect 6528 SmallVector<const Decl *, 4> VisitStack; 6529 6530 // Track where we are in the nested structs. Items will migrate from 6531 // VisitStack to HistoryStack as we do the DFS for bad field. 6532 SmallVector<const FieldDecl *, 4> HistoryStack; 6533 HistoryStack.push_back((const FieldDecl *) 0); 6534 6535 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6536 VisitStack.push_back(PD); 6537 6538 assert(VisitStack.back() && "First decl null?"); 6539 6540 do { 6541 const Decl *Next = VisitStack.pop_back_val(); 6542 if (!Next) { 6543 assert(!HistoryStack.empty()); 6544 // Found a marker, we have gone up a level 6545 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6546 ValidTypes.insert(Hist->getType().getTypePtr()); 6547 6548 continue; 6549 } 6550 6551 // Adds everything except the original parameter declaration (which is not a 6552 // field itself) to the history stack. 6553 const RecordDecl *RD; 6554 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6555 HistoryStack.push_back(Field); 6556 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6557 } else { 6558 RD = cast<RecordDecl>(Next); 6559 } 6560 6561 // Add a null marker so we know when we've gone back up a level 6562 VisitStack.push_back((const Decl *) 0); 6563 6564 for (const auto *FD : RD->fields()) { 6565 QualType QT = FD->getType(); 6566 6567 if (ValidTypes.count(QT.getTypePtr())) 6568 continue; 6569 6570 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6571 if (ParamType == ValidKernelParam) 6572 continue; 6573 6574 if (ParamType == RecordKernelParam) { 6575 VisitStack.push_back(FD); 6576 continue; 6577 } 6578 6579 // OpenCL v1.2 s6.9.p: 6580 // Arguments to kernel functions that are declared to be a struct or union 6581 // do not allow OpenCL objects to be passed as elements of the struct or 6582 // union. 6583 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6584 ParamType == PrivatePtrKernelParam) { 6585 S.Diag(Param->getLocation(), 6586 diag::err_record_with_pointers_kernel_param) 6587 << PT->isUnionType() 6588 << PT; 6589 } else { 6590 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6591 } 6592 6593 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6594 << PD->getDeclName(); 6595 6596 // We have an error, now let's go back up through history and show where 6597 // the offending field came from 6598 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6599 E = HistoryStack.end(); I != E; ++I) { 6600 const FieldDecl *OuterField = *I; 6601 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6602 << OuterField->getType(); 6603 } 6604 6605 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6606 << QT->isPointerType() 6607 << QT; 6608 D.setInvalidType(); 6609 return; 6610 } 6611 } while (!VisitStack.empty()); 6612 } 6613 6614 NamedDecl* 6615 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6616 TypeSourceInfo *TInfo, LookupResult &Previous, 6617 MultiTemplateParamsArg TemplateParamLists, 6618 bool &AddToScope) { 6619 QualType R = TInfo->getType(); 6620 6621 assert(R.getTypePtr()->isFunctionType()); 6622 6623 // TODO: consider using NameInfo for diagnostic. 6624 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6625 DeclarationName Name = NameInfo.getName(); 6626 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6627 6628 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6629 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6630 diag::err_invalid_thread) 6631 << DeclSpec::getSpecifierName(TSCS); 6632 6633 if (D.isFirstDeclarationOfMember()) 6634 adjustMemberFunctionCC(R, D.isStaticMember()); 6635 6636 bool isFriend = false; 6637 FunctionTemplateDecl *FunctionTemplate = 0; 6638 bool isExplicitSpecialization = false; 6639 bool isFunctionTemplateSpecialization = false; 6640 6641 bool isDependentClassScopeExplicitSpecialization = false; 6642 bool HasExplicitTemplateArgs = false; 6643 TemplateArgumentListInfo TemplateArgs; 6644 6645 bool isVirtualOkay = false; 6646 6647 DeclContext *OriginalDC = DC; 6648 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6649 6650 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6651 isVirtualOkay); 6652 if (!NewFD) return 0; 6653 6654 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6655 NewFD->setTopLevelDeclInObjCContainer(); 6656 6657 // Set the lexical context. If this is a function-scope declaration, or has a 6658 // C++ scope specifier, or is the object of a friend declaration, the lexical 6659 // context will be different from the semantic context. 6660 NewFD->setLexicalDeclContext(CurContext); 6661 6662 if (IsLocalExternDecl) 6663 NewFD->setLocalExternDecl(); 6664 6665 if (getLangOpts().CPlusPlus) { 6666 bool isInline = D.getDeclSpec().isInlineSpecified(); 6667 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6668 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6669 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6670 isFriend = D.getDeclSpec().isFriendSpecified(); 6671 if (isFriend && !isInline && D.isFunctionDefinition()) { 6672 // C++ [class.friend]p5 6673 // A function can be defined in a friend declaration of a 6674 // class . . . . Such a function is implicitly inline. 6675 NewFD->setImplicitlyInline(); 6676 } 6677 6678 // If this is a method defined in an __interface, and is not a constructor 6679 // or an overloaded operator, then set the pure flag (isVirtual will already 6680 // return true). 6681 if (const CXXRecordDecl *Parent = 6682 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6683 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6684 NewFD->setPure(true); 6685 } 6686 6687 SetNestedNameSpecifier(NewFD, D); 6688 isExplicitSpecialization = false; 6689 isFunctionTemplateSpecialization = false; 6690 if (D.isInvalidType()) 6691 NewFD->setInvalidDecl(); 6692 6693 // Match up the template parameter lists with the scope specifier, then 6694 // determine whether we have a template or a template specialization. 6695 bool Invalid = false; 6696 if (TemplateParameterList *TemplateParams = 6697 MatchTemplateParametersToScopeSpecifier( 6698 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6699 D.getCXXScopeSpec(), 6700 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6701 ? D.getName().TemplateId 6702 : 0, 6703 TemplateParamLists, isFriend, isExplicitSpecialization, 6704 Invalid)) { 6705 if (TemplateParams->size() > 0) { 6706 // This is a function template 6707 6708 // Check that we can declare a template here. 6709 if (CheckTemplateDeclScope(S, TemplateParams)) 6710 return 0; 6711 6712 // A destructor cannot be a template. 6713 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6714 Diag(NewFD->getLocation(), diag::err_destructor_template); 6715 return 0; 6716 } 6717 6718 // If we're adding a template to a dependent context, we may need to 6719 // rebuilding some of the types used within the template parameter list, 6720 // now that we know what the current instantiation is. 6721 if (DC->isDependentContext()) { 6722 ContextRAII SavedContext(*this, DC); 6723 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6724 Invalid = true; 6725 } 6726 6727 6728 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6729 NewFD->getLocation(), 6730 Name, TemplateParams, 6731 NewFD); 6732 FunctionTemplate->setLexicalDeclContext(CurContext); 6733 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6734 6735 // For source fidelity, store the other template param lists. 6736 if (TemplateParamLists.size() > 1) { 6737 NewFD->setTemplateParameterListsInfo(Context, 6738 TemplateParamLists.size() - 1, 6739 TemplateParamLists.data()); 6740 } 6741 } else { 6742 // This is a function template specialization. 6743 isFunctionTemplateSpecialization = true; 6744 // For source fidelity, store all the template param lists. 6745 if (TemplateParamLists.size() > 0) 6746 NewFD->setTemplateParameterListsInfo(Context, 6747 TemplateParamLists.size(), 6748 TemplateParamLists.data()); 6749 6750 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6751 if (isFriend) { 6752 // We want to remove the "template<>", found here. 6753 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6754 6755 // If we remove the template<> and the name is not a 6756 // template-id, we're actually silently creating a problem: 6757 // the friend declaration will refer to an untemplated decl, 6758 // and clearly the user wants a template specialization. So 6759 // we need to insert '<>' after the name. 6760 SourceLocation InsertLoc; 6761 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6762 InsertLoc = D.getName().getSourceRange().getEnd(); 6763 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 6764 } 6765 6766 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6767 << Name << RemoveRange 6768 << FixItHint::CreateRemoval(RemoveRange) 6769 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6770 } 6771 } 6772 } 6773 else { 6774 // All template param lists were matched against the scope specifier: 6775 // this is NOT (an explicit specialization of) a template. 6776 if (TemplateParamLists.size() > 0) 6777 // For source fidelity, store all the template param lists. 6778 NewFD->setTemplateParameterListsInfo(Context, 6779 TemplateParamLists.size(), 6780 TemplateParamLists.data()); 6781 } 6782 6783 if (Invalid) { 6784 NewFD->setInvalidDecl(); 6785 if (FunctionTemplate) 6786 FunctionTemplate->setInvalidDecl(); 6787 } 6788 6789 // C++ [dcl.fct.spec]p5: 6790 // The virtual specifier shall only be used in declarations of 6791 // nonstatic class member functions that appear within a 6792 // member-specification of a class declaration; see 10.3. 6793 // 6794 if (isVirtual && !NewFD->isInvalidDecl()) { 6795 if (!isVirtualOkay) { 6796 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6797 diag::err_virtual_non_function); 6798 } else if (!CurContext->isRecord()) { 6799 // 'virtual' was specified outside of the class. 6800 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6801 diag::err_virtual_out_of_class) 6802 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6803 } else if (NewFD->getDescribedFunctionTemplate()) { 6804 // C++ [temp.mem]p3: 6805 // A member function template shall not be virtual. 6806 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6807 diag::err_virtual_member_function_template) 6808 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6809 } else { 6810 // Okay: Add virtual to the method. 6811 NewFD->setVirtualAsWritten(true); 6812 } 6813 6814 if (getLangOpts().CPlusPlus1y && 6815 NewFD->getReturnType()->isUndeducedType()) 6816 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6817 } 6818 6819 if (getLangOpts().CPlusPlus1y && 6820 (NewFD->isDependentContext() || 6821 (isFriend && CurContext->isDependentContext())) && 6822 NewFD->getReturnType()->isUndeducedType()) { 6823 // If the function template is referenced directly (for instance, as a 6824 // member of the current instantiation), pretend it has a dependent type. 6825 // This is not really justified by the standard, but is the only sane 6826 // thing to do. 6827 // FIXME: For a friend function, we have not marked the function as being 6828 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6829 const FunctionProtoType *FPT = 6830 NewFD->getType()->castAs<FunctionProtoType>(); 6831 QualType Result = 6832 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6833 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6834 FPT->getExtProtoInfo())); 6835 } 6836 6837 // C++ [dcl.fct.spec]p3: 6838 // The inline specifier shall not appear on a block scope function 6839 // declaration. 6840 if (isInline && !NewFD->isInvalidDecl()) { 6841 if (CurContext->isFunctionOrMethod()) { 6842 // 'inline' is not allowed on block scope function declaration. 6843 Diag(D.getDeclSpec().getInlineSpecLoc(), 6844 diag::err_inline_declaration_block_scope) << Name 6845 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6846 } 6847 } 6848 6849 // C++ [dcl.fct.spec]p6: 6850 // The explicit specifier shall be used only in the declaration of a 6851 // constructor or conversion function within its class definition; 6852 // see 12.3.1 and 12.3.2. 6853 if (isExplicit && !NewFD->isInvalidDecl()) { 6854 if (!CurContext->isRecord()) { 6855 // 'explicit' was specified outside of the class. 6856 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6857 diag::err_explicit_out_of_class) 6858 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6859 } else if (!isa<CXXConstructorDecl>(NewFD) && 6860 !isa<CXXConversionDecl>(NewFD)) { 6861 // 'explicit' was specified on a function that wasn't a constructor 6862 // or conversion function. 6863 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6864 diag::err_explicit_non_ctor_or_conv_function) 6865 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6866 } 6867 } 6868 6869 if (isConstexpr) { 6870 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6871 // are implicitly inline. 6872 NewFD->setImplicitlyInline(); 6873 6874 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6875 // be either constructors or to return a literal type. Therefore, 6876 // destructors cannot be declared constexpr. 6877 if (isa<CXXDestructorDecl>(NewFD)) 6878 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6879 } 6880 6881 // If __module_private__ was specified, mark the function accordingly. 6882 if (D.getDeclSpec().isModulePrivateSpecified()) { 6883 if (isFunctionTemplateSpecialization) { 6884 SourceLocation ModulePrivateLoc 6885 = D.getDeclSpec().getModulePrivateSpecLoc(); 6886 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6887 << 0 6888 << FixItHint::CreateRemoval(ModulePrivateLoc); 6889 } else { 6890 NewFD->setModulePrivate(); 6891 if (FunctionTemplate) 6892 FunctionTemplate->setModulePrivate(); 6893 } 6894 } 6895 6896 if (isFriend) { 6897 if (FunctionTemplate) { 6898 FunctionTemplate->setObjectOfFriendDecl(); 6899 FunctionTemplate->setAccess(AS_public); 6900 } 6901 NewFD->setObjectOfFriendDecl(); 6902 NewFD->setAccess(AS_public); 6903 } 6904 6905 // If a function is defined as defaulted or deleted, mark it as such now. 6906 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6907 // definition kind to FDK_Definition. 6908 switch (D.getFunctionDefinitionKind()) { 6909 case FDK_Declaration: 6910 case FDK_Definition: 6911 break; 6912 6913 case FDK_Defaulted: 6914 NewFD->setDefaulted(); 6915 break; 6916 6917 case FDK_Deleted: 6918 NewFD->setDeletedAsWritten(); 6919 break; 6920 } 6921 6922 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6923 D.isFunctionDefinition()) { 6924 // C++ [class.mfct]p2: 6925 // A member function may be defined (8.4) in its class definition, in 6926 // which case it is an inline member function (7.1.2) 6927 NewFD->setImplicitlyInline(); 6928 } 6929 6930 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6931 !CurContext->isRecord()) { 6932 // C++ [class.static]p1: 6933 // A data or function member of a class may be declared static 6934 // in a class definition, in which case it is a static member of 6935 // the class. 6936 6937 // Complain about the 'static' specifier if it's on an out-of-line 6938 // member function definition. 6939 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6940 diag::err_static_out_of_line) 6941 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6942 } 6943 6944 // C++11 [except.spec]p15: 6945 // A deallocation function with no exception-specification is treated 6946 // as if it were specified with noexcept(true). 6947 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 6948 if ((Name.getCXXOverloadedOperator() == OO_Delete || 6949 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 6950 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 6951 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6952 EPI.ExceptionSpecType = EST_BasicNoexcept; 6953 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 6954 FPT->getParamTypes(), EPI)); 6955 } 6956 } 6957 6958 // Filter out previous declarations that don't match the scope. 6959 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 6960 D.getCXXScopeSpec().isNotEmpty() || 6961 isExplicitSpecialization || 6962 isFunctionTemplateSpecialization); 6963 6964 // Handle GNU asm-label extension (encoded as an attribute). 6965 if (Expr *E = (Expr*) D.getAsmLabel()) { 6966 // The parser guarantees this is a string. 6967 StringLiteral *SE = cast<StringLiteral>(E); 6968 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 6969 SE->getString(), 0)); 6970 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6971 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6972 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 6973 if (I != ExtnameUndeclaredIdentifiers.end()) { 6974 NewFD->addAttr(I->second); 6975 ExtnameUndeclaredIdentifiers.erase(I); 6976 } 6977 } 6978 6979 // Copy the parameter declarations from the declarator D to the function 6980 // declaration NewFD, if they are available. First scavenge them into Params. 6981 SmallVector<ParmVarDecl*, 16> Params; 6982 if (D.isFunctionDeclarator()) { 6983 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6984 6985 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 6986 // function that takes no arguments, not a function that takes a 6987 // single void argument. 6988 // We let through "const void" here because Sema::GetTypeForDeclarator 6989 // already checks for that case. 6990 if (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6991 FTI.Params[0].Param && 6992 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()) { 6993 // Empty arg list, don't push any params. 6994 } else if (FTI.NumParams > 0 && FTI.Params[0].Param != 0) { 6995 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 6996 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 6997 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 6998 Param->setDeclContext(NewFD); 6999 Params.push_back(Param); 7000 7001 if (Param->isInvalidDecl()) 7002 NewFD->setInvalidDecl(); 7003 } 7004 } 7005 7006 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7007 // When we're declaring a function with a typedef, typeof, etc as in the 7008 // following example, we'll need to synthesize (unnamed) 7009 // parameters for use in the declaration. 7010 // 7011 // @code 7012 // typedef void fn(int); 7013 // fn f; 7014 // @endcode 7015 7016 // Synthesize a parameter for each argument type. 7017 for (const auto &AI : FT->param_types()) { 7018 ParmVarDecl *Param = 7019 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7020 Param->setScopeInfo(0, Params.size()); 7021 Params.push_back(Param); 7022 } 7023 } else { 7024 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7025 "Should not need args for typedef of non-prototype fn"); 7026 } 7027 7028 // Finally, we know we have the right number of parameters, install them. 7029 NewFD->setParams(Params); 7030 7031 // Find all anonymous symbols defined during the declaration of this function 7032 // and add to NewFD. This lets us track decls such 'enum Y' in: 7033 // 7034 // void f(enum Y {AA} x) {} 7035 // 7036 // which would otherwise incorrectly end up in the translation unit scope. 7037 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7038 DeclsInPrototypeScope.clear(); 7039 7040 if (D.getDeclSpec().isNoreturnSpecified()) 7041 NewFD->addAttr( 7042 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7043 Context, 0)); 7044 7045 // Functions returning a variably modified type violate C99 6.7.5.2p2 7046 // because all functions have linkage. 7047 if (!NewFD->isInvalidDecl() && 7048 NewFD->getReturnType()->isVariablyModifiedType()) { 7049 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7050 NewFD->setInvalidDecl(); 7051 } 7052 7053 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7054 !NewFD->hasAttr<SectionAttr>()) { 7055 NewFD->addAttr( 7056 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7057 CodeSegStack.CurrentValue->getString(), 7058 CodeSegStack.CurrentPragmaLocation)); 7059 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7060 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7061 NewFD->dropAttr<SectionAttr>(); 7062 } 7063 7064 // Handle attributes. 7065 ProcessDeclAttributes(S, NewFD, D); 7066 7067 QualType RetType = NewFD->getReturnType(); 7068 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7069 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7070 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7071 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7072 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7073 // Attach WarnUnusedResult to functions returning types with that attribute. 7074 // Don't apply the attribute to that type's own non-static member functions 7075 // (to avoid warning on things like assignment operators) 7076 if (!MD || MD->getParent() != Ret) 7077 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7078 } 7079 7080 if (getLangOpts().OpenCL) { 7081 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7082 // type declaration will generate a compilation error. 7083 unsigned AddressSpace = RetType.getAddressSpace(); 7084 if (AddressSpace == LangAS::opencl_local || 7085 AddressSpace == LangAS::opencl_global || 7086 AddressSpace == LangAS::opencl_constant) { 7087 Diag(NewFD->getLocation(), 7088 diag::err_opencl_return_value_with_address_space); 7089 NewFD->setInvalidDecl(); 7090 } 7091 } 7092 7093 if (!getLangOpts().CPlusPlus) { 7094 // Perform semantic checking on the function declaration. 7095 bool isExplicitSpecialization=false; 7096 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7097 CheckMain(NewFD, D.getDeclSpec()); 7098 7099 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7100 CheckMSVCRTEntryPoint(NewFD); 7101 7102 if (!NewFD->isInvalidDecl()) 7103 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7104 isExplicitSpecialization)); 7105 else if (!Previous.empty()) 7106 // Make graceful recovery from an invalid redeclaration. 7107 D.setRedeclaration(true); 7108 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7109 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7110 "previous declaration set still overloaded"); 7111 } else { 7112 // C++11 [replacement.functions]p3: 7113 // The program's definitions shall not be specified as inline. 7114 // 7115 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7116 // 7117 // Suppress the diagnostic if the function is __attribute__((used)), since 7118 // that forces an external definition to be emitted. 7119 if (D.getDeclSpec().isInlineSpecified() && 7120 NewFD->isReplaceableGlobalAllocationFunction() && 7121 !NewFD->hasAttr<UsedAttr>()) 7122 Diag(D.getDeclSpec().getInlineSpecLoc(), 7123 diag::ext_operator_new_delete_declared_inline) 7124 << NewFD->getDeclName(); 7125 7126 // If the declarator is a template-id, translate the parser's template 7127 // argument list into our AST format. 7128 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7129 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7130 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7131 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7132 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7133 TemplateId->NumArgs); 7134 translateTemplateArguments(TemplateArgsPtr, 7135 TemplateArgs); 7136 7137 HasExplicitTemplateArgs = true; 7138 7139 if (NewFD->isInvalidDecl()) { 7140 HasExplicitTemplateArgs = false; 7141 } else if (FunctionTemplate) { 7142 // Function template with explicit template arguments. 7143 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7144 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7145 7146 HasExplicitTemplateArgs = false; 7147 } else { 7148 assert((isFunctionTemplateSpecialization || 7149 D.getDeclSpec().isFriendSpecified()) && 7150 "should have a 'template<>' for this decl"); 7151 // "friend void foo<>(int);" is an implicit specialization decl. 7152 isFunctionTemplateSpecialization = true; 7153 } 7154 } else if (isFriend && isFunctionTemplateSpecialization) { 7155 // This combination is only possible in a recovery case; the user 7156 // wrote something like: 7157 // template <> friend void foo(int); 7158 // which we're recovering from as if the user had written: 7159 // friend void foo<>(int); 7160 // Go ahead and fake up a template id. 7161 HasExplicitTemplateArgs = true; 7162 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7163 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7164 } 7165 7166 // If it's a friend (and only if it's a friend), it's possible 7167 // that either the specialized function type or the specialized 7168 // template is dependent, and therefore matching will fail. In 7169 // this case, don't check the specialization yet. 7170 bool InstantiationDependent = false; 7171 if (isFunctionTemplateSpecialization && isFriend && 7172 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7173 TemplateSpecializationType::anyDependentTemplateArguments( 7174 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7175 InstantiationDependent))) { 7176 assert(HasExplicitTemplateArgs && 7177 "friend function specialization without template args"); 7178 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7179 Previous)) 7180 NewFD->setInvalidDecl(); 7181 } else if (isFunctionTemplateSpecialization) { 7182 if (CurContext->isDependentContext() && CurContext->isRecord() 7183 && !isFriend) { 7184 isDependentClassScopeExplicitSpecialization = true; 7185 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7186 diag::ext_function_specialization_in_class : 7187 diag::err_function_specialization_in_class) 7188 << NewFD->getDeclName(); 7189 } else if (CheckFunctionTemplateSpecialization(NewFD, 7190 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 7191 Previous)) 7192 NewFD->setInvalidDecl(); 7193 7194 // C++ [dcl.stc]p1: 7195 // A storage-class-specifier shall not be specified in an explicit 7196 // specialization (14.7.3) 7197 FunctionTemplateSpecializationInfo *Info = 7198 NewFD->getTemplateSpecializationInfo(); 7199 if (Info && SC != SC_None) { 7200 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7201 Diag(NewFD->getLocation(), 7202 diag::err_explicit_specialization_inconsistent_storage_class) 7203 << SC 7204 << FixItHint::CreateRemoval( 7205 D.getDeclSpec().getStorageClassSpecLoc()); 7206 7207 else 7208 Diag(NewFD->getLocation(), 7209 diag::ext_explicit_specialization_storage_class) 7210 << FixItHint::CreateRemoval( 7211 D.getDeclSpec().getStorageClassSpecLoc()); 7212 } 7213 7214 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7215 if (CheckMemberSpecialization(NewFD, Previous)) 7216 NewFD->setInvalidDecl(); 7217 } 7218 7219 // Perform semantic checking on the function declaration. 7220 if (!isDependentClassScopeExplicitSpecialization) { 7221 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7222 CheckMain(NewFD, D.getDeclSpec()); 7223 7224 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7225 CheckMSVCRTEntryPoint(NewFD); 7226 7227 if (!NewFD->isInvalidDecl()) 7228 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7229 isExplicitSpecialization)); 7230 } 7231 7232 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7233 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7234 "previous declaration set still overloaded"); 7235 7236 NamedDecl *PrincipalDecl = (FunctionTemplate 7237 ? cast<NamedDecl>(FunctionTemplate) 7238 : NewFD); 7239 7240 if (isFriend && D.isRedeclaration()) { 7241 AccessSpecifier Access = AS_public; 7242 if (!NewFD->isInvalidDecl()) 7243 Access = NewFD->getPreviousDecl()->getAccess(); 7244 7245 NewFD->setAccess(Access); 7246 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7247 } 7248 7249 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7250 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7251 PrincipalDecl->setNonMemberOperator(); 7252 7253 // If we have a function template, check the template parameter 7254 // list. This will check and merge default template arguments. 7255 if (FunctionTemplate) { 7256 FunctionTemplateDecl *PrevTemplate = 7257 FunctionTemplate->getPreviousDecl(); 7258 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7259 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 7260 D.getDeclSpec().isFriendSpecified() 7261 ? (D.isFunctionDefinition() 7262 ? TPC_FriendFunctionTemplateDefinition 7263 : TPC_FriendFunctionTemplate) 7264 : (D.getCXXScopeSpec().isSet() && 7265 DC && DC->isRecord() && 7266 DC->isDependentContext()) 7267 ? TPC_ClassTemplateMember 7268 : TPC_FunctionTemplate); 7269 } 7270 7271 if (NewFD->isInvalidDecl()) { 7272 // Ignore all the rest of this. 7273 } else if (!D.isRedeclaration()) { 7274 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7275 AddToScope }; 7276 // Fake up an access specifier if it's supposed to be a class member. 7277 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7278 NewFD->setAccess(AS_public); 7279 7280 // Qualified decls generally require a previous declaration. 7281 if (D.getCXXScopeSpec().isSet()) { 7282 // ...with the major exception of templated-scope or 7283 // dependent-scope friend declarations. 7284 7285 // TODO: we currently also suppress this check in dependent 7286 // contexts because (1) the parameter depth will be off when 7287 // matching friend templates and (2) we might actually be 7288 // selecting a friend based on a dependent factor. But there 7289 // are situations where these conditions don't apply and we 7290 // can actually do this check immediately. 7291 if (isFriend && 7292 (TemplateParamLists.size() || 7293 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7294 CurContext->isDependentContext())) { 7295 // ignore these 7296 } else { 7297 // The user tried to provide an out-of-line definition for a 7298 // function that is a member of a class or namespace, but there 7299 // was no such member function declared (C++ [class.mfct]p2, 7300 // C++ [namespace.memdef]p2). For example: 7301 // 7302 // class X { 7303 // void f() const; 7304 // }; 7305 // 7306 // void X::f() { } // ill-formed 7307 // 7308 // Complain about this problem, and attempt to suggest close 7309 // matches (e.g., those that differ only in cv-qualifiers and 7310 // whether the parameter types are references). 7311 7312 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7313 *this, Previous, NewFD, ExtraArgs, false, 0)) { 7314 AddToScope = ExtraArgs.AddToScope; 7315 return Result; 7316 } 7317 } 7318 7319 // Unqualified local friend declarations are required to resolve 7320 // to something. 7321 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7322 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7323 *this, Previous, NewFD, ExtraArgs, true, S)) { 7324 AddToScope = ExtraArgs.AddToScope; 7325 return Result; 7326 } 7327 } 7328 7329 } else if (!D.isFunctionDefinition() && 7330 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7331 !isFriend && !isFunctionTemplateSpecialization && 7332 !isExplicitSpecialization) { 7333 // An out-of-line member function declaration must also be a 7334 // definition (C++ [class.mfct]p2). 7335 // Note that this is not the case for explicit specializations of 7336 // function templates or member functions of class templates, per 7337 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7338 // extension for compatibility with old SWIG code which likes to 7339 // generate them. 7340 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7341 << D.getCXXScopeSpec().getRange(); 7342 } 7343 } 7344 7345 ProcessPragmaWeak(S, NewFD); 7346 checkAttributesAfterMerging(*this, *NewFD); 7347 7348 AddKnownFunctionAttributes(NewFD); 7349 7350 if (NewFD->hasAttr<OverloadableAttr>() && 7351 !NewFD->getType()->getAs<FunctionProtoType>()) { 7352 Diag(NewFD->getLocation(), 7353 diag::err_attribute_overloadable_no_prototype) 7354 << NewFD; 7355 7356 // Turn this into a variadic function with no parameters. 7357 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7358 FunctionProtoType::ExtProtoInfo EPI( 7359 Context.getDefaultCallingConvention(true, false)); 7360 EPI.Variadic = true; 7361 EPI.ExtInfo = FT->getExtInfo(); 7362 7363 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7364 NewFD->setType(R); 7365 } 7366 7367 // If there's a #pragma GCC visibility in scope, and this isn't a class 7368 // member, set the visibility of this function. 7369 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7370 AddPushedVisibilityAttribute(NewFD); 7371 7372 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7373 // marking the function. 7374 AddCFAuditedAttribute(NewFD); 7375 7376 // If this is the first declaration of an extern C variable, update 7377 // the map of such variables. 7378 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7379 isIncompleteDeclExternC(*this, NewFD)) 7380 RegisterLocallyScopedExternCDecl(NewFD, S); 7381 7382 // Set this FunctionDecl's range up to the right paren. 7383 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7384 7385 if (D.isRedeclaration() && !Previous.empty()) { 7386 checkDLLAttributeRedeclaration( 7387 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7388 isExplicitSpecialization || isFunctionTemplateSpecialization); 7389 } 7390 7391 if (getLangOpts().CPlusPlus) { 7392 if (FunctionTemplate) { 7393 if (NewFD->isInvalidDecl()) 7394 FunctionTemplate->setInvalidDecl(); 7395 return FunctionTemplate; 7396 } 7397 } 7398 7399 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7400 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7401 if ((getLangOpts().OpenCLVersion >= 120) 7402 && (SC == SC_Static)) { 7403 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7404 D.setInvalidType(); 7405 } 7406 7407 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7408 if (!NewFD->getReturnType()->isVoidType()) { 7409 Diag(D.getIdentifierLoc(), 7410 diag::err_expected_kernel_void_return_type); 7411 D.setInvalidType(); 7412 } 7413 7414 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7415 for (auto Param : NewFD->params()) 7416 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7417 } 7418 7419 MarkUnusedFileScopedDecl(NewFD); 7420 7421 if (getLangOpts().CUDA) 7422 if (IdentifierInfo *II = NewFD->getIdentifier()) 7423 if (!NewFD->isInvalidDecl() && 7424 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7425 if (II->isStr("cudaConfigureCall")) { 7426 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7427 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7428 7429 Context.setcudaConfigureCallDecl(NewFD); 7430 } 7431 } 7432 7433 // Here we have an function template explicit specialization at class scope. 7434 // The actually specialization will be postponed to template instatiation 7435 // time via the ClassScopeFunctionSpecializationDecl node. 7436 if (isDependentClassScopeExplicitSpecialization) { 7437 ClassScopeFunctionSpecializationDecl *NewSpec = 7438 ClassScopeFunctionSpecializationDecl::Create( 7439 Context, CurContext, SourceLocation(), 7440 cast<CXXMethodDecl>(NewFD), 7441 HasExplicitTemplateArgs, TemplateArgs); 7442 CurContext->addDecl(NewSpec); 7443 AddToScope = false; 7444 } 7445 7446 return NewFD; 7447 } 7448 7449 /// \brief Perform semantic checking of a new function declaration. 7450 /// 7451 /// Performs semantic analysis of the new function declaration 7452 /// NewFD. This routine performs all semantic checking that does not 7453 /// require the actual declarator involved in the declaration, and is 7454 /// used both for the declaration of functions as they are parsed 7455 /// (called via ActOnDeclarator) and for the declaration of functions 7456 /// that have been instantiated via C++ template instantiation (called 7457 /// via InstantiateDecl). 7458 /// 7459 /// \param IsExplicitSpecialization whether this new function declaration is 7460 /// an explicit specialization of the previous declaration. 7461 /// 7462 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7463 /// 7464 /// \returns true if the function declaration is a redeclaration. 7465 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7466 LookupResult &Previous, 7467 bool IsExplicitSpecialization) { 7468 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7469 "Variably modified return types are not handled here"); 7470 7471 // Determine whether the type of this function should be merged with 7472 // a previous visible declaration. This never happens for functions in C++, 7473 // and always happens in C if the previous declaration was visible. 7474 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7475 !Previous.isShadowed(); 7476 7477 // Filter out any non-conflicting previous declarations. 7478 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7479 7480 bool Redeclaration = false; 7481 NamedDecl *OldDecl = 0; 7482 7483 // Merge or overload the declaration with an existing declaration of 7484 // the same name, if appropriate. 7485 if (!Previous.empty()) { 7486 // Determine whether NewFD is an overload of PrevDecl or 7487 // a declaration that requires merging. If it's an overload, 7488 // there's no more work to do here; we'll just add the new 7489 // function to the scope. 7490 if (!AllowOverloadingOfFunction(Previous, Context)) { 7491 NamedDecl *Candidate = Previous.getFoundDecl(); 7492 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7493 Redeclaration = true; 7494 OldDecl = Candidate; 7495 } 7496 } else { 7497 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7498 /*NewIsUsingDecl*/ false)) { 7499 case Ovl_Match: 7500 Redeclaration = true; 7501 break; 7502 7503 case Ovl_NonFunction: 7504 Redeclaration = true; 7505 break; 7506 7507 case Ovl_Overload: 7508 Redeclaration = false; 7509 break; 7510 } 7511 7512 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7513 // If a function name is overloadable in C, then every function 7514 // with that name must be marked "overloadable". 7515 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7516 << Redeclaration << NewFD; 7517 NamedDecl *OverloadedDecl = 0; 7518 if (Redeclaration) 7519 OverloadedDecl = OldDecl; 7520 else if (!Previous.empty()) 7521 OverloadedDecl = Previous.getRepresentativeDecl(); 7522 if (OverloadedDecl) 7523 Diag(OverloadedDecl->getLocation(), 7524 diag::note_attribute_overloadable_prev_overload); 7525 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7526 } 7527 } 7528 } 7529 7530 // Check for a previous extern "C" declaration with this name. 7531 if (!Redeclaration && 7532 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7533 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7534 if (!Previous.empty()) { 7535 // This is an extern "C" declaration with the same name as a previous 7536 // declaration, and thus redeclares that entity... 7537 Redeclaration = true; 7538 OldDecl = Previous.getFoundDecl(); 7539 MergeTypeWithPrevious = false; 7540 7541 // ... except in the presence of __attribute__((overloadable)). 7542 if (OldDecl->hasAttr<OverloadableAttr>()) { 7543 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7544 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7545 << Redeclaration << NewFD; 7546 Diag(Previous.getFoundDecl()->getLocation(), 7547 diag::note_attribute_overloadable_prev_overload); 7548 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7549 } 7550 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7551 Redeclaration = false; 7552 OldDecl = 0; 7553 } 7554 } 7555 } 7556 } 7557 7558 // C++11 [dcl.constexpr]p8: 7559 // A constexpr specifier for a non-static member function that is not 7560 // a constructor declares that member function to be const. 7561 // 7562 // This needs to be delayed until we know whether this is an out-of-line 7563 // definition of a static member function. 7564 // 7565 // This rule is not present in C++1y, so we produce a backwards 7566 // compatibility warning whenever it happens in C++11. 7567 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7568 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7569 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7570 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7571 CXXMethodDecl *OldMD = 0; 7572 if (OldDecl) 7573 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7574 if (!OldMD || !OldMD->isStatic()) { 7575 const FunctionProtoType *FPT = 7576 MD->getType()->castAs<FunctionProtoType>(); 7577 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7578 EPI.TypeQuals |= Qualifiers::Const; 7579 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7580 FPT->getParamTypes(), EPI)); 7581 7582 // Warn that we did this, if we're not performing template instantiation. 7583 // In that case, we'll have warned already when the template was defined. 7584 if (ActiveTemplateInstantiations.empty()) { 7585 SourceLocation AddConstLoc; 7586 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7587 .IgnoreParens().getAs<FunctionTypeLoc>()) 7588 AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc()); 7589 7590 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7591 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7592 } 7593 } 7594 } 7595 7596 if (Redeclaration) { 7597 // NewFD and OldDecl represent declarations that need to be 7598 // merged. 7599 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7600 NewFD->setInvalidDecl(); 7601 return Redeclaration; 7602 } 7603 7604 Previous.clear(); 7605 Previous.addDecl(OldDecl); 7606 7607 if (FunctionTemplateDecl *OldTemplateDecl 7608 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7609 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7610 FunctionTemplateDecl *NewTemplateDecl 7611 = NewFD->getDescribedFunctionTemplate(); 7612 assert(NewTemplateDecl && "Template/non-template mismatch"); 7613 if (CXXMethodDecl *Method 7614 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7615 Method->setAccess(OldTemplateDecl->getAccess()); 7616 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7617 } 7618 7619 // If this is an explicit specialization of a member that is a function 7620 // template, mark it as a member specialization. 7621 if (IsExplicitSpecialization && 7622 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7623 NewTemplateDecl->setMemberSpecialization(); 7624 assert(OldTemplateDecl->isMemberSpecialization()); 7625 } 7626 7627 } else { 7628 // This needs to happen first so that 'inline' propagates. 7629 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7630 7631 if (isa<CXXMethodDecl>(NewFD)) { 7632 // A valid redeclaration of a C++ method must be out-of-line, 7633 // but (unfortunately) it's not necessarily a definition 7634 // because of templates, which means that the previous 7635 // declaration is not necessarily from the class definition. 7636 7637 // For just setting the access, that doesn't matter. 7638 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7639 NewFD->setAccess(oldMethod->getAccess()); 7640 7641 // Update the key-function state if necessary for this ABI. 7642 if (NewFD->isInlined() && 7643 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7644 // setNonKeyFunction needs to work with the original 7645 // declaration from the class definition, and isVirtual() is 7646 // just faster in that case, so map back to that now. 7647 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7648 if (oldMethod->isVirtual()) { 7649 Context.setNonKeyFunction(oldMethod); 7650 } 7651 } 7652 } 7653 } 7654 } 7655 7656 // Semantic checking for this function declaration (in isolation). 7657 if (getLangOpts().CPlusPlus) { 7658 // C++-specific checks. 7659 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7660 CheckConstructor(Constructor); 7661 } else if (CXXDestructorDecl *Destructor = 7662 dyn_cast<CXXDestructorDecl>(NewFD)) { 7663 CXXRecordDecl *Record = Destructor->getParent(); 7664 QualType ClassType = Context.getTypeDeclType(Record); 7665 7666 // FIXME: Shouldn't we be able to perform this check even when the class 7667 // type is dependent? Both gcc and edg can handle that. 7668 if (!ClassType->isDependentType()) { 7669 DeclarationName Name 7670 = Context.DeclarationNames.getCXXDestructorName( 7671 Context.getCanonicalType(ClassType)); 7672 if (NewFD->getDeclName() != Name) { 7673 Diag(NewFD->getLocation(), diag::err_destructor_name); 7674 NewFD->setInvalidDecl(); 7675 return Redeclaration; 7676 } 7677 } 7678 } else if (CXXConversionDecl *Conversion 7679 = dyn_cast<CXXConversionDecl>(NewFD)) { 7680 ActOnConversionDeclarator(Conversion); 7681 } 7682 7683 // Find any virtual functions that this function overrides. 7684 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7685 if (!Method->isFunctionTemplateSpecialization() && 7686 !Method->getDescribedFunctionTemplate() && 7687 Method->isCanonicalDecl()) { 7688 if (AddOverriddenMethods(Method->getParent(), Method)) { 7689 // If the function was marked as "static", we have a problem. 7690 if (NewFD->getStorageClass() == SC_Static) { 7691 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7692 } 7693 } 7694 } 7695 7696 if (Method->isStatic()) 7697 checkThisInStaticMemberFunctionType(Method); 7698 } 7699 7700 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7701 if (NewFD->isOverloadedOperator() && 7702 CheckOverloadedOperatorDeclaration(NewFD)) { 7703 NewFD->setInvalidDecl(); 7704 return Redeclaration; 7705 } 7706 7707 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7708 if (NewFD->getLiteralIdentifier() && 7709 CheckLiteralOperatorDeclaration(NewFD)) { 7710 NewFD->setInvalidDecl(); 7711 return Redeclaration; 7712 } 7713 7714 // In C++, check default arguments now that we have merged decls. Unless 7715 // the lexical context is the class, because in this case this is done 7716 // during delayed parsing anyway. 7717 if (!CurContext->isRecord()) 7718 CheckCXXDefaultArguments(NewFD); 7719 7720 // If this function declares a builtin function, check the type of this 7721 // declaration against the expected type for the builtin. 7722 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7723 ASTContext::GetBuiltinTypeError Error; 7724 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7725 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7726 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7727 // The type of this function differs from the type of the builtin, 7728 // so forget about the builtin entirely. 7729 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7730 } 7731 } 7732 7733 // If this function is declared as being extern "C", then check to see if 7734 // the function returns a UDT (class, struct, or union type) that is not C 7735 // compatible, and if it does, warn the user. 7736 // But, issue any diagnostic on the first declaration only. 7737 if (NewFD->isExternC() && Previous.empty()) { 7738 QualType R = NewFD->getReturnType(); 7739 if (R->isIncompleteType() && !R->isVoidType()) 7740 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7741 << NewFD << R; 7742 else if (!R.isPODType(Context) && !R->isVoidType() && 7743 !R->isObjCObjectPointerType()) 7744 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7745 } 7746 } 7747 return Redeclaration; 7748 } 7749 7750 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7751 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7752 if (!TSI) 7753 return SourceRange(); 7754 7755 TypeLoc TL = TSI->getTypeLoc(); 7756 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7757 if (!FunctionTL) 7758 return SourceRange(); 7759 7760 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7761 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7762 return ResultTL.getSourceRange(); 7763 7764 return SourceRange(); 7765 } 7766 7767 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7768 // C++11 [basic.start.main]p3: 7769 // A program that [...] declares main to be inline, static or 7770 // constexpr is ill-formed. 7771 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7772 // appear in a declaration of main. 7773 // static main is not an error under C99, but we should warn about it. 7774 // We accept _Noreturn main as an extension. 7775 if (FD->getStorageClass() == SC_Static) 7776 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7777 ? diag::err_static_main : diag::warn_static_main) 7778 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7779 if (FD->isInlineSpecified()) 7780 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7781 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7782 if (DS.isNoreturnSpecified()) { 7783 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7784 SourceRange NoreturnRange(NoreturnLoc, 7785 PP.getLocForEndOfToken(NoreturnLoc)); 7786 Diag(NoreturnLoc, diag::ext_noreturn_main); 7787 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7788 << FixItHint::CreateRemoval(NoreturnRange); 7789 } 7790 if (FD->isConstexpr()) { 7791 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7792 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7793 FD->setConstexpr(false); 7794 } 7795 7796 if (getLangOpts().OpenCL) { 7797 Diag(FD->getLocation(), diag::err_opencl_no_main) 7798 << FD->hasAttr<OpenCLKernelAttr>(); 7799 FD->setInvalidDecl(); 7800 return; 7801 } 7802 7803 QualType T = FD->getType(); 7804 assert(T->isFunctionType() && "function decl is not of function type"); 7805 const FunctionType* FT = T->castAs<FunctionType>(); 7806 7807 // All the standards say that main() should should return 'int'. 7808 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7809 // In C and C++, main magically returns 0 if you fall off the end; 7810 // set the flag which tells us that. 7811 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7812 FD->setHasImplicitReturnZero(true); 7813 7814 // In C with GNU extensions we allow main() to have non-integer return 7815 // type, but we should warn about the extension, and we disable the 7816 // implicit-return-zero rule. 7817 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7818 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7819 7820 SourceRange ResultRange = getResultSourceRange(FD); 7821 if (ResultRange.isValid()) 7822 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7823 << FixItHint::CreateReplacement(ResultRange, "int"); 7824 7825 // Otherwise, this is just a flat-out error. 7826 } else { 7827 SourceRange ResultRange = getResultSourceRange(FD); 7828 if (ResultRange.isValid()) 7829 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7830 << FixItHint::CreateReplacement(ResultRange, "int"); 7831 else 7832 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7833 7834 FD->setInvalidDecl(true); 7835 } 7836 7837 // Treat protoless main() as nullary. 7838 if (isa<FunctionNoProtoType>(FT)) return; 7839 7840 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7841 unsigned nparams = FTP->getNumParams(); 7842 assert(FD->getNumParams() == nparams); 7843 7844 bool HasExtraParameters = (nparams > 3); 7845 7846 // Darwin passes an undocumented fourth argument of type char**. If 7847 // other platforms start sprouting these, the logic below will start 7848 // getting shifty. 7849 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7850 HasExtraParameters = false; 7851 7852 if (HasExtraParameters) { 7853 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7854 FD->setInvalidDecl(true); 7855 nparams = 3; 7856 } 7857 7858 // FIXME: a lot of the following diagnostics would be improved 7859 // if we had some location information about types. 7860 7861 QualType CharPP = 7862 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7863 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7864 7865 for (unsigned i = 0; i < nparams; ++i) { 7866 QualType AT = FTP->getParamType(i); 7867 7868 bool mismatch = true; 7869 7870 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7871 mismatch = false; 7872 else if (Expected[i] == CharPP) { 7873 // As an extension, the following forms are okay: 7874 // char const ** 7875 // char const * const * 7876 // char * const * 7877 7878 QualifierCollector qs; 7879 const PointerType* PT; 7880 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7881 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7882 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7883 Context.CharTy)) { 7884 qs.removeConst(); 7885 mismatch = !qs.empty(); 7886 } 7887 } 7888 7889 if (mismatch) { 7890 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7891 // TODO: suggest replacing given type with expected type 7892 FD->setInvalidDecl(true); 7893 } 7894 } 7895 7896 if (nparams == 1 && !FD->isInvalidDecl()) { 7897 Diag(FD->getLocation(), diag::warn_main_one_arg); 7898 } 7899 7900 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7901 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7902 FD->setInvalidDecl(); 7903 } 7904 } 7905 7906 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7907 QualType T = FD->getType(); 7908 assert(T->isFunctionType() && "function decl is not of function type"); 7909 const FunctionType *FT = T->castAs<FunctionType>(); 7910 7911 // Set an implicit return of 'zero' if the function can return some integral, 7912 // enumeration, pointer or nullptr type. 7913 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7914 FT->getReturnType()->isAnyPointerType() || 7915 FT->getReturnType()->isNullPtrType()) 7916 // DllMain is exempt because a return value of zero means it failed. 7917 if (FD->getName() != "DllMain") 7918 FD->setHasImplicitReturnZero(true); 7919 7920 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7921 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7922 FD->setInvalidDecl(); 7923 } 7924 } 7925 7926 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7927 // FIXME: Need strict checking. In C89, we need to check for 7928 // any assignment, increment, decrement, function-calls, or 7929 // commas outside of a sizeof. In C99, it's the same list, 7930 // except that the aforementioned are allowed in unevaluated 7931 // expressions. Everything else falls under the 7932 // "may accept other forms of constant expressions" exception. 7933 // (We never end up here for C++, so the constant expression 7934 // rules there don't matter.) 7935 if (Init->isConstantInitializer(Context, false)) 7936 return false; 7937 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 7938 << Init->getSourceRange(); 7939 return true; 7940 } 7941 7942 namespace { 7943 // Visits an initialization expression to see if OrigDecl is evaluated in 7944 // its own initialization and throws a warning if it does. 7945 class SelfReferenceChecker 7946 : public EvaluatedExprVisitor<SelfReferenceChecker> { 7947 Sema &S; 7948 Decl *OrigDecl; 7949 bool isRecordType; 7950 bool isPODType; 7951 bool isReferenceType; 7952 7953 public: 7954 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 7955 7956 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 7957 S(S), OrigDecl(OrigDecl) { 7958 isPODType = false; 7959 isRecordType = false; 7960 isReferenceType = false; 7961 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 7962 isPODType = VD->getType().isPODType(S.Context); 7963 isRecordType = VD->getType()->isRecordType(); 7964 isReferenceType = VD->getType()->isReferenceType(); 7965 } 7966 } 7967 7968 // For most expressions, the cast is directly above the DeclRefExpr. 7969 // For conditional operators, the cast can be outside the conditional 7970 // operator if both expressions are DeclRefExpr's. 7971 void HandleValue(Expr *E) { 7972 if (isReferenceType) 7973 return; 7974 E = E->IgnoreParenImpCasts(); 7975 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 7976 HandleDeclRefExpr(DRE); 7977 return; 7978 } 7979 7980 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7981 HandleValue(CO->getTrueExpr()); 7982 HandleValue(CO->getFalseExpr()); 7983 return; 7984 } 7985 7986 if (isa<MemberExpr>(E)) { 7987 Expr *Base = E->IgnoreParenImpCasts(); 7988 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 7989 // Check for static member variables and don't warn on them. 7990 if (!isa<FieldDecl>(ME->getMemberDecl())) 7991 return; 7992 Base = ME->getBase()->IgnoreParenImpCasts(); 7993 } 7994 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 7995 HandleDeclRefExpr(DRE); 7996 return; 7997 } 7998 } 7999 8000 // Reference types are handled here since all uses of references are 8001 // bad, not just r-value uses. 8002 void VisitDeclRefExpr(DeclRefExpr *E) { 8003 if (isReferenceType) 8004 HandleDeclRefExpr(E); 8005 } 8006 8007 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8008 if (E->getCastKind() == CK_LValueToRValue || 8009 (isRecordType && E->getCastKind() == CK_NoOp)) 8010 HandleValue(E->getSubExpr()); 8011 8012 Inherited::VisitImplicitCastExpr(E); 8013 } 8014 8015 void VisitMemberExpr(MemberExpr *E) { 8016 // Don't warn on arrays since they can be treated as pointers. 8017 if (E->getType()->canDecayToPointerType()) return; 8018 8019 // Warn when a non-static method call is followed by non-static member 8020 // field accesses, which is followed by a DeclRefExpr. 8021 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8022 bool Warn = (MD && !MD->isStatic()); 8023 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8024 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8025 if (!isa<FieldDecl>(ME->getMemberDecl())) 8026 Warn = false; 8027 Base = ME->getBase()->IgnoreParenImpCasts(); 8028 } 8029 8030 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8031 if (Warn) 8032 HandleDeclRefExpr(DRE); 8033 return; 8034 } 8035 8036 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8037 // Visit that expression. 8038 Visit(Base); 8039 } 8040 8041 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8042 if (E->getNumArgs() > 0) 8043 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8044 HandleDeclRefExpr(DRE); 8045 8046 Inherited::VisitCXXOperatorCallExpr(E); 8047 } 8048 8049 void VisitUnaryOperator(UnaryOperator *E) { 8050 // For POD record types, addresses of its own members are well-defined. 8051 if (E->getOpcode() == UO_AddrOf && isRecordType && 8052 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8053 if (!isPODType) 8054 HandleValue(E->getSubExpr()); 8055 return; 8056 } 8057 Inherited::VisitUnaryOperator(E); 8058 } 8059 8060 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8061 8062 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8063 Decl* ReferenceDecl = DRE->getDecl(); 8064 if (OrigDecl != ReferenceDecl) return; 8065 unsigned diag; 8066 if (isReferenceType) { 8067 diag = diag::warn_uninit_self_reference_in_reference_init; 8068 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8069 diag = diag::warn_static_self_reference_in_init; 8070 } else { 8071 diag = diag::warn_uninit_self_reference_in_init; 8072 } 8073 8074 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8075 S.PDiag(diag) 8076 << DRE->getNameInfo().getName() 8077 << OrigDecl->getLocation() 8078 << DRE->getSourceRange()); 8079 } 8080 }; 8081 8082 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8083 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8084 bool DirectInit) { 8085 // Parameters arguments are occassionially constructed with itself, 8086 // for instance, in recursive functions. Skip them. 8087 if (isa<ParmVarDecl>(OrigDecl)) 8088 return; 8089 8090 E = E->IgnoreParens(); 8091 8092 // Skip checking T a = a where T is not a record or reference type. 8093 // Doing so is a way to silence uninitialized warnings. 8094 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8095 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8096 if (ICE->getCastKind() == CK_LValueToRValue) 8097 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8098 if (DRE->getDecl() == OrigDecl) 8099 return; 8100 8101 SelfReferenceChecker(S, OrigDecl).Visit(E); 8102 } 8103 } 8104 8105 /// AddInitializerToDecl - Adds the initializer Init to the 8106 /// declaration dcl. If DirectInit is true, this is C++ direct 8107 /// initialization rather than copy initialization. 8108 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8109 bool DirectInit, bool TypeMayContainAuto) { 8110 // If there is no declaration, there was an error parsing it. Just ignore 8111 // the initializer. 8112 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 8113 return; 8114 8115 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8116 // With declarators parsed the way they are, the parser cannot 8117 // distinguish between a normal initializer and a pure-specifier. 8118 // Thus this grotesque test. 8119 IntegerLiteral *IL; 8120 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8121 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8122 CheckPureMethod(Method, Init->getSourceRange()); 8123 else { 8124 Diag(Method->getLocation(), diag::err_member_function_initialization) 8125 << Method->getDeclName() << Init->getSourceRange(); 8126 Method->setInvalidDecl(); 8127 } 8128 return; 8129 } 8130 8131 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8132 if (!VDecl) { 8133 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8134 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8135 RealDecl->setInvalidDecl(); 8136 return; 8137 } 8138 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8139 8140 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8141 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8142 Expr *DeduceInit = Init; 8143 // Initializer could be a C++ direct-initializer. Deduction only works if it 8144 // contains exactly one expression. 8145 if (CXXDirectInit) { 8146 if (CXXDirectInit->getNumExprs() == 0) { 8147 // It isn't possible to write this directly, but it is possible to 8148 // end up in this situation with "auto x(some_pack...);" 8149 Diag(CXXDirectInit->getLocStart(), 8150 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8151 : diag::err_auto_var_init_no_expression) 8152 << VDecl->getDeclName() << VDecl->getType() 8153 << VDecl->getSourceRange(); 8154 RealDecl->setInvalidDecl(); 8155 return; 8156 } else if (CXXDirectInit->getNumExprs() > 1) { 8157 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8158 VDecl->isInitCapture() 8159 ? diag::err_init_capture_multiple_expressions 8160 : diag::err_auto_var_init_multiple_expressions) 8161 << VDecl->getDeclName() << VDecl->getType() 8162 << VDecl->getSourceRange(); 8163 RealDecl->setInvalidDecl(); 8164 return; 8165 } else { 8166 DeduceInit = CXXDirectInit->getExpr(0); 8167 if (isa<InitListExpr>(DeduceInit)) 8168 Diag(CXXDirectInit->getLocStart(), 8169 diag::err_auto_var_init_paren_braces) 8170 << VDecl->getDeclName() << VDecl->getType() 8171 << VDecl->getSourceRange(); 8172 } 8173 } 8174 8175 // Expressions default to 'id' when we're in a debugger. 8176 bool DefaultedToAuto = false; 8177 if (getLangOpts().DebuggerCastResultToId && 8178 Init->getType() == Context.UnknownAnyTy) { 8179 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8180 if (Result.isInvalid()) { 8181 VDecl->setInvalidDecl(); 8182 return; 8183 } 8184 Init = Result.take(); 8185 DefaultedToAuto = true; 8186 } 8187 8188 QualType DeducedType; 8189 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8190 DAR_Failed) 8191 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8192 if (DeducedType.isNull()) { 8193 RealDecl->setInvalidDecl(); 8194 return; 8195 } 8196 VDecl->setType(DeducedType); 8197 assert(VDecl->isLinkageValid()); 8198 8199 // In ARC, infer lifetime. 8200 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8201 VDecl->setInvalidDecl(); 8202 8203 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8204 // 'id' instead of a specific object type prevents most of our usual checks. 8205 // We only want to warn outside of template instantiations, though: 8206 // inside a template, the 'id' could have come from a parameter. 8207 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8208 DeducedType->isObjCIdType()) { 8209 SourceLocation Loc = 8210 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8211 Diag(Loc, diag::warn_auto_var_is_id) 8212 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8213 } 8214 8215 // If this is a redeclaration, check that the type we just deduced matches 8216 // the previously declared type. 8217 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8218 // We never need to merge the type, because we cannot form an incomplete 8219 // array of auto, nor deduce such a type. 8220 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8221 } 8222 8223 // Check the deduced type is valid for a variable declaration. 8224 CheckVariableDeclarationType(VDecl); 8225 if (VDecl->isInvalidDecl()) 8226 return; 8227 } 8228 8229 // dllimport cannot be used on variable definitions. 8230 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8231 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8232 VDecl->setInvalidDecl(); 8233 return; 8234 } 8235 8236 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8237 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8238 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8239 VDecl->setInvalidDecl(); 8240 return; 8241 } 8242 8243 if (!VDecl->getType()->isDependentType()) { 8244 // A definition must end up with a complete type, which means it must be 8245 // complete with the restriction that an array type might be completed by 8246 // the initializer; note that later code assumes this restriction. 8247 QualType BaseDeclType = VDecl->getType(); 8248 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8249 BaseDeclType = Array->getElementType(); 8250 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8251 diag::err_typecheck_decl_incomplete_type)) { 8252 RealDecl->setInvalidDecl(); 8253 return; 8254 } 8255 8256 // The variable can not have an abstract class type. 8257 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8258 diag::err_abstract_type_in_decl, 8259 AbstractVariableType)) 8260 VDecl->setInvalidDecl(); 8261 } 8262 8263 const VarDecl *Def; 8264 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8265 Diag(VDecl->getLocation(), diag::err_redefinition) 8266 << VDecl->getDeclName(); 8267 Diag(Def->getLocation(), diag::note_previous_definition); 8268 VDecl->setInvalidDecl(); 8269 return; 8270 } 8271 8272 const VarDecl* PrevInit = 0; 8273 if (getLangOpts().CPlusPlus) { 8274 // C++ [class.static.data]p4 8275 // If a static data member is of const integral or const 8276 // enumeration type, its declaration in the class definition can 8277 // specify a constant-initializer which shall be an integral 8278 // constant expression (5.19). In that case, the member can appear 8279 // in integral constant expressions. The member shall still be 8280 // defined in a namespace scope if it is used in the program and the 8281 // namespace scope definition shall not contain an initializer. 8282 // 8283 // We already performed a redefinition check above, but for static 8284 // data members we also need to check whether there was an in-class 8285 // declaration with an initializer. 8286 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8287 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8288 << VDecl->getDeclName(); 8289 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8290 return; 8291 } 8292 8293 if (VDecl->hasLocalStorage()) 8294 getCurFunction()->setHasBranchProtectedScope(); 8295 8296 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8297 VDecl->setInvalidDecl(); 8298 return; 8299 } 8300 } 8301 8302 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8303 // a kernel function cannot be initialized." 8304 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8305 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8306 VDecl->setInvalidDecl(); 8307 return; 8308 } 8309 8310 // Get the decls type and save a reference for later, since 8311 // CheckInitializerTypes may change it. 8312 QualType DclT = VDecl->getType(), SavT = DclT; 8313 8314 // Expressions default to 'id' when we're in a debugger 8315 // and we are assigning it to a variable of Objective-C pointer type. 8316 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8317 Init->getType() == Context.UnknownAnyTy) { 8318 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8319 if (Result.isInvalid()) { 8320 VDecl->setInvalidDecl(); 8321 return; 8322 } 8323 Init = Result.take(); 8324 } 8325 8326 // Perform the initialization. 8327 if (!VDecl->isInvalidDecl()) { 8328 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8329 InitializationKind Kind 8330 = DirectInit ? 8331 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8332 Init->getLocStart(), 8333 Init->getLocEnd()) 8334 : InitializationKind::CreateDirectList( 8335 VDecl->getLocation()) 8336 : InitializationKind::CreateCopy(VDecl->getLocation(), 8337 Init->getLocStart()); 8338 8339 MultiExprArg Args = Init; 8340 if (CXXDirectInit) 8341 Args = MultiExprArg(CXXDirectInit->getExprs(), 8342 CXXDirectInit->getNumExprs()); 8343 8344 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8345 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8346 if (Result.isInvalid()) { 8347 VDecl->setInvalidDecl(); 8348 return; 8349 } 8350 8351 Init = Result.takeAs<Expr>(); 8352 } 8353 8354 // Check for self-references within variable initializers. 8355 // Variables declared within a function/method body (except for references) 8356 // are handled by a dataflow analysis. 8357 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8358 VDecl->getType()->isReferenceType()) { 8359 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8360 } 8361 8362 // If the type changed, it means we had an incomplete type that was 8363 // completed by the initializer. For example: 8364 // int ary[] = { 1, 3, 5 }; 8365 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8366 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8367 VDecl->setType(DclT); 8368 8369 if (!VDecl->isInvalidDecl()) { 8370 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8371 8372 if (VDecl->hasAttr<BlocksAttr>()) 8373 checkRetainCycles(VDecl, Init); 8374 8375 // It is safe to assign a weak reference into a strong variable. 8376 // Although this code can still have problems: 8377 // id x = self.weakProp; 8378 // id y = self.weakProp; 8379 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8380 // paths through the function. This should be revisited if 8381 // -Wrepeated-use-of-weak is made flow-sensitive. 8382 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8383 DiagnosticsEngine::Level Level = 8384 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8385 Init->getLocStart()); 8386 if (Level != DiagnosticsEngine::Ignored) 8387 getCurFunction()->markSafeWeakUse(Init); 8388 } 8389 } 8390 8391 // The initialization is usually a full-expression. 8392 // 8393 // FIXME: If this is a braced initialization of an aggregate, it is not 8394 // an expression, and each individual field initializer is a separate 8395 // full-expression. For instance, in: 8396 // 8397 // struct Temp { ~Temp(); }; 8398 // struct S { S(Temp); }; 8399 // struct T { S a, b; } t = { Temp(), Temp() } 8400 // 8401 // we should destroy the first Temp before constructing the second. 8402 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8403 false, 8404 VDecl->isConstexpr()); 8405 if (Result.isInvalid()) { 8406 VDecl->setInvalidDecl(); 8407 return; 8408 } 8409 Init = Result.take(); 8410 8411 // Attach the initializer to the decl. 8412 VDecl->setInit(Init); 8413 8414 if (VDecl->isLocalVarDecl()) { 8415 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8416 // static storage duration shall be constant expressions or string literals. 8417 // C++ does not have this restriction. 8418 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8419 if (VDecl->getStorageClass() == SC_Static) 8420 CheckForConstantInitializer(Init, DclT); 8421 // C89 is stricter than C99 for non-static aggregate types. 8422 // C89 6.5.7p3: All the expressions [...] in an initializer list 8423 // for an object that has aggregate or union type shall be 8424 // constant expressions. 8425 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8426 isa<InitListExpr>(Init) && 8427 !Init->isConstantInitializer(Context, false)) 8428 Diag(Init->getExprLoc(), 8429 diag::ext_aggregate_init_not_constant) 8430 << Init->getSourceRange(); 8431 } 8432 } else if (VDecl->isStaticDataMember() && 8433 VDecl->getLexicalDeclContext()->isRecord()) { 8434 // This is an in-class initialization for a static data member, e.g., 8435 // 8436 // struct S { 8437 // static const int value = 17; 8438 // }; 8439 8440 // C++ [class.mem]p4: 8441 // A member-declarator can contain a constant-initializer only 8442 // if it declares a static member (9.4) of const integral or 8443 // const enumeration type, see 9.4.2. 8444 // 8445 // C++11 [class.static.data]p3: 8446 // If a non-volatile const static data member is of integral or 8447 // enumeration type, its declaration in the class definition can 8448 // specify a brace-or-equal-initializer in which every initalizer-clause 8449 // that is an assignment-expression is a constant expression. A static 8450 // data member of literal type can be declared in the class definition 8451 // with the constexpr specifier; if so, its declaration shall specify a 8452 // brace-or-equal-initializer in which every initializer-clause that is 8453 // an assignment-expression is a constant expression. 8454 8455 // Do nothing on dependent types. 8456 if (DclT->isDependentType()) { 8457 8458 // Allow any 'static constexpr' members, whether or not they are of literal 8459 // type. We separately check that every constexpr variable is of literal 8460 // type. 8461 } else if (VDecl->isConstexpr()) { 8462 8463 // Require constness. 8464 } else if (!DclT.isConstQualified()) { 8465 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8466 << Init->getSourceRange(); 8467 VDecl->setInvalidDecl(); 8468 8469 // We allow integer constant expressions in all cases. 8470 } else if (DclT->isIntegralOrEnumerationType()) { 8471 // Check whether the expression is a constant expression. 8472 SourceLocation Loc; 8473 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8474 // In C++11, a non-constexpr const static data member with an 8475 // in-class initializer cannot be volatile. 8476 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8477 else if (Init->isValueDependent()) 8478 ; // Nothing to check. 8479 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8480 ; // Ok, it's an ICE! 8481 else if (Init->isEvaluatable(Context)) { 8482 // If we can constant fold the initializer through heroics, accept it, 8483 // but report this as a use of an extension for -pedantic. 8484 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8485 << Init->getSourceRange(); 8486 } else { 8487 // Otherwise, this is some crazy unknown case. Report the issue at the 8488 // location provided by the isIntegerConstantExpr failed check. 8489 Diag(Loc, diag::err_in_class_initializer_non_constant) 8490 << Init->getSourceRange(); 8491 VDecl->setInvalidDecl(); 8492 } 8493 8494 // We allow foldable floating-point constants as an extension. 8495 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8496 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8497 // it anyway and provide a fixit to add the 'constexpr'. 8498 if (getLangOpts().CPlusPlus11) { 8499 Diag(VDecl->getLocation(), 8500 diag::ext_in_class_initializer_float_type_cxx11) 8501 << DclT << Init->getSourceRange(); 8502 Diag(VDecl->getLocStart(), 8503 diag::note_in_class_initializer_float_type_cxx11) 8504 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8505 } else { 8506 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8507 << DclT << Init->getSourceRange(); 8508 8509 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8510 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8511 << Init->getSourceRange(); 8512 VDecl->setInvalidDecl(); 8513 } 8514 } 8515 8516 // Suggest adding 'constexpr' in C++11 for literal types. 8517 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8518 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8519 << DclT << Init->getSourceRange() 8520 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8521 VDecl->setConstexpr(true); 8522 8523 } else { 8524 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8525 << DclT << Init->getSourceRange(); 8526 VDecl->setInvalidDecl(); 8527 } 8528 } else if (VDecl->isFileVarDecl()) { 8529 if (VDecl->getStorageClass() == SC_Extern && 8530 (!getLangOpts().CPlusPlus || 8531 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8532 VDecl->isExternC())) && 8533 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8534 Diag(VDecl->getLocation(), diag::warn_extern_init); 8535 8536 // C99 6.7.8p4. All file scoped initializers need to be constant. 8537 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8538 CheckForConstantInitializer(Init, DclT); 8539 else if (VDecl->getTLSKind() == VarDecl::TLS_Static && 8540 !VDecl->isInvalidDecl() && !DclT->isDependentType() && 8541 !Init->isValueDependent() && !VDecl->isConstexpr() && 8542 !Init->isConstantInitializer( 8543 Context, VDecl->getType()->isReferenceType())) { 8544 // GNU C++98 edits for __thread, [basic.start.init]p4: 8545 // An object of thread storage duration shall not require dynamic 8546 // initialization. 8547 // FIXME: Need strict checking here. 8548 Diag(VDecl->getLocation(), diag::err_thread_dynamic_init); 8549 if (getLangOpts().CPlusPlus11) 8550 Diag(VDecl->getLocation(), diag::note_use_thread_local); 8551 } 8552 } 8553 8554 // We will represent direct-initialization similarly to copy-initialization: 8555 // int x(1); -as-> int x = 1; 8556 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8557 // 8558 // Clients that want to distinguish between the two forms, can check for 8559 // direct initializer using VarDecl::getInitStyle(). 8560 // A major benefit is that clients that don't particularly care about which 8561 // exactly form was it (like the CodeGen) can handle both cases without 8562 // special case code. 8563 8564 // C++ 8.5p11: 8565 // The form of initialization (using parentheses or '=') is generally 8566 // insignificant, but does matter when the entity being initialized has a 8567 // class type. 8568 if (CXXDirectInit) { 8569 assert(DirectInit && "Call-style initializer must be direct init."); 8570 VDecl->setInitStyle(VarDecl::CallInit); 8571 } else if (DirectInit) { 8572 // This must be list-initialization. No other way is direct-initialization. 8573 VDecl->setInitStyle(VarDecl::ListInit); 8574 } 8575 8576 CheckCompleteVariableDeclaration(VDecl); 8577 } 8578 8579 /// ActOnInitializerError - Given that there was an error parsing an 8580 /// initializer for the given declaration, try to return to some form 8581 /// of sanity. 8582 void Sema::ActOnInitializerError(Decl *D) { 8583 // Our main concern here is re-establishing invariants like "a 8584 // variable's type is either dependent or complete". 8585 if (!D || D->isInvalidDecl()) return; 8586 8587 VarDecl *VD = dyn_cast<VarDecl>(D); 8588 if (!VD) return; 8589 8590 // Auto types are meaningless if we can't make sense of the initializer. 8591 if (ParsingInitForAutoVars.count(D)) { 8592 D->setInvalidDecl(); 8593 return; 8594 } 8595 8596 QualType Ty = VD->getType(); 8597 if (Ty->isDependentType()) return; 8598 8599 // Require a complete type. 8600 if (RequireCompleteType(VD->getLocation(), 8601 Context.getBaseElementType(Ty), 8602 diag::err_typecheck_decl_incomplete_type)) { 8603 VD->setInvalidDecl(); 8604 return; 8605 } 8606 8607 // Require a non-abstract type. 8608 if (RequireNonAbstractType(VD->getLocation(), Ty, 8609 diag::err_abstract_type_in_decl, 8610 AbstractVariableType)) { 8611 VD->setInvalidDecl(); 8612 return; 8613 } 8614 8615 // Don't bother complaining about constructors or destructors, 8616 // though. 8617 } 8618 8619 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8620 bool TypeMayContainAuto) { 8621 // If there is no declaration, there was an error parsing it. Just ignore it. 8622 if (RealDecl == 0) 8623 return; 8624 8625 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8626 QualType Type = Var->getType(); 8627 8628 // C++11 [dcl.spec.auto]p3 8629 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8630 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8631 << Var->getDeclName() << Type; 8632 Var->setInvalidDecl(); 8633 return; 8634 } 8635 8636 // C++11 [class.static.data]p3: A static data member can be declared with 8637 // the constexpr specifier; if so, its declaration shall specify 8638 // a brace-or-equal-initializer. 8639 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8640 // the definition of a variable [...] or the declaration of a static data 8641 // member. 8642 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8643 if (Var->isStaticDataMember()) 8644 Diag(Var->getLocation(), 8645 diag::err_constexpr_static_mem_var_requires_init) 8646 << Var->getDeclName(); 8647 else 8648 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8649 Var->setInvalidDecl(); 8650 return; 8651 } 8652 8653 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8654 // be initialized. 8655 if (!Var->isInvalidDecl() && 8656 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8657 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8658 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8659 Var->setInvalidDecl(); 8660 return; 8661 } 8662 8663 switch (Var->isThisDeclarationADefinition()) { 8664 case VarDecl::Definition: 8665 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8666 break; 8667 8668 // We have an out-of-line definition of a static data member 8669 // that has an in-class initializer, so we type-check this like 8670 // a declaration. 8671 // 8672 // Fall through 8673 8674 case VarDecl::DeclarationOnly: 8675 // It's only a declaration. 8676 8677 // Block scope. C99 6.7p7: If an identifier for an object is 8678 // declared with no linkage (C99 6.2.2p6), the type for the 8679 // object shall be complete. 8680 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8681 !Var->hasLinkage() && !Var->isInvalidDecl() && 8682 RequireCompleteType(Var->getLocation(), Type, 8683 diag::err_typecheck_decl_incomplete_type)) 8684 Var->setInvalidDecl(); 8685 8686 // Make sure that the type is not abstract. 8687 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8688 RequireNonAbstractType(Var->getLocation(), Type, 8689 diag::err_abstract_type_in_decl, 8690 AbstractVariableType)) 8691 Var->setInvalidDecl(); 8692 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8693 Var->getStorageClass() == SC_PrivateExtern) { 8694 Diag(Var->getLocation(), diag::warn_private_extern); 8695 Diag(Var->getLocation(), diag::note_private_extern); 8696 } 8697 8698 return; 8699 8700 case VarDecl::TentativeDefinition: 8701 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8702 // object that has file scope without an initializer, and without a 8703 // storage-class specifier or with the storage-class specifier "static", 8704 // constitutes a tentative definition. Note: A tentative definition with 8705 // external linkage is valid (C99 6.2.2p5). 8706 if (!Var->isInvalidDecl()) { 8707 if (const IncompleteArrayType *ArrayT 8708 = Context.getAsIncompleteArrayType(Type)) { 8709 if (RequireCompleteType(Var->getLocation(), 8710 ArrayT->getElementType(), 8711 diag::err_illegal_decl_array_incomplete_type)) 8712 Var->setInvalidDecl(); 8713 } else if (Var->getStorageClass() == SC_Static) { 8714 // C99 6.9.2p3: If the declaration of an identifier for an object is 8715 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8716 // declared type shall not be an incomplete type. 8717 // NOTE: code such as the following 8718 // static struct s; 8719 // struct s { int a; }; 8720 // is accepted by gcc. Hence here we issue a warning instead of 8721 // an error and we do not invalidate the static declaration. 8722 // NOTE: to avoid multiple warnings, only check the first declaration. 8723 if (Var->isFirstDecl()) 8724 RequireCompleteType(Var->getLocation(), Type, 8725 diag::ext_typecheck_decl_incomplete_type); 8726 } 8727 } 8728 8729 // Record the tentative definition; we're done. 8730 if (!Var->isInvalidDecl()) 8731 TentativeDefinitions.push_back(Var); 8732 return; 8733 } 8734 8735 // Provide a specific diagnostic for uninitialized variable 8736 // definitions with incomplete array type. 8737 if (Type->isIncompleteArrayType()) { 8738 Diag(Var->getLocation(), 8739 diag::err_typecheck_incomplete_array_needs_initializer); 8740 Var->setInvalidDecl(); 8741 return; 8742 } 8743 8744 // Provide a specific diagnostic for uninitialized variable 8745 // definitions with reference type. 8746 if (Type->isReferenceType()) { 8747 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8748 << Var->getDeclName() 8749 << SourceRange(Var->getLocation(), Var->getLocation()); 8750 Var->setInvalidDecl(); 8751 return; 8752 } 8753 8754 // Do not attempt to type-check the default initializer for a 8755 // variable with dependent type. 8756 if (Type->isDependentType()) 8757 return; 8758 8759 if (Var->isInvalidDecl()) 8760 return; 8761 8762 if (RequireCompleteType(Var->getLocation(), 8763 Context.getBaseElementType(Type), 8764 diag::err_typecheck_decl_incomplete_type)) { 8765 Var->setInvalidDecl(); 8766 return; 8767 } 8768 8769 // The variable can not have an abstract class type. 8770 if (RequireNonAbstractType(Var->getLocation(), Type, 8771 diag::err_abstract_type_in_decl, 8772 AbstractVariableType)) { 8773 Var->setInvalidDecl(); 8774 return; 8775 } 8776 8777 // Check for jumps past the implicit initializer. C++0x 8778 // clarifies that this applies to a "variable with automatic 8779 // storage duration", not a "local variable". 8780 // C++11 [stmt.dcl]p3 8781 // A program that jumps from a point where a variable with automatic 8782 // storage duration is not in scope to a point where it is in scope is 8783 // ill-formed unless the variable has scalar type, class type with a 8784 // trivial default constructor and a trivial destructor, a cv-qualified 8785 // version of one of these types, or an array of one of the preceding 8786 // types and is declared without an initializer. 8787 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8788 if (const RecordType *Record 8789 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8790 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8791 // Mark the function for further checking even if the looser rules of 8792 // C++11 do not require such checks, so that we can diagnose 8793 // incompatibilities with C++98. 8794 if (!CXXRecord->isPOD()) 8795 getCurFunction()->setHasBranchProtectedScope(); 8796 } 8797 } 8798 8799 // C++03 [dcl.init]p9: 8800 // If no initializer is specified for an object, and the 8801 // object is of (possibly cv-qualified) non-POD class type (or 8802 // array thereof), the object shall be default-initialized; if 8803 // the object is of const-qualified type, the underlying class 8804 // type shall have a user-declared default 8805 // constructor. Otherwise, if no initializer is specified for 8806 // a non- static object, the object and its subobjects, if 8807 // any, have an indeterminate initial value); if the object 8808 // or any of its subobjects are of const-qualified type, the 8809 // program is ill-formed. 8810 // C++0x [dcl.init]p11: 8811 // If no initializer is specified for an object, the object is 8812 // default-initialized; [...]. 8813 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8814 InitializationKind Kind 8815 = InitializationKind::CreateDefault(Var->getLocation()); 8816 8817 InitializationSequence InitSeq(*this, Entity, Kind, None); 8818 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8819 if (Init.isInvalid()) 8820 Var->setInvalidDecl(); 8821 else if (Init.get()) { 8822 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8823 // This is important for template substitution. 8824 Var->setInitStyle(VarDecl::CallInit); 8825 } 8826 8827 CheckCompleteVariableDeclaration(Var); 8828 } 8829 } 8830 8831 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8832 VarDecl *VD = dyn_cast<VarDecl>(D); 8833 if (!VD) { 8834 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8835 D->setInvalidDecl(); 8836 return; 8837 } 8838 8839 VD->setCXXForRangeDecl(true); 8840 8841 // for-range-declaration cannot be given a storage class specifier. 8842 int Error = -1; 8843 switch (VD->getStorageClass()) { 8844 case SC_None: 8845 break; 8846 case SC_Extern: 8847 Error = 0; 8848 break; 8849 case SC_Static: 8850 Error = 1; 8851 break; 8852 case SC_PrivateExtern: 8853 Error = 2; 8854 break; 8855 case SC_Auto: 8856 Error = 3; 8857 break; 8858 case SC_Register: 8859 Error = 4; 8860 break; 8861 case SC_OpenCLWorkGroupLocal: 8862 llvm_unreachable("Unexpected storage class"); 8863 } 8864 if (VD->isConstexpr()) 8865 Error = 5; 8866 if (Error != -1) { 8867 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8868 << VD->getDeclName() << Error; 8869 D->setInvalidDecl(); 8870 } 8871 } 8872 8873 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8874 if (var->isInvalidDecl()) return; 8875 8876 // In ARC, don't allow jumps past the implicit initialization of a 8877 // local retaining variable. 8878 if (getLangOpts().ObjCAutoRefCount && 8879 var->hasLocalStorage()) { 8880 switch (var->getType().getObjCLifetime()) { 8881 case Qualifiers::OCL_None: 8882 case Qualifiers::OCL_ExplicitNone: 8883 case Qualifiers::OCL_Autoreleasing: 8884 break; 8885 8886 case Qualifiers::OCL_Weak: 8887 case Qualifiers::OCL_Strong: 8888 getCurFunction()->setHasBranchProtectedScope(); 8889 break; 8890 } 8891 } 8892 8893 // Warn about externally-visible variables being defined without a 8894 // prior declaration. We only want to do this for global 8895 // declarations, but we also specifically need to avoid doing it for 8896 // class members because the linkage of an anonymous class can 8897 // change if it's later given a typedef name. 8898 if (var->isThisDeclarationADefinition() && 8899 var->getDeclContext()->getRedeclContext()->isFileContext() && 8900 var->isExternallyVisible() && var->hasLinkage() && 8901 getDiagnostics().getDiagnosticLevel( 8902 diag::warn_missing_variable_declarations, 8903 var->getLocation())) { 8904 // Find a previous declaration that's not a definition. 8905 VarDecl *prev = var->getPreviousDecl(); 8906 while (prev && prev->isThisDeclarationADefinition()) 8907 prev = prev->getPreviousDecl(); 8908 8909 if (!prev) 8910 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8911 } 8912 8913 if (var->getTLSKind() == VarDecl::TLS_Static && 8914 var->getType().isDestructedType()) { 8915 // GNU C++98 edits for __thread, [basic.start.term]p3: 8916 // The type of an object with thread storage duration shall not 8917 // have a non-trivial destructor. 8918 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8919 if (getLangOpts().CPlusPlus11) 8920 Diag(var->getLocation(), diag::note_use_thread_local); 8921 } 8922 8923 if (var->isThisDeclarationADefinition() && 8924 ActiveTemplateInstantiations.empty()) { 8925 PragmaStack<StringLiteral *> *Stack = nullptr; 8926 int SectionFlags = PSF_Implicit | PSF_Read; 8927 if (var->getType().isConstQualified()) 8928 Stack = &ConstSegStack; 8929 else if (!var->getInit()) { 8930 Stack = &BSSSegStack; 8931 SectionFlags |= PSF_Write; 8932 } else { 8933 Stack = &DataSegStack; 8934 SectionFlags |= PSF_Write; 8935 } 8936 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 8937 var->addAttr( 8938 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8939 Stack->CurrentValue->getString(), 8940 Stack->CurrentPragmaLocation)); 8941 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 8942 if (UnifySection(SA->getName(), SectionFlags, var)) 8943 var->dropAttr<SectionAttr>(); 8944 } 8945 8946 // All the following checks are C++ only. 8947 if (!getLangOpts().CPlusPlus) return; 8948 8949 QualType type = var->getType(); 8950 if (type->isDependentType()) return; 8951 8952 // __block variables might require us to capture a copy-initializer. 8953 if (var->hasAttr<BlocksAttr>()) { 8954 // It's currently invalid to ever have a __block variable with an 8955 // array type; should we diagnose that here? 8956 8957 // Regardless, we don't want to ignore array nesting when 8958 // constructing this copy. 8959 if (type->isStructureOrClassType()) { 8960 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 8961 SourceLocation poi = var->getLocation(); 8962 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 8963 ExprResult result 8964 = PerformMoveOrCopyInitialization( 8965 InitializedEntity::InitializeBlock(poi, type, false), 8966 var, var->getType(), varRef, /*AllowNRVO=*/true); 8967 if (!result.isInvalid()) { 8968 result = MaybeCreateExprWithCleanups(result); 8969 Expr *init = result.takeAs<Expr>(); 8970 Context.setBlockVarCopyInits(var, init); 8971 } 8972 } 8973 } 8974 8975 Expr *Init = var->getInit(); 8976 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 8977 QualType baseType = Context.getBaseElementType(type); 8978 8979 if (!var->getDeclContext()->isDependentContext() && 8980 Init && !Init->isValueDependent()) { 8981 if (IsGlobal && !var->isConstexpr() && 8982 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 8983 var->getLocation()) 8984 != DiagnosticsEngine::Ignored) { 8985 // Warn about globals which don't have a constant initializer. Don't 8986 // warn about globals with a non-trivial destructor because we already 8987 // warned about them. 8988 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 8989 if (!(RD && !RD->hasTrivialDestructor()) && 8990 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 8991 Diag(var->getLocation(), diag::warn_global_constructor) 8992 << Init->getSourceRange(); 8993 } 8994 8995 if (var->isConstexpr()) { 8996 SmallVector<PartialDiagnosticAt, 8> Notes; 8997 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 8998 SourceLocation DiagLoc = var->getLocation(); 8999 // If the note doesn't add any useful information other than a source 9000 // location, fold it into the primary diagnostic. 9001 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9002 diag::note_invalid_subexpr_in_const_expr) { 9003 DiagLoc = Notes[0].first; 9004 Notes.clear(); 9005 } 9006 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9007 << var << Init->getSourceRange(); 9008 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9009 Diag(Notes[I].first, Notes[I].second); 9010 } 9011 } else if (var->isUsableInConstantExpressions(Context)) { 9012 // Check whether the initializer of a const variable of integral or 9013 // enumeration type is an ICE now, since we can't tell whether it was 9014 // initialized by a constant expression if we check later. 9015 var->checkInitIsICE(); 9016 } 9017 } 9018 9019 // Require the destructor. 9020 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9021 FinalizeVarWithDestructor(var, recordType); 9022 } 9023 9024 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9025 /// any semantic actions necessary after any initializer has been attached. 9026 void 9027 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9028 // Note that we are no longer parsing the initializer for this declaration. 9029 ParsingInitForAutoVars.erase(ThisDecl); 9030 9031 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9032 if (!VD) 9033 return; 9034 9035 checkAttributesAfterMerging(*this, *VD); 9036 9037 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9038 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9039 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9040 VD->dropAttr<UsedAttr>(); 9041 } 9042 } 9043 9044 if (!VD->isInvalidDecl() && 9045 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9046 if (const VarDecl *Def = VD->getDefinition()) { 9047 if (Def->hasAttr<AliasAttr>()) { 9048 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9049 << VD->getDeclName(); 9050 Diag(Def->getLocation(), diag::note_previous_definition); 9051 VD->setInvalidDecl(); 9052 } 9053 } 9054 } 9055 9056 const DeclContext *DC = VD->getDeclContext(); 9057 // If there's a #pragma GCC visibility in scope, and this isn't a class 9058 // member, set the visibility of this variable. 9059 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9060 AddPushedVisibilityAttribute(VD); 9061 9062 // FIXME: Warn on unused templates. 9063 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate()) 9064 MarkUnusedFileScopedDecl(VD); 9065 9066 // Now we have parsed the initializer and can update the table of magic 9067 // tag values. 9068 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9069 !VD->getType()->isIntegralOrEnumerationType()) 9070 return; 9071 9072 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9073 const Expr *MagicValueExpr = VD->getInit(); 9074 if (!MagicValueExpr) { 9075 continue; 9076 } 9077 llvm::APSInt MagicValueInt; 9078 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9079 Diag(I->getRange().getBegin(), 9080 diag::err_type_tag_for_datatype_not_ice) 9081 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9082 continue; 9083 } 9084 if (MagicValueInt.getActiveBits() > 64) { 9085 Diag(I->getRange().getBegin(), 9086 diag::err_type_tag_for_datatype_too_large) 9087 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9088 continue; 9089 } 9090 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9091 RegisterTypeTagForDatatype(I->getArgumentKind(), 9092 MagicValue, 9093 I->getMatchingCType(), 9094 I->getLayoutCompatible(), 9095 I->getMustBeNull()); 9096 } 9097 } 9098 9099 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9100 ArrayRef<Decl *> Group) { 9101 SmallVector<Decl*, 8> Decls; 9102 9103 if (DS.isTypeSpecOwned()) 9104 Decls.push_back(DS.getRepAsDecl()); 9105 9106 DeclaratorDecl *FirstDeclaratorInGroup = 0; 9107 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9108 if (Decl *D = Group[i]) { 9109 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9110 if (!FirstDeclaratorInGroup) 9111 FirstDeclaratorInGroup = DD; 9112 Decls.push_back(D); 9113 } 9114 9115 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9116 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9117 HandleTagNumbering(*this, Tag, S); 9118 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9119 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9120 } 9121 } 9122 9123 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9124 } 9125 9126 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9127 /// group, performing any necessary semantic checking. 9128 Sema::DeclGroupPtrTy 9129 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9130 bool TypeMayContainAuto) { 9131 // C++0x [dcl.spec.auto]p7: 9132 // If the type deduced for the template parameter U is not the same in each 9133 // deduction, the program is ill-formed. 9134 // FIXME: When initializer-list support is added, a distinction is needed 9135 // between the deduced type U and the deduced type which 'auto' stands for. 9136 // auto a = 0, b = { 1, 2, 3 }; 9137 // is legal because the deduced type U is 'int' in both cases. 9138 if (TypeMayContainAuto && Group.size() > 1) { 9139 QualType Deduced; 9140 CanQualType DeducedCanon; 9141 VarDecl *DeducedDecl = 0; 9142 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9143 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9144 AutoType *AT = D->getType()->getContainedAutoType(); 9145 // Don't reissue diagnostics when instantiating a template. 9146 if (AT && D->isInvalidDecl()) 9147 break; 9148 QualType U = AT ? AT->getDeducedType() : QualType(); 9149 if (!U.isNull()) { 9150 CanQualType UCanon = Context.getCanonicalType(U); 9151 if (Deduced.isNull()) { 9152 Deduced = U; 9153 DeducedCanon = UCanon; 9154 DeducedDecl = D; 9155 } else if (DeducedCanon != UCanon) { 9156 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9157 diag::err_auto_different_deductions) 9158 << (AT->isDecltypeAuto() ? 1 : 0) 9159 << Deduced << DeducedDecl->getDeclName() 9160 << U << D->getDeclName() 9161 << DeducedDecl->getInit()->getSourceRange() 9162 << D->getInit()->getSourceRange(); 9163 D->setInvalidDecl(); 9164 break; 9165 } 9166 } 9167 } 9168 } 9169 } 9170 9171 ActOnDocumentableDecls(Group); 9172 9173 return DeclGroupPtrTy::make( 9174 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9175 } 9176 9177 void Sema::ActOnDocumentableDecl(Decl *D) { 9178 ActOnDocumentableDecls(D); 9179 } 9180 9181 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9182 // Don't parse the comment if Doxygen diagnostics are ignored. 9183 if (Group.empty() || !Group[0]) 9184 return; 9185 9186 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9187 Group[0]->getLocation()) 9188 == DiagnosticsEngine::Ignored) 9189 return; 9190 9191 if (Group.size() >= 2) { 9192 // This is a decl group. Normally it will contain only declarations 9193 // produced from declarator list. But in case we have any definitions or 9194 // additional declaration references: 9195 // 'typedef struct S {} S;' 9196 // 'typedef struct S *S;' 9197 // 'struct S *pS;' 9198 // FinalizeDeclaratorGroup adds these as separate declarations. 9199 Decl *MaybeTagDecl = Group[0]; 9200 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9201 Group = Group.slice(1); 9202 } 9203 } 9204 9205 // See if there are any new comments that are not attached to a decl. 9206 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9207 if (!Comments.empty() && 9208 !Comments.back()->isAttached()) { 9209 // There is at least one comment that not attached to a decl. 9210 // Maybe it should be attached to one of these decls? 9211 // 9212 // Note that this way we pick up not only comments that precede the 9213 // declaration, but also comments that *follow* the declaration -- thanks to 9214 // the lookahead in the lexer: we've consumed the semicolon and looked 9215 // ahead through comments. 9216 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9217 Context.getCommentForDecl(Group[i], &PP); 9218 } 9219 } 9220 9221 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9222 /// to introduce parameters into function prototype scope. 9223 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9224 const DeclSpec &DS = D.getDeclSpec(); 9225 9226 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9227 9228 // C++03 [dcl.stc]p2 also permits 'auto'. 9229 VarDecl::StorageClass StorageClass = SC_None; 9230 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9231 StorageClass = SC_Register; 9232 } else if (getLangOpts().CPlusPlus && 9233 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9234 StorageClass = SC_Auto; 9235 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9236 Diag(DS.getStorageClassSpecLoc(), 9237 diag::err_invalid_storage_class_in_func_decl); 9238 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9239 } 9240 9241 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9242 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9243 << DeclSpec::getSpecifierName(TSCS); 9244 if (DS.isConstexprSpecified()) 9245 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9246 << 0; 9247 9248 DiagnoseFunctionSpecifiers(DS); 9249 9250 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9251 QualType parmDeclType = TInfo->getType(); 9252 9253 if (getLangOpts().CPlusPlus) { 9254 // Check that there are no default arguments inside the type of this 9255 // parameter. 9256 CheckExtraCXXDefaultArguments(D); 9257 9258 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9259 if (D.getCXXScopeSpec().isSet()) { 9260 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9261 << D.getCXXScopeSpec().getRange(); 9262 D.getCXXScopeSpec().clear(); 9263 } 9264 } 9265 9266 // Ensure we have a valid name 9267 IdentifierInfo *II = 0; 9268 if (D.hasName()) { 9269 II = D.getIdentifier(); 9270 if (!II) { 9271 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9272 << GetNameForDeclarator(D).getName(); 9273 D.setInvalidType(true); 9274 } 9275 } 9276 9277 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9278 if (II) { 9279 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9280 ForRedeclaration); 9281 LookupName(R, S); 9282 if (R.isSingleResult()) { 9283 NamedDecl *PrevDecl = R.getFoundDecl(); 9284 if (PrevDecl->isTemplateParameter()) { 9285 // Maybe we will complain about the shadowed template parameter. 9286 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9287 // Just pretend that we didn't see the previous declaration. 9288 PrevDecl = 0; 9289 } else if (S->isDeclScope(PrevDecl)) { 9290 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9291 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9292 9293 // Recover by removing the name 9294 II = 0; 9295 D.SetIdentifier(0, D.getIdentifierLoc()); 9296 D.setInvalidType(true); 9297 } 9298 } 9299 } 9300 9301 // Temporarily put parameter variables in the translation unit, not 9302 // the enclosing context. This prevents them from accidentally 9303 // looking like class members in C++. 9304 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9305 D.getLocStart(), 9306 D.getIdentifierLoc(), II, 9307 parmDeclType, TInfo, 9308 StorageClass); 9309 9310 if (D.isInvalidType()) 9311 New->setInvalidDecl(); 9312 9313 assert(S->isFunctionPrototypeScope()); 9314 assert(S->getFunctionPrototypeDepth() >= 1); 9315 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9316 S->getNextFunctionPrototypeIndex()); 9317 9318 // Add the parameter declaration into this scope. 9319 S->AddDecl(New); 9320 if (II) 9321 IdResolver.AddDecl(New); 9322 9323 ProcessDeclAttributes(S, New, D); 9324 9325 if (D.getDeclSpec().isModulePrivateSpecified()) 9326 Diag(New->getLocation(), diag::err_module_private_local) 9327 << 1 << New->getDeclName() 9328 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9329 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9330 9331 if (New->hasAttr<BlocksAttr>()) { 9332 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9333 } 9334 return New; 9335 } 9336 9337 /// \brief Synthesizes a variable for a parameter arising from a 9338 /// typedef. 9339 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9340 SourceLocation Loc, 9341 QualType T) { 9342 /* FIXME: setting StartLoc == Loc. 9343 Would it be worth to modify callers so as to provide proper source 9344 location for the unnamed parameters, embedding the parameter's type? */ 9345 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 9346 T, Context.getTrivialTypeSourceInfo(T, Loc), 9347 SC_None, 0); 9348 Param->setImplicit(); 9349 return Param; 9350 } 9351 9352 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9353 ParmVarDecl * const *ParamEnd) { 9354 // Don't diagnose unused-parameter errors in template instantiations; we 9355 // will already have done so in the template itself. 9356 if (!ActiveTemplateInstantiations.empty()) 9357 return; 9358 9359 for (; Param != ParamEnd; ++Param) { 9360 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9361 !(*Param)->hasAttr<UnusedAttr>()) { 9362 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9363 << (*Param)->getDeclName(); 9364 } 9365 } 9366 } 9367 9368 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9369 ParmVarDecl * const *ParamEnd, 9370 QualType ReturnTy, 9371 NamedDecl *D) { 9372 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9373 return; 9374 9375 // Warn if the return value is pass-by-value and larger than the specified 9376 // threshold. 9377 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9378 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9379 if (Size > LangOpts.NumLargeByValueCopy) 9380 Diag(D->getLocation(), diag::warn_return_value_size) 9381 << D->getDeclName() << Size; 9382 } 9383 9384 // Warn if any parameter is pass-by-value and larger than the specified 9385 // threshold. 9386 for (; Param != ParamEnd; ++Param) { 9387 QualType T = (*Param)->getType(); 9388 if (T->isDependentType() || !T.isPODType(Context)) 9389 continue; 9390 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9391 if (Size > LangOpts.NumLargeByValueCopy) 9392 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9393 << (*Param)->getDeclName() << Size; 9394 } 9395 } 9396 9397 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9398 SourceLocation NameLoc, IdentifierInfo *Name, 9399 QualType T, TypeSourceInfo *TSInfo, 9400 VarDecl::StorageClass StorageClass) { 9401 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9402 if (getLangOpts().ObjCAutoRefCount && 9403 T.getObjCLifetime() == Qualifiers::OCL_None && 9404 T->isObjCLifetimeType()) { 9405 9406 Qualifiers::ObjCLifetime lifetime; 9407 9408 // Special cases for arrays: 9409 // - if it's const, use __unsafe_unretained 9410 // - otherwise, it's an error 9411 if (T->isArrayType()) { 9412 if (!T.isConstQualified()) { 9413 DelayedDiagnostics.add( 9414 sema::DelayedDiagnostic::makeForbiddenType( 9415 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9416 } 9417 lifetime = Qualifiers::OCL_ExplicitNone; 9418 } else { 9419 lifetime = T->getObjCARCImplicitLifetime(); 9420 } 9421 T = Context.getLifetimeQualifiedType(T, lifetime); 9422 } 9423 9424 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9425 Context.getAdjustedParameterType(T), 9426 TSInfo, 9427 StorageClass, 0); 9428 9429 // Parameters can not be abstract class types. 9430 // For record types, this is done by the AbstractClassUsageDiagnoser once 9431 // the class has been completely parsed. 9432 if (!CurContext->isRecord() && 9433 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9434 AbstractParamType)) 9435 New->setInvalidDecl(); 9436 9437 // Parameter declarators cannot be interface types. All ObjC objects are 9438 // passed by reference. 9439 if (T->isObjCObjectType()) { 9440 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9441 Diag(NameLoc, 9442 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9443 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9444 T = Context.getObjCObjectPointerType(T); 9445 New->setType(T); 9446 } 9447 9448 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9449 // duration shall not be qualified by an address-space qualifier." 9450 // Since all parameters have automatic store duration, they can not have 9451 // an address space. 9452 if (T.getAddressSpace() != 0) { 9453 // OpenCL allows function arguments declared to be an array of a type 9454 // to be qualified with an address space. 9455 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9456 Diag(NameLoc, diag::err_arg_with_address_space); 9457 New->setInvalidDecl(); 9458 } 9459 } 9460 9461 return New; 9462 } 9463 9464 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9465 SourceLocation LocAfterDecls) { 9466 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9467 9468 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9469 // for a K&R function. 9470 if (!FTI.hasPrototype) { 9471 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9472 --i; 9473 if (FTI.Params[i].Param == 0) { 9474 SmallString<256> Code; 9475 llvm::raw_svector_ostream(Code) 9476 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9477 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9478 << FTI.Params[i].Ident 9479 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9480 9481 // Implicitly declare the argument as type 'int' for lack of a better 9482 // type. 9483 AttributeFactory attrs; 9484 DeclSpec DS(attrs); 9485 const char* PrevSpec; // unused 9486 unsigned DiagID; // unused 9487 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9488 DiagID, Context.getPrintingPolicy()); 9489 // Use the identifier location for the type source range. 9490 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9491 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9492 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9493 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9494 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9495 } 9496 } 9497 } 9498 } 9499 9500 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9501 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 9502 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9503 Scope *ParentScope = FnBodyScope->getParent(); 9504 9505 D.setFunctionDefinitionKind(FDK_Definition); 9506 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9507 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9508 } 9509 9510 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9511 const FunctionDecl*& PossibleZeroParamPrototype) { 9512 // Don't warn about invalid declarations. 9513 if (FD->isInvalidDecl()) 9514 return false; 9515 9516 // Or declarations that aren't global. 9517 if (!FD->isGlobal()) 9518 return false; 9519 9520 // Don't warn about C++ member functions. 9521 if (isa<CXXMethodDecl>(FD)) 9522 return false; 9523 9524 // Don't warn about 'main'. 9525 if (FD->isMain()) 9526 return false; 9527 9528 // Don't warn about inline functions. 9529 if (FD->isInlined()) 9530 return false; 9531 9532 // Don't warn about function templates. 9533 if (FD->getDescribedFunctionTemplate()) 9534 return false; 9535 9536 // Don't warn about function template specializations. 9537 if (FD->isFunctionTemplateSpecialization()) 9538 return false; 9539 9540 // Don't warn for OpenCL kernels. 9541 if (FD->hasAttr<OpenCLKernelAttr>()) 9542 return false; 9543 9544 bool MissingPrototype = true; 9545 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9546 Prev; Prev = Prev->getPreviousDecl()) { 9547 // Ignore any declarations that occur in function or method 9548 // scope, because they aren't visible from the header. 9549 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9550 continue; 9551 9552 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9553 if (FD->getNumParams() == 0) 9554 PossibleZeroParamPrototype = Prev; 9555 break; 9556 } 9557 9558 return MissingPrototype; 9559 } 9560 9561 void 9562 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9563 const FunctionDecl *EffectiveDefinition) { 9564 // Don't complain if we're in GNU89 mode and the previous definition 9565 // was an extern inline function. 9566 const FunctionDecl *Definition = EffectiveDefinition; 9567 if (!Definition) 9568 if (!FD->isDefined(Definition)) 9569 return; 9570 9571 if (canRedefineFunction(Definition, getLangOpts())) 9572 return; 9573 9574 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9575 Definition->getStorageClass() == SC_Extern) 9576 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9577 << FD->getDeclName() << getLangOpts().CPlusPlus; 9578 else 9579 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9580 9581 Diag(Definition->getLocation(), diag::note_previous_definition); 9582 FD->setInvalidDecl(); 9583 } 9584 9585 9586 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9587 Sema &S) { 9588 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9589 9590 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9591 LSI->CallOperator = CallOperator; 9592 LSI->Lambda = LambdaClass; 9593 LSI->ReturnType = CallOperator->getReturnType(); 9594 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9595 9596 if (LCD == LCD_None) 9597 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9598 else if (LCD == LCD_ByCopy) 9599 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9600 else if (LCD == LCD_ByRef) 9601 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9602 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9603 9604 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9605 LSI->Mutable = !CallOperator->isConst(); 9606 9607 // Add the captures to the LSI so they can be noted as already 9608 // captured within tryCaptureVar. 9609 for (const auto &C : LambdaClass->captures()) { 9610 if (C.capturesVariable()) { 9611 VarDecl *VD = C.getCapturedVar(); 9612 if (VD->isInitCapture()) 9613 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9614 QualType CaptureType = VD->getType(); 9615 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 9616 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9617 /*RefersToEnclosingLocal*/true, C.getLocation(), 9618 /*EllipsisLoc*/C.isPackExpansion() 9619 ? C.getEllipsisLoc() : SourceLocation(), 9620 CaptureType, /*Expr*/ 0); 9621 9622 } else if (C.capturesThis()) { 9623 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 9624 S.getCurrentThisType(), /*Expr*/ 0); 9625 } 9626 } 9627 } 9628 9629 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9630 // Clear the last template instantiation error context. 9631 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9632 9633 if (!D) 9634 return D; 9635 FunctionDecl *FD = 0; 9636 9637 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9638 FD = FunTmpl->getTemplatedDecl(); 9639 else 9640 FD = cast<FunctionDecl>(D); 9641 // If we are instantiating a generic lambda call operator, push 9642 // a LambdaScopeInfo onto the function stack. But use the information 9643 // that's already been calculated (ActOnLambdaExpr) to prime the current 9644 // LambdaScopeInfo. 9645 // When the template operator is being specialized, the LambdaScopeInfo, 9646 // has to be properly restored so that tryCaptureVariable doesn't try 9647 // and capture any new variables. In addition when calculating potential 9648 // captures during transformation of nested lambdas, it is necessary to 9649 // have the LSI properly restored. 9650 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9651 assert(ActiveTemplateInstantiations.size() && 9652 "There should be an active template instantiation on the stack " 9653 "when instantiating a generic lambda!"); 9654 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9655 } 9656 else 9657 // Enter a new function scope 9658 PushFunctionScope(); 9659 9660 // See if this is a redefinition. 9661 if (!FD->isLateTemplateParsed()) 9662 CheckForFunctionRedefinition(FD); 9663 9664 // Builtin functions cannot be defined. 9665 if (unsigned BuiltinID = FD->getBuiltinID()) { 9666 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9667 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9668 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9669 FD->setInvalidDecl(); 9670 } 9671 } 9672 9673 // The return type of a function definition must be complete 9674 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9675 QualType ResultType = FD->getReturnType(); 9676 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9677 !FD->isInvalidDecl() && 9678 RequireCompleteType(FD->getLocation(), ResultType, 9679 diag::err_func_def_incomplete_result)) 9680 FD->setInvalidDecl(); 9681 9682 // GNU warning -Wmissing-prototypes: 9683 // Warn if a global function is defined without a previous 9684 // prototype declaration. This warning is issued even if the 9685 // definition itself provides a prototype. The aim is to detect 9686 // global functions that fail to be declared in header files. 9687 const FunctionDecl *PossibleZeroParamPrototype = 0; 9688 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9689 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9690 9691 if (PossibleZeroParamPrototype) { 9692 // We found a declaration that is not a prototype, 9693 // but that could be a zero-parameter prototype 9694 if (TypeSourceInfo *TI = 9695 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9696 TypeLoc TL = TI->getTypeLoc(); 9697 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9698 Diag(PossibleZeroParamPrototype->getLocation(), 9699 diag::note_declaration_not_a_prototype) 9700 << PossibleZeroParamPrototype 9701 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9702 } 9703 } 9704 } 9705 9706 if (FnBodyScope) 9707 PushDeclContext(FnBodyScope, FD); 9708 9709 // Check the validity of our function parameters 9710 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9711 /*CheckParameterNames=*/true); 9712 9713 // Introduce our parameters into the function scope 9714 for (auto Param : FD->params()) { 9715 Param->setOwningFunction(FD); 9716 9717 // If this has an identifier, add it to the scope stack. 9718 if (Param->getIdentifier() && FnBodyScope) { 9719 CheckShadow(FnBodyScope, Param); 9720 9721 PushOnScopeChains(Param, FnBodyScope); 9722 } 9723 } 9724 9725 // If we had any tags defined in the function prototype, 9726 // introduce them into the function scope. 9727 if (FnBodyScope) { 9728 for (ArrayRef<NamedDecl *>::iterator 9729 I = FD->getDeclsInPrototypeScope().begin(), 9730 E = FD->getDeclsInPrototypeScope().end(); 9731 I != E; ++I) { 9732 NamedDecl *D = *I; 9733 9734 // Some of these decls (like enums) may have been pinned to the translation unit 9735 // for lack of a real context earlier. If so, remove from the translation unit 9736 // and reattach to the current context. 9737 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9738 // Is the decl actually in the context? 9739 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9740 if (DI == D) { 9741 Context.getTranslationUnitDecl()->removeDecl(D); 9742 break; 9743 } 9744 } 9745 // Either way, reassign the lexical decl context to our FunctionDecl. 9746 D->setLexicalDeclContext(CurContext); 9747 } 9748 9749 // If the decl has a non-null name, make accessible in the current scope. 9750 if (!D->getName().empty()) 9751 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9752 9753 // Similarly, dive into enums and fish their constants out, making them 9754 // accessible in this scope. 9755 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9756 for (auto *EI : ED->enumerators()) 9757 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9758 } 9759 } 9760 } 9761 9762 // Ensure that the function's exception specification is instantiated. 9763 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9764 ResolveExceptionSpec(D->getLocation(), FPT); 9765 9766 // Checking attributes of current function definition 9767 // dllimport attribute. 9768 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 9769 if (DA && (!FD->hasAttr<DLLExportAttr>())) { 9770 // dllimport attribute cannot be directly applied to definition. 9771 // Microsoft accepts dllimport for functions defined within class scope. 9772 if (!DA->isInherited() && 9773 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 9774 Diag(FD->getLocation(), 9775 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 9776 << DA; 9777 FD->setInvalidDecl(); 9778 return D; 9779 } 9780 } 9781 // We want to attach documentation to original Decl (which might be 9782 // a function template). 9783 ActOnDocumentableDecl(D); 9784 return D; 9785 } 9786 9787 /// \brief Given the set of return statements within a function body, 9788 /// compute the variables that are subject to the named return value 9789 /// optimization. 9790 /// 9791 /// Each of the variables that is subject to the named return value 9792 /// optimization will be marked as NRVO variables in the AST, and any 9793 /// return statement that has a marked NRVO variable as its NRVO candidate can 9794 /// use the named return value optimization. 9795 /// 9796 /// This function applies a very simplistic algorithm for NRVO: if every return 9797 /// statement in the function has the same NRVO candidate, that candidate is 9798 /// the NRVO variable. 9799 /// 9800 /// FIXME: Employ a smarter algorithm that accounts for multiple return 9801 /// statements and the lifetimes of the NRVO candidates. We should be able to 9802 /// find a maximal set of NRVO variables. 9803 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9804 ReturnStmt **Returns = Scope->Returns.data(); 9805 9806 const VarDecl *NRVOCandidate = 0; 9807 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9808 if (!Returns[I]->getNRVOCandidate()) 9809 return; 9810 9811 if (!NRVOCandidate) 9812 NRVOCandidate = Returns[I]->getNRVOCandidate(); 9813 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 9814 return; 9815 } 9816 9817 if (NRVOCandidate) 9818 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 9819 } 9820 9821 bool Sema::canDelayFunctionBody(const Declarator &D) { 9822 // We can't delay parsing the body of a constexpr function template (yet). 9823 if (D.getDeclSpec().isConstexprSpecified()) 9824 return false; 9825 9826 // We can't delay parsing the body of a function template with a deduced 9827 // return type (yet). 9828 if (D.getDeclSpec().containsPlaceholderType()) { 9829 // If the placeholder introduces a non-deduced trailing return type, 9830 // we can still delay parsing it. 9831 if (D.getNumTypeObjects()) { 9832 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 9833 if (Outer.Kind == DeclaratorChunk::Function && 9834 Outer.Fun.hasTrailingReturnType()) { 9835 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 9836 return Ty.isNull() || !Ty->isUndeducedType(); 9837 } 9838 } 9839 return false; 9840 } 9841 9842 return true; 9843 } 9844 9845 bool Sema::canSkipFunctionBody(Decl *D) { 9846 // We cannot skip the body of a function (or function template) which is 9847 // constexpr, since we may need to evaluate its body in order to parse the 9848 // rest of the file. 9849 // We cannot skip the body of a function with an undeduced return type, 9850 // because any callers of that function need to know the type. 9851 if (const FunctionDecl *FD = D->getAsFunction()) 9852 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9853 return false; 9854 return Consumer.shouldSkipFunctionBody(D); 9855 } 9856 9857 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9858 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9859 FD->setHasSkippedBody(); 9860 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9861 MD->setHasSkippedBody(); 9862 return ActOnFinishFunctionBody(Decl, 0); 9863 } 9864 9865 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9866 return ActOnFinishFunctionBody(D, BodyArg, false); 9867 } 9868 9869 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9870 bool IsInstantiation) { 9871 FunctionDecl *FD = dcl ? dcl->getAsFunction() : 0; 9872 9873 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9874 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 9875 9876 if (FD) { 9877 FD->setBody(Body); 9878 9879 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9880 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9881 // If the function has a deduced result type but contains no 'return' 9882 // statements, the result type as written must be exactly 'auto', and 9883 // the deduced result type is 'void'. 9884 if (!FD->getReturnType()->getAs<AutoType>()) { 9885 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9886 << FD->getReturnType(); 9887 FD->setInvalidDecl(); 9888 } else { 9889 // Substitute 'void' for the 'auto' in the type. 9890 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9891 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9892 Context.adjustDeducedFunctionResultType( 9893 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9894 } 9895 } 9896 9897 // The only way to be included in UndefinedButUsed is if there is an 9898 // ODR use before the definition. Avoid the expensive map lookup if this 9899 // is the first declaration. 9900 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9901 if (!FD->isExternallyVisible()) 9902 UndefinedButUsed.erase(FD); 9903 else if (FD->isInlined() && 9904 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9905 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9906 UndefinedButUsed.erase(FD); 9907 } 9908 9909 // If the function implicitly returns zero (like 'main') or is naked, 9910 // don't complain about missing return statements. 9911 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9912 WP.disableCheckFallThrough(); 9913 9914 // MSVC permits the use of pure specifier (=0) on function definition, 9915 // defined at class scope, warn about this non-standard construct. 9916 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 9917 Diag(FD->getLocation(), diag::warn_pure_function_definition); 9918 9919 if (!FD->isInvalidDecl()) { 9920 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 9921 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 9922 FD->getReturnType(), FD); 9923 9924 // If this is a constructor, we need a vtable. 9925 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 9926 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 9927 9928 // Try to apply the named return value optimization. We have to check 9929 // if we can do this here because lambdas keep return statements around 9930 // to deduce an implicit return type. 9931 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 9932 !FD->isDependentContext()) 9933 computeNRVO(Body, getCurFunction()); 9934 } 9935 9936 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 9937 "Function parsing confused"); 9938 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 9939 assert(MD == getCurMethodDecl() && "Method parsing confused"); 9940 MD->setBody(Body); 9941 if (!MD->isInvalidDecl()) { 9942 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 9943 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 9944 MD->getReturnType(), MD); 9945 9946 if (Body) 9947 computeNRVO(Body, getCurFunction()); 9948 } 9949 if (getCurFunction()->ObjCShouldCallSuper) { 9950 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 9951 << MD->getSelector().getAsString(); 9952 getCurFunction()->ObjCShouldCallSuper = false; 9953 } 9954 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 9955 const ObjCMethodDecl *InitMethod = 0; 9956 bool isDesignated = 9957 MD->isDesignatedInitializerForTheInterface(&InitMethod); 9958 assert(isDesignated && InitMethod); 9959 (void)isDesignated; 9960 9961 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 9962 auto IFace = MD->getClassInterface(); 9963 if (!IFace) 9964 return false; 9965 auto SuperD = IFace->getSuperClass(); 9966 if (!SuperD) 9967 return false; 9968 return SuperD->getIdentifier() == 9969 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 9970 }; 9971 // Don't issue this warning for unavailable inits or direct subclasses 9972 // of NSObject. 9973 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 9974 Diag(MD->getLocation(), 9975 diag::warn_objc_designated_init_missing_super_call); 9976 Diag(InitMethod->getLocation(), 9977 diag::note_objc_designated_init_marked_here); 9978 } 9979 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 9980 } 9981 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 9982 // Don't issue this warning for unavaialable inits. 9983 if (!MD->isUnavailable()) 9984 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 9985 getCurFunction()->ObjCWarnForNoInitDelegation = false; 9986 } 9987 } else { 9988 return 0; 9989 } 9990 9991 assert(!getCurFunction()->ObjCShouldCallSuper && 9992 "This should only be set for ObjC methods, which should have been " 9993 "handled in the block above."); 9994 9995 // Verify and clean out per-function state. 9996 if (Body) { 9997 // C++ constructors that have function-try-blocks can't have return 9998 // statements in the handlers of that block. (C++ [except.handle]p14) 9999 // Verify this. 10000 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10001 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10002 10003 // Verify that gotos and switch cases don't jump into scopes illegally. 10004 if (getCurFunction()->NeedsScopeChecking() && 10005 !dcl->isInvalidDecl() && 10006 !hasAnyUnrecoverableErrorsInThisFunction() && 10007 !PP.isCodeCompletionEnabled()) 10008 DiagnoseInvalidJumps(Body); 10009 10010 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10011 if (!Destructor->getParent()->isDependentType()) 10012 CheckDestructor(Destructor); 10013 10014 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10015 Destructor->getParent()); 10016 } 10017 10018 // If any errors have occurred, clear out any temporaries that may have 10019 // been leftover. This ensures that these temporaries won't be picked up for 10020 // deletion in some later function. 10021 if (PP.getDiagnostics().hasErrorOccurred() || 10022 PP.getDiagnostics().getSuppressAllDiagnostics()) { 10023 DiscardCleanupsInEvaluationContext(); 10024 } 10025 if (!PP.getDiagnostics().hasUncompilableErrorOccurred() && 10026 !isa<FunctionTemplateDecl>(dcl)) { 10027 // Since the body is valid, issue any analysis-based warnings that are 10028 // enabled. 10029 ActivePolicy = &WP; 10030 } 10031 10032 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10033 (!CheckConstexprFunctionDecl(FD) || 10034 !CheckConstexprFunctionBody(FD, Body))) 10035 FD->setInvalidDecl(); 10036 10037 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10038 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10039 assert(MaybeODRUseExprs.empty() && 10040 "Leftover expressions for odr-use checking"); 10041 } 10042 10043 if (!IsInstantiation) 10044 PopDeclContext(); 10045 10046 PopFunctionScopeInfo(ActivePolicy, dcl); 10047 // If any errors have occurred, clear out any temporaries that may have 10048 // been leftover. This ensures that these temporaries won't be picked up for 10049 // deletion in some later function. 10050 if (getDiagnostics().hasErrorOccurred()) { 10051 DiscardCleanupsInEvaluationContext(); 10052 } 10053 10054 return dcl; 10055 } 10056 10057 10058 /// When we finish delayed parsing of an attribute, we must attach it to the 10059 /// relevant Decl. 10060 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10061 ParsedAttributes &Attrs) { 10062 // Always attach attributes to the underlying decl. 10063 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10064 D = TD->getTemplatedDecl(); 10065 ProcessDeclAttributeList(S, D, Attrs.getList()); 10066 10067 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10068 if (Method->isStatic()) 10069 checkThisInStaticMemberFunctionAttributes(Method); 10070 } 10071 10072 10073 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10074 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10075 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10076 IdentifierInfo &II, Scope *S) { 10077 // Before we produce a declaration for an implicitly defined 10078 // function, see whether there was a locally-scoped declaration of 10079 // this name as a function or variable. If so, use that 10080 // (non-visible) declaration, and complain about it. 10081 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10082 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10083 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10084 return ExternCPrev; 10085 } 10086 10087 // Extension in C99. Legal in C90, but warn about it. 10088 unsigned diag_id; 10089 if (II.getName().startswith("__builtin_")) 10090 diag_id = diag::warn_builtin_unknown; 10091 else if (getLangOpts().C99) 10092 diag_id = diag::ext_implicit_function_decl; 10093 else 10094 diag_id = diag::warn_implicit_function_decl; 10095 Diag(Loc, diag_id) << &II; 10096 10097 // Because typo correction is expensive, only do it if the implicit 10098 // function declaration is going to be treated as an error. 10099 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10100 TypoCorrection Corrected; 10101 DeclFilterCCC<FunctionDecl> Validator; 10102 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10103 LookupOrdinaryName, S, 0, Validator))) 10104 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10105 /*ErrorRecovery*/false); 10106 } 10107 10108 // Set a Declarator for the implicit definition: int foo(); 10109 const char *Dummy; 10110 AttributeFactory attrFactory; 10111 DeclSpec DS(attrFactory); 10112 unsigned DiagID; 10113 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10114 Context.getPrintingPolicy()); 10115 (void)Error; // Silence warning. 10116 assert(!Error && "Error setting up implicit decl!"); 10117 SourceLocation NoLoc; 10118 Declarator D(DS, Declarator::BlockContext); 10119 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10120 /*IsAmbiguous=*/false, 10121 /*LParenLoc=*/NoLoc, 10122 /*Params=*/0, 10123 /*NumParams=*/0, 10124 /*EllipsisLoc=*/NoLoc, 10125 /*RParenLoc=*/NoLoc, 10126 /*TypeQuals=*/0, 10127 /*RefQualifierIsLvalueRef=*/true, 10128 /*RefQualifierLoc=*/NoLoc, 10129 /*ConstQualifierLoc=*/NoLoc, 10130 /*VolatileQualifierLoc=*/NoLoc, 10131 /*MutableLoc=*/NoLoc, 10132 EST_None, 10133 /*ESpecLoc=*/NoLoc, 10134 /*Exceptions=*/0, 10135 /*ExceptionRanges=*/0, 10136 /*NumExceptions=*/0, 10137 /*NoexceptExpr=*/0, 10138 Loc, Loc, D), 10139 DS.getAttributes(), 10140 SourceLocation()); 10141 D.SetIdentifier(&II, Loc); 10142 10143 // Insert this function into translation-unit scope. 10144 10145 DeclContext *PrevDC = CurContext; 10146 CurContext = Context.getTranslationUnitDecl(); 10147 10148 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10149 FD->setImplicit(); 10150 10151 CurContext = PrevDC; 10152 10153 AddKnownFunctionAttributes(FD); 10154 10155 return FD; 10156 } 10157 10158 /// \brief Adds any function attributes that we know a priori based on 10159 /// the declaration of this function. 10160 /// 10161 /// These attributes can apply both to implicitly-declared builtins 10162 /// (like __builtin___printf_chk) or to library-declared functions 10163 /// like NSLog or printf. 10164 /// 10165 /// We need to check for duplicate attributes both here and where user-written 10166 /// attributes are applied to declarations. 10167 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10168 if (FD->isInvalidDecl()) 10169 return; 10170 10171 // If this is a built-in function, map its builtin attributes to 10172 // actual attributes. 10173 if (unsigned BuiltinID = FD->getBuiltinID()) { 10174 // Handle printf-formatting attributes. 10175 unsigned FormatIdx; 10176 bool HasVAListArg; 10177 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10178 if (!FD->hasAttr<FormatAttr>()) { 10179 const char *fmt = "printf"; 10180 unsigned int NumParams = FD->getNumParams(); 10181 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10182 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10183 fmt = "NSString"; 10184 FD->addAttr(FormatAttr::CreateImplicit(Context, 10185 &Context.Idents.get(fmt), 10186 FormatIdx+1, 10187 HasVAListArg ? 0 : FormatIdx+2, 10188 FD->getLocation())); 10189 } 10190 } 10191 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10192 HasVAListArg)) { 10193 if (!FD->hasAttr<FormatAttr>()) 10194 FD->addAttr(FormatAttr::CreateImplicit(Context, 10195 &Context.Idents.get("scanf"), 10196 FormatIdx+1, 10197 HasVAListArg ? 0 : FormatIdx+2, 10198 FD->getLocation())); 10199 } 10200 10201 // Mark const if we don't care about errno and that is the only 10202 // thing preventing the function from being const. This allows 10203 // IRgen to use LLVM intrinsics for such functions. 10204 if (!getLangOpts().MathErrno && 10205 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10206 if (!FD->hasAttr<ConstAttr>()) 10207 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10208 } 10209 10210 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10211 !FD->hasAttr<ReturnsTwiceAttr>()) 10212 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10213 FD->getLocation())); 10214 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10215 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10216 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10217 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10218 } 10219 10220 IdentifierInfo *Name = FD->getIdentifier(); 10221 if (!Name) 10222 return; 10223 if ((!getLangOpts().CPlusPlus && 10224 FD->getDeclContext()->isTranslationUnit()) || 10225 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10226 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10227 LinkageSpecDecl::lang_c)) { 10228 // Okay: this could be a libc/libm/Objective-C function we know 10229 // about. 10230 } else 10231 return; 10232 10233 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10234 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10235 // target-specific builtins, perhaps? 10236 if (!FD->hasAttr<FormatAttr>()) 10237 FD->addAttr(FormatAttr::CreateImplicit(Context, 10238 &Context.Idents.get("printf"), 2, 10239 Name->isStr("vasprintf") ? 0 : 3, 10240 FD->getLocation())); 10241 } 10242 10243 if (Name->isStr("__CFStringMakeConstantString")) { 10244 // We already have a __builtin___CFStringMakeConstantString, 10245 // but builds that use -fno-constant-cfstrings don't go through that. 10246 if (!FD->hasAttr<FormatArgAttr>()) 10247 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10248 FD->getLocation())); 10249 } 10250 } 10251 10252 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10253 TypeSourceInfo *TInfo) { 10254 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10255 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10256 10257 if (!TInfo) { 10258 assert(D.isInvalidType() && "no declarator info for valid type"); 10259 TInfo = Context.getTrivialTypeSourceInfo(T); 10260 } 10261 10262 // Scope manipulation handled by caller. 10263 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10264 D.getLocStart(), 10265 D.getIdentifierLoc(), 10266 D.getIdentifier(), 10267 TInfo); 10268 10269 // Bail out immediately if we have an invalid declaration. 10270 if (D.isInvalidType()) { 10271 NewTD->setInvalidDecl(); 10272 return NewTD; 10273 } 10274 10275 if (D.getDeclSpec().isModulePrivateSpecified()) { 10276 if (CurContext->isFunctionOrMethod()) 10277 Diag(NewTD->getLocation(), diag::err_module_private_local) 10278 << 2 << NewTD->getDeclName() 10279 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10280 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10281 else 10282 NewTD->setModulePrivate(); 10283 } 10284 10285 // C++ [dcl.typedef]p8: 10286 // If the typedef declaration defines an unnamed class (or 10287 // enum), the first typedef-name declared by the declaration 10288 // to be that class type (or enum type) is used to denote the 10289 // class type (or enum type) for linkage purposes only. 10290 // We need to check whether the type was declared in the declaration. 10291 switch (D.getDeclSpec().getTypeSpecType()) { 10292 case TST_enum: 10293 case TST_struct: 10294 case TST_interface: 10295 case TST_union: 10296 case TST_class: { 10297 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10298 10299 // Do nothing if the tag is not anonymous or already has an 10300 // associated typedef (from an earlier typedef in this decl group). 10301 if (tagFromDeclSpec->getIdentifier()) break; 10302 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10303 10304 // A well-formed anonymous tag must always be a TUK_Definition. 10305 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10306 10307 // The type must match the tag exactly; no qualifiers allowed. 10308 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10309 break; 10310 10311 // If we've already computed linkage for the anonymous tag, then 10312 // adding a typedef name for the anonymous decl can change that 10313 // linkage, which might be a serious problem. Diagnose this as 10314 // unsupported and ignore the typedef name. TODO: we should 10315 // pursue this as a language defect and establish a formal rule 10316 // for how to handle it. 10317 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10318 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10319 10320 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10321 tagLoc = Lexer::getLocForEndOfToken(tagLoc, 0, getSourceManager(), 10322 getLangOpts()); 10323 10324 llvm::SmallString<40> textToInsert; 10325 textToInsert += ' '; 10326 textToInsert += D.getIdentifier()->getName(); 10327 Diag(tagLoc, diag::note_typedef_changes_linkage) 10328 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10329 break; 10330 } 10331 10332 // Otherwise, set this is the anon-decl typedef for the tag. 10333 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10334 break; 10335 } 10336 10337 default: 10338 break; 10339 } 10340 10341 return NewTD; 10342 } 10343 10344 10345 /// \brief Check that this is a valid underlying type for an enum declaration. 10346 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10347 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10348 QualType T = TI->getType(); 10349 10350 if (T->isDependentType()) 10351 return false; 10352 10353 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10354 if (BT->isInteger()) 10355 return false; 10356 10357 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10358 return true; 10359 } 10360 10361 /// Check whether this is a valid redeclaration of a previous enumeration. 10362 /// \return true if the redeclaration was invalid. 10363 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10364 QualType EnumUnderlyingTy, 10365 const EnumDecl *Prev) { 10366 bool IsFixed = !EnumUnderlyingTy.isNull(); 10367 10368 if (IsScoped != Prev->isScoped()) { 10369 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10370 << Prev->isScoped(); 10371 Diag(Prev->getLocation(), diag::note_previous_declaration); 10372 return true; 10373 } 10374 10375 if (IsFixed && Prev->isFixed()) { 10376 if (!EnumUnderlyingTy->isDependentType() && 10377 !Prev->getIntegerType()->isDependentType() && 10378 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10379 Prev->getIntegerType())) { 10380 // TODO: Highlight the underlying type of the redeclaration. 10381 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10382 << EnumUnderlyingTy << Prev->getIntegerType(); 10383 Diag(Prev->getLocation(), diag::note_previous_declaration) 10384 << Prev->getIntegerTypeRange(); 10385 return true; 10386 } 10387 } else if (IsFixed != Prev->isFixed()) { 10388 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10389 << Prev->isFixed(); 10390 Diag(Prev->getLocation(), diag::note_previous_declaration); 10391 return true; 10392 } 10393 10394 return false; 10395 } 10396 10397 /// \brief Get diagnostic %select index for tag kind for 10398 /// redeclaration diagnostic message. 10399 /// WARNING: Indexes apply to particular diagnostics only! 10400 /// 10401 /// \returns diagnostic %select index. 10402 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10403 switch (Tag) { 10404 case TTK_Struct: return 0; 10405 case TTK_Interface: return 1; 10406 case TTK_Class: return 2; 10407 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10408 } 10409 } 10410 10411 /// \brief Determine if tag kind is a class-key compatible with 10412 /// class for redeclaration (class, struct, or __interface). 10413 /// 10414 /// \returns true iff the tag kind is compatible. 10415 static bool isClassCompatTagKind(TagTypeKind Tag) 10416 { 10417 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10418 } 10419 10420 /// \brief Determine whether a tag with a given kind is acceptable 10421 /// as a redeclaration of the given tag declaration. 10422 /// 10423 /// \returns true if the new tag kind is acceptable, false otherwise. 10424 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10425 TagTypeKind NewTag, bool isDefinition, 10426 SourceLocation NewTagLoc, 10427 const IdentifierInfo &Name) { 10428 // C++ [dcl.type.elab]p3: 10429 // The class-key or enum keyword present in the 10430 // elaborated-type-specifier shall agree in kind with the 10431 // declaration to which the name in the elaborated-type-specifier 10432 // refers. This rule also applies to the form of 10433 // elaborated-type-specifier that declares a class-name or 10434 // friend class since it can be construed as referring to the 10435 // definition of the class. Thus, in any 10436 // elaborated-type-specifier, the enum keyword shall be used to 10437 // refer to an enumeration (7.2), the union class-key shall be 10438 // used to refer to a union (clause 9), and either the class or 10439 // struct class-key shall be used to refer to a class (clause 9) 10440 // declared using the class or struct class-key. 10441 TagTypeKind OldTag = Previous->getTagKind(); 10442 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10443 if (OldTag == NewTag) 10444 return true; 10445 10446 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10447 // Warn about the struct/class tag mismatch. 10448 bool isTemplate = false; 10449 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10450 isTemplate = Record->getDescribedClassTemplate(); 10451 10452 if (!ActiveTemplateInstantiations.empty()) { 10453 // In a template instantiation, do not offer fix-its for tag mismatches 10454 // since they usually mess up the template instead of fixing the problem. 10455 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10456 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10457 << getRedeclDiagFromTagKind(OldTag); 10458 return true; 10459 } 10460 10461 if (isDefinition) { 10462 // On definitions, check previous tags and issue a fix-it for each 10463 // one that doesn't match the current tag. 10464 if (Previous->getDefinition()) { 10465 // Don't suggest fix-its for redefinitions. 10466 return true; 10467 } 10468 10469 bool previousMismatch = false; 10470 for (auto I : Previous->redecls()) { 10471 if (I->getTagKind() != NewTag) { 10472 if (!previousMismatch) { 10473 previousMismatch = true; 10474 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10475 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10476 << getRedeclDiagFromTagKind(I->getTagKind()); 10477 } 10478 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10479 << getRedeclDiagFromTagKind(NewTag) 10480 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10481 TypeWithKeyword::getTagTypeKindName(NewTag)); 10482 } 10483 } 10484 return true; 10485 } 10486 10487 // Check for a previous definition. If current tag and definition 10488 // are same type, do nothing. If no definition, but disagree with 10489 // with previous tag type, give a warning, but no fix-it. 10490 const TagDecl *Redecl = Previous->getDefinition() ? 10491 Previous->getDefinition() : Previous; 10492 if (Redecl->getTagKind() == NewTag) { 10493 return true; 10494 } 10495 10496 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10497 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10498 << getRedeclDiagFromTagKind(OldTag); 10499 Diag(Redecl->getLocation(), diag::note_previous_use); 10500 10501 // If there is a previous definition, suggest a fix-it. 10502 if (Previous->getDefinition()) { 10503 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10504 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10505 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10506 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10507 } 10508 10509 return true; 10510 } 10511 return false; 10512 } 10513 10514 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10515 /// former case, Name will be non-null. In the later case, Name will be null. 10516 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10517 /// reference/declaration/definition of a tag. 10518 /// 10519 /// IsTypeSpecifier is true if this is a type-specifier (or 10520 /// trailing-type-specifier) other than one in an alias-declaration. 10521 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10522 SourceLocation KWLoc, CXXScopeSpec &SS, 10523 IdentifierInfo *Name, SourceLocation NameLoc, 10524 AttributeList *Attr, AccessSpecifier AS, 10525 SourceLocation ModulePrivateLoc, 10526 MultiTemplateParamsArg TemplateParameterLists, 10527 bool &OwnedDecl, bool &IsDependent, 10528 SourceLocation ScopedEnumKWLoc, 10529 bool ScopedEnumUsesClassTag, 10530 TypeResult UnderlyingType, 10531 bool IsTypeSpecifier) { 10532 // If this is not a definition, it must have a name. 10533 IdentifierInfo *OrigName = Name; 10534 assert((Name != 0 || TUK == TUK_Definition) && 10535 "Nameless record must be a definition!"); 10536 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10537 10538 OwnedDecl = false; 10539 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10540 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10541 10542 // FIXME: Check explicit specializations more carefully. 10543 bool isExplicitSpecialization = false; 10544 bool Invalid = false; 10545 10546 // We only need to do this matching if we have template parameters 10547 // or a scope specifier, which also conveniently avoids this work 10548 // for non-C++ cases. 10549 if (TemplateParameterLists.size() > 0 || 10550 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10551 if (TemplateParameterList *TemplateParams = 10552 MatchTemplateParametersToScopeSpecifier( 10553 KWLoc, NameLoc, SS, 0, TemplateParameterLists, 10554 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 10555 if (Kind == TTK_Enum) { 10556 Diag(KWLoc, diag::err_enum_template); 10557 return 0; 10558 } 10559 10560 if (TemplateParams->size() > 0) { 10561 // This is a declaration or definition of a class template (which may 10562 // be a member of another template). 10563 10564 if (Invalid) 10565 return 0; 10566 10567 OwnedDecl = false; 10568 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10569 SS, Name, NameLoc, Attr, 10570 TemplateParams, AS, 10571 ModulePrivateLoc, 10572 TemplateParameterLists.size()-1, 10573 TemplateParameterLists.data()); 10574 return Result.get(); 10575 } else { 10576 // The "template<>" header is extraneous. 10577 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10578 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10579 isExplicitSpecialization = true; 10580 } 10581 } 10582 } 10583 10584 // Figure out the underlying type if this a enum declaration. We need to do 10585 // this early, because it's needed to detect if this is an incompatible 10586 // redeclaration. 10587 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10588 10589 if (Kind == TTK_Enum) { 10590 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10591 // No underlying type explicitly specified, or we failed to parse the 10592 // type, default to int. 10593 EnumUnderlying = Context.IntTy.getTypePtr(); 10594 else if (UnderlyingType.get()) { 10595 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10596 // integral type; any cv-qualification is ignored. 10597 TypeSourceInfo *TI = 0; 10598 GetTypeFromParser(UnderlyingType.get(), &TI); 10599 EnumUnderlying = TI; 10600 10601 if (CheckEnumUnderlyingType(TI)) 10602 // Recover by falling back to int. 10603 EnumUnderlying = Context.IntTy.getTypePtr(); 10604 10605 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10606 UPPC_FixedUnderlyingType)) 10607 EnumUnderlying = Context.IntTy.getTypePtr(); 10608 10609 } else if (getLangOpts().MSVCCompat) 10610 // Microsoft enums are always of int type. 10611 EnumUnderlying = Context.IntTy.getTypePtr(); 10612 } 10613 10614 DeclContext *SearchDC = CurContext; 10615 DeclContext *DC = CurContext; 10616 bool isStdBadAlloc = false; 10617 10618 RedeclarationKind Redecl = ForRedeclaration; 10619 if (TUK == TUK_Friend || TUK == TUK_Reference) 10620 Redecl = NotForRedeclaration; 10621 10622 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10623 bool FriendSawTagOutsideEnclosingNamespace = false; 10624 if (Name && SS.isNotEmpty()) { 10625 // We have a nested-name tag ('struct foo::bar'). 10626 10627 // Check for invalid 'foo::'. 10628 if (SS.isInvalid()) { 10629 Name = 0; 10630 goto CreateNewDecl; 10631 } 10632 10633 // If this is a friend or a reference to a class in a dependent 10634 // context, don't try to make a decl for it. 10635 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10636 DC = computeDeclContext(SS, false); 10637 if (!DC) { 10638 IsDependent = true; 10639 return 0; 10640 } 10641 } else { 10642 DC = computeDeclContext(SS, true); 10643 if (!DC) { 10644 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10645 << SS.getRange(); 10646 return 0; 10647 } 10648 } 10649 10650 if (RequireCompleteDeclContext(SS, DC)) 10651 return 0; 10652 10653 SearchDC = DC; 10654 // Look-up name inside 'foo::'. 10655 LookupQualifiedName(Previous, DC); 10656 10657 if (Previous.isAmbiguous()) 10658 return 0; 10659 10660 if (Previous.empty()) { 10661 // Name lookup did not find anything. However, if the 10662 // nested-name-specifier refers to the current instantiation, 10663 // and that current instantiation has any dependent base 10664 // classes, we might find something at instantiation time: treat 10665 // this as a dependent elaborated-type-specifier. 10666 // But this only makes any sense for reference-like lookups. 10667 if (Previous.wasNotFoundInCurrentInstantiation() && 10668 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10669 IsDependent = true; 10670 return 0; 10671 } 10672 10673 // A tag 'foo::bar' must already exist. 10674 Diag(NameLoc, diag::err_not_tag_in_scope) 10675 << Kind << Name << DC << SS.getRange(); 10676 Name = 0; 10677 Invalid = true; 10678 goto CreateNewDecl; 10679 } 10680 } else if (Name) { 10681 // If this is a named struct, check to see if there was a previous forward 10682 // declaration or definition. 10683 // FIXME: We're looking into outer scopes here, even when we 10684 // shouldn't be. Doing so can result in ambiguities that we 10685 // shouldn't be diagnosing. 10686 LookupName(Previous, S); 10687 10688 // When declaring or defining a tag, ignore ambiguities introduced 10689 // by types using'ed into this scope. 10690 if (Previous.isAmbiguous() && 10691 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10692 LookupResult::Filter F = Previous.makeFilter(); 10693 while (F.hasNext()) { 10694 NamedDecl *ND = F.next(); 10695 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10696 F.erase(); 10697 } 10698 F.done(); 10699 } 10700 10701 // C++11 [namespace.memdef]p3: 10702 // If the name in a friend declaration is neither qualified nor 10703 // a template-id and the declaration is a function or an 10704 // elaborated-type-specifier, the lookup to determine whether 10705 // the entity has been previously declared shall not consider 10706 // any scopes outside the innermost enclosing namespace. 10707 // 10708 // Does it matter that this should be by scope instead of by 10709 // semantic context? 10710 if (!Previous.empty() && TUK == TUK_Friend) { 10711 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10712 LookupResult::Filter F = Previous.makeFilter(); 10713 while (F.hasNext()) { 10714 NamedDecl *ND = F.next(); 10715 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10716 if (DC->isFileContext() && 10717 !EnclosingNS->Encloses(ND->getDeclContext())) { 10718 F.erase(); 10719 FriendSawTagOutsideEnclosingNamespace = true; 10720 } 10721 } 10722 F.done(); 10723 } 10724 10725 // Note: there used to be some attempt at recovery here. 10726 if (Previous.isAmbiguous()) 10727 return 0; 10728 10729 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10730 // FIXME: This makes sure that we ignore the contexts associated 10731 // with C structs, unions, and enums when looking for a matching 10732 // tag declaration or definition. See the similar lookup tweak 10733 // in Sema::LookupName; is there a better way to deal with this? 10734 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10735 SearchDC = SearchDC->getParent(); 10736 } 10737 } else if (S->isFunctionPrototypeScope()) { 10738 // If this is an enum declaration in function prototype scope, set its 10739 // initial context to the translation unit. 10740 // FIXME: [citation needed] 10741 SearchDC = Context.getTranslationUnitDecl(); 10742 } 10743 10744 if (Previous.isSingleResult() && 10745 Previous.getFoundDecl()->isTemplateParameter()) { 10746 // Maybe we will complain about the shadowed template parameter. 10747 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10748 // Just pretend that we didn't see the previous declaration. 10749 Previous.clear(); 10750 } 10751 10752 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10753 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10754 // This is a declaration of or a reference to "std::bad_alloc". 10755 isStdBadAlloc = true; 10756 10757 if (Previous.empty() && StdBadAlloc) { 10758 // std::bad_alloc has been implicitly declared (but made invisible to 10759 // name lookup). Fill in this implicit declaration as the previous 10760 // declaration, so that the declarations get chained appropriately. 10761 Previous.addDecl(getStdBadAlloc()); 10762 } 10763 } 10764 10765 // If we didn't find a previous declaration, and this is a reference 10766 // (or friend reference), move to the correct scope. In C++, we 10767 // also need to do a redeclaration lookup there, just in case 10768 // there's a shadow friend decl. 10769 if (Name && Previous.empty() && 10770 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10771 if (Invalid) goto CreateNewDecl; 10772 assert(SS.isEmpty()); 10773 10774 if (TUK == TUK_Reference) { 10775 // C++ [basic.scope.pdecl]p5: 10776 // -- for an elaborated-type-specifier of the form 10777 // 10778 // class-key identifier 10779 // 10780 // if the elaborated-type-specifier is used in the 10781 // decl-specifier-seq or parameter-declaration-clause of a 10782 // function defined in namespace scope, the identifier is 10783 // declared as a class-name in the namespace that contains 10784 // the declaration; otherwise, except as a friend 10785 // declaration, the identifier is declared in the smallest 10786 // non-class, non-function-prototype scope that contains the 10787 // declaration. 10788 // 10789 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10790 // C structs and unions. 10791 // 10792 // It is an error in C++ to declare (rather than define) an enum 10793 // type, including via an elaborated type specifier. We'll 10794 // diagnose that later; for now, declare the enum in the same 10795 // scope as we would have picked for any other tag type. 10796 // 10797 // GNU C also supports this behavior as part of its incomplete 10798 // enum types extension, while GNU C++ does not. 10799 // 10800 // Find the context where we'll be declaring the tag. 10801 // FIXME: We would like to maintain the current DeclContext as the 10802 // lexical context, 10803 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10804 SearchDC = SearchDC->getParent(); 10805 10806 // Find the scope where we'll be declaring the tag. 10807 while (S->isClassScope() || 10808 (getLangOpts().CPlusPlus && 10809 S->isFunctionPrototypeScope()) || 10810 ((S->getFlags() & Scope::DeclScope) == 0) || 10811 (S->getEntity() && S->getEntity()->isTransparentContext())) 10812 S = S->getParent(); 10813 } else { 10814 assert(TUK == TUK_Friend); 10815 // C++ [namespace.memdef]p3: 10816 // If a friend declaration in a non-local class first declares a 10817 // class or function, the friend class or function is a member of 10818 // the innermost enclosing namespace. 10819 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10820 } 10821 10822 // In C++, we need to do a redeclaration lookup to properly 10823 // diagnose some problems. 10824 if (getLangOpts().CPlusPlus) { 10825 Previous.setRedeclarationKind(ForRedeclaration); 10826 LookupQualifiedName(Previous, SearchDC); 10827 } 10828 } 10829 10830 if (!Previous.empty()) { 10831 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10832 NamedDecl *DirectPrevDecl = 10833 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10834 10835 // It's okay to have a tag decl in the same scope as a typedef 10836 // which hides a tag decl in the same scope. Finding this 10837 // insanity with a redeclaration lookup can only actually happen 10838 // in C++. 10839 // 10840 // This is also okay for elaborated-type-specifiers, which is 10841 // technically forbidden by the current standard but which is 10842 // okay according to the likely resolution of an open issue; 10843 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10844 if (getLangOpts().CPlusPlus) { 10845 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10846 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10847 TagDecl *Tag = TT->getDecl(); 10848 if (Tag->getDeclName() == Name && 10849 Tag->getDeclContext()->getRedeclContext() 10850 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10851 PrevDecl = Tag; 10852 Previous.clear(); 10853 Previous.addDecl(Tag); 10854 Previous.resolveKind(); 10855 } 10856 } 10857 } 10858 } 10859 10860 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10861 // If this is a use of a previous tag, or if the tag is already declared 10862 // in the same scope (so that the definition/declaration completes or 10863 // rementions the tag), reuse the decl. 10864 if (TUK == TUK_Reference || TUK == TUK_Friend || 10865 isDeclInScope(DirectPrevDecl, SearchDC, S, 10866 SS.isNotEmpty() || isExplicitSpecialization)) { 10867 // Make sure that this wasn't declared as an enum and now used as a 10868 // struct or something similar. 10869 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10870 TUK == TUK_Definition, KWLoc, 10871 *Name)) { 10872 bool SafeToContinue 10873 = (PrevTagDecl->getTagKind() != TTK_Enum && 10874 Kind != TTK_Enum); 10875 if (SafeToContinue) 10876 Diag(KWLoc, diag::err_use_with_wrong_tag) 10877 << Name 10878 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10879 PrevTagDecl->getKindName()); 10880 else 10881 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10882 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10883 10884 if (SafeToContinue) 10885 Kind = PrevTagDecl->getTagKind(); 10886 else { 10887 // Recover by making this an anonymous redefinition. 10888 Name = 0; 10889 Previous.clear(); 10890 Invalid = true; 10891 } 10892 } 10893 10894 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10895 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10896 10897 // If this is an elaborated-type-specifier for a scoped enumeration, 10898 // the 'class' keyword is not necessary and not permitted. 10899 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10900 if (ScopedEnum) 10901 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10902 << PrevEnum->isScoped() 10903 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10904 return PrevTagDecl; 10905 } 10906 10907 QualType EnumUnderlyingTy; 10908 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10909 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10910 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10911 EnumUnderlyingTy = QualType(T, 0); 10912 10913 // All conflicts with previous declarations are recovered by 10914 // returning the previous declaration, unless this is a definition, 10915 // in which case we want the caller to bail out. 10916 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 10917 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 10918 return TUK == TUK_Declaration ? PrevTagDecl : 0; 10919 } 10920 10921 // C++11 [class.mem]p1: 10922 // A member shall not be declared twice in the member-specification, 10923 // except that a nested class or member class template can be declared 10924 // and then later defined. 10925 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 10926 S->isDeclScope(PrevDecl)) { 10927 Diag(NameLoc, diag::ext_member_redeclared); 10928 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 10929 } 10930 10931 if (!Invalid) { 10932 // If this is a use, just return the declaration we found. 10933 10934 // FIXME: In the future, return a variant or some other clue 10935 // for the consumer of this Decl to know it doesn't own it. 10936 // For our current ASTs this shouldn't be a problem, but will 10937 // need to be changed with DeclGroups. 10938 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 10939 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 10940 return PrevTagDecl; 10941 10942 // Diagnose attempts to redefine a tag. 10943 if (TUK == TUK_Definition) { 10944 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 10945 // If we're defining a specialization and the previous definition 10946 // is from an implicit instantiation, don't emit an error 10947 // here; we'll catch this in the general case below. 10948 bool IsExplicitSpecializationAfterInstantiation = false; 10949 if (isExplicitSpecialization) { 10950 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 10951 IsExplicitSpecializationAfterInstantiation = 10952 RD->getTemplateSpecializationKind() != 10953 TSK_ExplicitSpecialization; 10954 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 10955 IsExplicitSpecializationAfterInstantiation = 10956 ED->getTemplateSpecializationKind() != 10957 TSK_ExplicitSpecialization; 10958 } 10959 10960 if (!IsExplicitSpecializationAfterInstantiation) { 10961 // A redeclaration in function prototype scope in C isn't 10962 // visible elsewhere, so merely issue a warning. 10963 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 10964 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 10965 else 10966 Diag(NameLoc, diag::err_redefinition) << Name; 10967 Diag(Def->getLocation(), diag::note_previous_definition); 10968 // If this is a redefinition, recover by making this 10969 // struct be anonymous, which will make any later 10970 // references get the previous definition. 10971 Name = 0; 10972 Previous.clear(); 10973 Invalid = true; 10974 } 10975 } else { 10976 // If the type is currently being defined, complain 10977 // about a nested redefinition. 10978 const TagType *Tag 10979 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 10980 if (Tag->isBeingDefined()) { 10981 Diag(NameLoc, diag::err_nested_redefinition) << Name; 10982 Diag(PrevTagDecl->getLocation(), 10983 diag::note_previous_definition); 10984 Name = 0; 10985 Previous.clear(); 10986 Invalid = true; 10987 } 10988 } 10989 10990 // Okay, this is definition of a previously declared or referenced 10991 // tag PrevDecl. We're going to create a new Decl for it. 10992 } 10993 } 10994 // If we get here we have (another) forward declaration or we 10995 // have a definition. Just create a new decl. 10996 10997 } else { 10998 // If we get here, this is a definition of a new tag type in a nested 10999 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11000 // new decl/type. We set PrevDecl to NULL so that the entities 11001 // have distinct types. 11002 Previous.clear(); 11003 } 11004 // If we get here, we're going to create a new Decl. If PrevDecl 11005 // is non-NULL, it's a definition of the tag declared by 11006 // PrevDecl. If it's NULL, we have a new definition. 11007 11008 11009 // Otherwise, PrevDecl is not a tag, but was found with tag 11010 // lookup. This is only actually possible in C++, where a few 11011 // things like templates still live in the tag namespace. 11012 } else { 11013 // Use a better diagnostic if an elaborated-type-specifier 11014 // found the wrong kind of type on the first 11015 // (non-redeclaration) lookup. 11016 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11017 !Previous.isForRedeclaration()) { 11018 unsigned Kind = 0; 11019 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11020 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11021 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11022 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11023 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11024 Invalid = true; 11025 11026 // Otherwise, only diagnose if the declaration is in scope. 11027 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11028 SS.isNotEmpty() || isExplicitSpecialization)) { 11029 // do nothing 11030 11031 // Diagnose implicit declarations introduced by elaborated types. 11032 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11033 unsigned Kind = 0; 11034 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11035 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11036 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11037 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11038 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11039 Invalid = true; 11040 11041 // Otherwise it's a declaration. Call out a particularly common 11042 // case here. 11043 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11044 unsigned Kind = 0; 11045 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11046 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11047 << Name << Kind << TND->getUnderlyingType(); 11048 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11049 Invalid = true; 11050 11051 // Otherwise, diagnose. 11052 } else { 11053 // The tag name clashes with something else in the target scope, 11054 // issue an error and recover by making this tag be anonymous. 11055 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11056 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11057 Name = 0; 11058 Invalid = true; 11059 } 11060 11061 // The existing declaration isn't relevant to us; we're in a 11062 // new scope, so clear out the previous declaration. 11063 Previous.clear(); 11064 } 11065 } 11066 11067 CreateNewDecl: 11068 11069 TagDecl *PrevDecl = 0; 11070 if (Previous.isSingleResult()) 11071 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11072 11073 // If there is an identifier, use the location of the identifier as the 11074 // location of the decl, otherwise use the location of the struct/union 11075 // keyword. 11076 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11077 11078 // Otherwise, create a new declaration. If there is a previous 11079 // declaration of the same entity, the two will be linked via 11080 // PrevDecl. 11081 TagDecl *New; 11082 11083 bool IsForwardReference = false; 11084 if (Kind == TTK_Enum) { 11085 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11086 // enum X { A, B, C } D; D should chain to X. 11087 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11088 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11089 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11090 // If this is an undefined enum, warn. 11091 if (TUK != TUK_Definition && !Invalid) { 11092 TagDecl *Def; 11093 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11094 cast<EnumDecl>(New)->isFixed()) { 11095 // C++0x: 7.2p2: opaque-enum-declaration. 11096 // Conflicts are diagnosed above. Do nothing. 11097 } 11098 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11099 Diag(Loc, diag::ext_forward_ref_enum_def) 11100 << New; 11101 Diag(Def->getLocation(), diag::note_previous_definition); 11102 } else { 11103 unsigned DiagID = diag::ext_forward_ref_enum; 11104 if (getLangOpts().MSVCCompat) 11105 DiagID = diag::ext_ms_forward_ref_enum; 11106 else if (getLangOpts().CPlusPlus) 11107 DiagID = diag::err_forward_ref_enum; 11108 Diag(Loc, DiagID); 11109 11110 // If this is a forward-declared reference to an enumeration, make a 11111 // note of it; we won't actually be introducing the declaration into 11112 // the declaration context. 11113 if (TUK == TUK_Reference) 11114 IsForwardReference = true; 11115 } 11116 } 11117 11118 if (EnumUnderlying) { 11119 EnumDecl *ED = cast<EnumDecl>(New); 11120 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11121 ED->setIntegerTypeSourceInfo(TI); 11122 else 11123 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11124 ED->setPromotionType(ED->getIntegerType()); 11125 } 11126 11127 } else { 11128 // struct/union/class 11129 11130 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11131 // struct X { int A; } D; D should chain to X. 11132 if (getLangOpts().CPlusPlus) { 11133 // FIXME: Look for a way to use RecordDecl for simple structs. 11134 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11135 cast_or_null<CXXRecordDecl>(PrevDecl)); 11136 11137 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11138 StdBadAlloc = cast<CXXRecordDecl>(New); 11139 } else 11140 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11141 cast_or_null<RecordDecl>(PrevDecl)); 11142 } 11143 11144 // C++11 [dcl.type]p3: 11145 // A type-specifier-seq shall not define a class or enumeration [...]. 11146 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11147 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11148 << Context.getTagDeclType(New); 11149 Invalid = true; 11150 } 11151 11152 // Maybe add qualifier info. 11153 if (SS.isNotEmpty()) { 11154 if (SS.isSet()) { 11155 // If this is either a declaration or a definition, check the 11156 // nested-name-specifier against the current context. We don't do this 11157 // for explicit specializations, because they have similar checking 11158 // (with more specific diagnostics) in the call to 11159 // CheckMemberSpecialization, below. 11160 if (!isExplicitSpecialization && 11161 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11162 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11163 Invalid = true; 11164 11165 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11166 if (TemplateParameterLists.size() > 0) { 11167 New->setTemplateParameterListsInfo(Context, 11168 TemplateParameterLists.size(), 11169 TemplateParameterLists.data()); 11170 } 11171 } 11172 else 11173 Invalid = true; 11174 } 11175 11176 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11177 // Add alignment attributes if necessary; these attributes are checked when 11178 // the ASTContext lays out the structure. 11179 // 11180 // It is important for implementing the correct semantics that this 11181 // happen here (in act on tag decl). The #pragma pack stack is 11182 // maintained as a result of parser callbacks which can occur at 11183 // many points during the parsing of a struct declaration (because 11184 // the #pragma tokens are effectively skipped over during the 11185 // parsing of the struct). 11186 if (TUK == TUK_Definition) { 11187 AddAlignmentAttributesForRecord(RD); 11188 AddMsStructLayoutForRecord(RD); 11189 } 11190 } 11191 11192 if (ModulePrivateLoc.isValid()) { 11193 if (isExplicitSpecialization) 11194 Diag(New->getLocation(), diag::err_module_private_specialization) 11195 << 2 11196 << FixItHint::CreateRemoval(ModulePrivateLoc); 11197 // __module_private__ does not apply to local classes. However, we only 11198 // diagnose this as an error when the declaration specifiers are 11199 // freestanding. Here, we just ignore the __module_private__. 11200 else if (!SearchDC->isFunctionOrMethod()) 11201 New->setModulePrivate(); 11202 } 11203 11204 // If this is a specialization of a member class (of a class template), 11205 // check the specialization. 11206 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11207 Invalid = true; 11208 11209 if (Invalid) 11210 New->setInvalidDecl(); 11211 11212 if (Attr) 11213 ProcessDeclAttributeList(S, New, Attr); 11214 11215 // If we're declaring or defining a tag in function prototype scope in C, 11216 // note that this type can only be used within the function and add it to 11217 // the list of decls to inject into the function definition scope. 11218 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) && 11219 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11220 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11221 DeclsInPrototypeScope.push_back(New); 11222 } 11223 11224 // Set the lexical context. If the tag has a C++ scope specifier, the 11225 // lexical context will be different from the semantic context. 11226 New->setLexicalDeclContext(CurContext); 11227 11228 // Mark this as a friend decl if applicable. 11229 // In Microsoft mode, a friend declaration also acts as a forward 11230 // declaration so we always pass true to setObjectOfFriendDecl to make 11231 // the tag name visible. 11232 if (TUK == TUK_Friend) 11233 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11234 getLangOpts().MicrosoftExt); 11235 11236 // Set the access specifier. 11237 if (!Invalid && SearchDC->isRecord()) 11238 SetMemberAccessSpecifier(New, PrevDecl, AS); 11239 11240 if (TUK == TUK_Definition) 11241 New->startDefinition(); 11242 11243 // If this has an identifier, add it to the scope stack. 11244 if (TUK == TUK_Friend) { 11245 // We might be replacing an existing declaration in the lookup tables; 11246 // if so, borrow its access specifier. 11247 if (PrevDecl) 11248 New->setAccess(PrevDecl->getAccess()); 11249 11250 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11251 DC->makeDeclVisibleInContext(New); 11252 if (Name) // can be null along some error paths 11253 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11254 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11255 } else if (Name) { 11256 S = getNonFieldDeclScope(S); 11257 PushOnScopeChains(New, S, !IsForwardReference); 11258 if (IsForwardReference) 11259 SearchDC->makeDeclVisibleInContext(New); 11260 11261 } else { 11262 CurContext->addDecl(New); 11263 } 11264 11265 // If this is the C FILE type, notify the AST context. 11266 if (IdentifierInfo *II = New->getIdentifier()) 11267 if (!New->isInvalidDecl() && 11268 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11269 II->isStr("FILE")) 11270 Context.setFILEDecl(New); 11271 11272 if (PrevDecl) 11273 mergeDeclAttributes(New, PrevDecl); 11274 11275 // If there's a #pragma GCC visibility in scope, set the visibility of this 11276 // record. 11277 AddPushedVisibilityAttribute(New); 11278 11279 OwnedDecl = true; 11280 // In C++, don't return an invalid declaration. We can't recover well from 11281 // the cases where we make the type anonymous. 11282 return (Invalid && getLangOpts().CPlusPlus) ? 0 : New; 11283 } 11284 11285 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11286 AdjustDeclIfTemplate(TagD); 11287 TagDecl *Tag = cast<TagDecl>(TagD); 11288 11289 // Enter the tag context. 11290 PushDeclContext(S, Tag); 11291 11292 ActOnDocumentableDecl(TagD); 11293 11294 // If there's a #pragma GCC visibility in scope, set the visibility of this 11295 // record. 11296 AddPushedVisibilityAttribute(Tag); 11297 } 11298 11299 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11300 assert(isa<ObjCContainerDecl>(IDecl) && 11301 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11302 DeclContext *OCD = cast<DeclContext>(IDecl); 11303 assert(getContainingDC(OCD) == CurContext && 11304 "The next DeclContext should be lexically contained in the current one."); 11305 CurContext = OCD; 11306 return IDecl; 11307 } 11308 11309 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11310 SourceLocation FinalLoc, 11311 bool IsFinalSpelledSealed, 11312 SourceLocation LBraceLoc) { 11313 AdjustDeclIfTemplate(TagD); 11314 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11315 11316 FieldCollector->StartClass(); 11317 11318 if (!Record->getIdentifier()) 11319 return; 11320 11321 if (FinalLoc.isValid()) 11322 Record->addAttr(new (Context) 11323 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11324 11325 // C++ [class]p2: 11326 // [...] The class-name is also inserted into the scope of the 11327 // class itself; this is known as the injected-class-name. For 11328 // purposes of access checking, the injected-class-name is treated 11329 // as if it were a public member name. 11330 CXXRecordDecl *InjectedClassName 11331 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11332 Record->getLocStart(), Record->getLocation(), 11333 Record->getIdentifier(), 11334 /*PrevDecl=*/0, 11335 /*DelayTypeCreation=*/true); 11336 Context.getTypeDeclType(InjectedClassName, Record); 11337 InjectedClassName->setImplicit(); 11338 InjectedClassName->setAccess(AS_public); 11339 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11340 InjectedClassName->setDescribedClassTemplate(Template); 11341 PushOnScopeChains(InjectedClassName, S); 11342 assert(InjectedClassName->isInjectedClassName() && 11343 "Broken injected-class-name"); 11344 } 11345 11346 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11347 SourceLocation RBraceLoc) { 11348 AdjustDeclIfTemplate(TagD); 11349 TagDecl *Tag = cast<TagDecl>(TagD); 11350 Tag->setRBraceLoc(RBraceLoc); 11351 11352 // Make sure we "complete" the definition even it is invalid. 11353 if (Tag->isBeingDefined()) { 11354 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11355 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11356 RD->completeDefinition(); 11357 } 11358 11359 if (isa<CXXRecordDecl>(Tag)) 11360 FieldCollector->FinishClass(); 11361 11362 // Exit this scope of this tag's definition. 11363 PopDeclContext(); 11364 11365 if (getCurLexicalContext()->isObjCContainer() && 11366 Tag->getDeclContext()->isFileContext()) 11367 Tag->setTopLevelDeclInObjCContainer(); 11368 11369 // Notify the consumer that we've defined a tag. 11370 if (!Tag->isInvalidDecl()) 11371 Consumer.HandleTagDeclDefinition(Tag); 11372 } 11373 11374 void Sema::ActOnObjCContainerFinishDefinition() { 11375 // Exit this scope of this interface definition. 11376 PopDeclContext(); 11377 } 11378 11379 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11380 assert(DC == CurContext && "Mismatch of container contexts"); 11381 OriginalLexicalContext = DC; 11382 ActOnObjCContainerFinishDefinition(); 11383 } 11384 11385 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11386 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11387 OriginalLexicalContext = 0; 11388 } 11389 11390 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11391 AdjustDeclIfTemplate(TagD); 11392 TagDecl *Tag = cast<TagDecl>(TagD); 11393 Tag->setInvalidDecl(); 11394 11395 // Make sure we "complete" the definition even it is invalid. 11396 if (Tag->isBeingDefined()) { 11397 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11398 RD->completeDefinition(); 11399 } 11400 11401 // We're undoing ActOnTagStartDefinition here, not 11402 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11403 // the FieldCollector. 11404 11405 PopDeclContext(); 11406 } 11407 11408 // Note that FieldName may be null for anonymous bitfields. 11409 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11410 IdentifierInfo *FieldName, 11411 QualType FieldTy, bool IsMsStruct, 11412 Expr *BitWidth, bool *ZeroWidth) { 11413 // Default to true; that shouldn't confuse checks for emptiness 11414 if (ZeroWidth) 11415 *ZeroWidth = true; 11416 11417 // C99 6.7.2.1p4 - verify the field type. 11418 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11419 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11420 // Handle incomplete types with specific error. 11421 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11422 return ExprError(); 11423 if (FieldName) 11424 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11425 << FieldName << FieldTy << BitWidth->getSourceRange(); 11426 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11427 << FieldTy << BitWidth->getSourceRange(); 11428 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11429 UPPC_BitFieldWidth)) 11430 return ExprError(); 11431 11432 // If the bit-width is type- or value-dependent, don't try to check 11433 // it now. 11434 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11435 return Owned(BitWidth); 11436 11437 llvm::APSInt Value; 11438 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11439 if (ICE.isInvalid()) 11440 return ICE; 11441 BitWidth = ICE.take(); 11442 11443 if (Value != 0 && ZeroWidth) 11444 *ZeroWidth = false; 11445 11446 // Zero-width bitfield is ok for anonymous field. 11447 if (Value == 0 && FieldName) 11448 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11449 11450 if (Value.isSigned() && Value.isNegative()) { 11451 if (FieldName) 11452 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11453 << FieldName << Value.toString(10); 11454 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11455 << Value.toString(10); 11456 } 11457 11458 if (!FieldTy->isDependentType()) { 11459 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11460 if (Value.getZExtValue() > TypeSize) { 11461 if (!getLangOpts().CPlusPlus || IsMsStruct || 11462 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11463 if (FieldName) 11464 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11465 << FieldName << (unsigned)Value.getZExtValue() 11466 << (unsigned)TypeSize; 11467 11468 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11469 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11470 } 11471 11472 if (FieldName) 11473 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11474 << FieldName << (unsigned)Value.getZExtValue() 11475 << (unsigned)TypeSize; 11476 else 11477 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11478 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11479 } 11480 } 11481 11482 return Owned(BitWidth); 11483 } 11484 11485 /// ActOnField - Each field of a C struct/union is passed into this in order 11486 /// to create a FieldDecl object for it. 11487 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11488 Declarator &D, Expr *BitfieldWidth) { 11489 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11490 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11491 /*InitStyle=*/ICIS_NoInit, AS_public); 11492 return Res; 11493 } 11494 11495 /// HandleField - Analyze a field of a C struct or a C++ data member. 11496 /// 11497 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11498 SourceLocation DeclStart, 11499 Declarator &D, Expr *BitWidth, 11500 InClassInitStyle InitStyle, 11501 AccessSpecifier AS) { 11502 IdentifierInfo *II = D.getIdentifier(); 11503 SourceLocation Loc = DeclStart; 11504 if (II) Loc = D.getIdentifierLoc(); 11505 11506 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11507 QualType T = TInfo->getType(); 11508 if (getLangOpts().CPlusPlus) { 11509 CheckExtraCXXDefaultArguments(D); 11510 11511 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11512 UPPC_DataMemberType)) { 11513 D.setInvalidType(); 11514 T = Context.IntTy; 11515 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11516 } 11517 } 11518 11519 // TR 18037 does not allow fields to be declared with address spaces. 11520 if (T.getQualifiers().hasAddressSpace()) { 11521 Diag(Loc, diag::err_field_with_address_space); 11522 D.setInvalidType(); 11523 } 11524 11525 // OpenCL 1.2 spec, s6.9 r: 11526 // The event type cannot be used to declare a structure or union field. 11527 if (LangOpts.OpenCL && T->isEventT()) { 11528 Diag(Loc, diag::err_event_t_struct_field); 11529 D.setInvalidType(); 11530 } 11531 11532 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11533 11534 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11535 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11536 diag::err_invalid_thread) 11537 << DeclSpec::getSpecifierName(TSCS); 11538 11539 // Check to see if this name was declared as a member previously 11540 NamedDecl *PrevDecl = 0; 11541 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11542 LookupName(Previous, S); 11543 switch (Previous.getResultKind()) { 11544 case LookupResult::Found: 11545 case LookupResult::FoundUnresolvedValue: 11546 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11547 break; 11548 11549 case LookupResult::FoundOverloaded: 11550 PrevDecl = Previous.getRepresentativeDecl(); 11551 break; 11552 11553 case LookupResult::NotFound: 11554 case LookupResult::NotFoundInCurrentInstantiation: 11555 case LookupResult::Ambiguous: 11556 break; 11557 } 11558 Previous.suppressDiagnostics(); 11559 11560 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11561 // Maybe we will complain about the shadowed template parameter. 11562 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11563 // Just pretend that we didn't see the previous declaration. 11564 PrevDecl = 0; 11565 } 11566 11567 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11568 PrevDecl = 0; 11569 11570 bool Mutable 11571 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11572 SourceLocation TSSL = D.getLocStart(); 11573 FieldDecl *NewFD 11574 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11575 TSSL, AS, PrevDecl, &D); 11576 11577 if (NewFD->isInvalidDecl()) 11578 Record->setInvalidDecl(); 11579 11580 if (D.getDeclSpec().isModulePrivateSpecified()) 11581 NewFD->setModulePrivate(); 11582 11583 if (NewFD->isInvalidDecl() && PrevDecl) { 11584 // Don't introduce NewFD into scope; there's already something 11585 // with the same name in the same scope. 11586 } else if (II) { 11587 PushOnScopeChains(NewFD, S); 11588 } else 11589 Record->addDecl(NewFD); 11590 11591 return NewFD; 11592 } 11593 11594 /// \brief Build a new FieldDecl and check its well-formedness. 11595 /// 11596 /// This routine builds a new FieldDecl given the fields name, type, 11597 /// record, etc. \p PrevDecl should refer to any previous declaration 11598 /// with the same name and in the same scope as the field to be 11599 /// created. 11600 /// 11601 /// \returns a new FieldDecl. 11602 /// 11603 /// \todo The Declarator argument is a hack. It will be removed once 11604 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11605 TypeSourceInfo *TInfo, 11606 RecordDecl *Record, SourceLocation Loc, 11607 bool Mutable, Expr *BitWidth, 11608 InClassInitStyle InitStyle, 11609 SourceLocation TSSL, 11610 AccessSpecifier AS, NamedDecl *PrevDecl, 11611 Declarator *D) { 11612 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11613 bool InvalidDecl = false; 11614 if (D) InvalidDecl = D->isInvalidType(); 11615 11616 // If we receive a broken type, recover by assuming 'int' and 11617 // marking this declaration as invalid. 11618 if (T.isNull()) { 11619 InvalidDecl = true; 11620 T = Context.IntTy; 11621 } 11622 11623 QualType EltTy = Context.getBaseElementType(T); 11624 if (!EltTy->isDependentType()) { 11625 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11626 // Fields of incomplete type force their record to be invalid. 11627 Record->setInvalidDecl(); 11628 InvalidDecl = true; 11629 } else { 11630 NamedDecl *Def; 11631 EltTy->isIncompleteType(&Def); 11632 if (Def && Def->isInvalidDecl()) { 11633 Record->setInvalidDecl(); 11634 InvalidDecl = true; 11635 } 11636 } 11637 } 11638 11639 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11640 if (BitWidth && getLangOpts().OpenCL) { 11641 Diag(Loc, diag::err_opencl_bitfields); 11642 InvalidDecl = true; 11643 } 11644 11645 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11646 // than a variably modified type. 11647 if (!InvalidDecl && T->isVariablyModifiedType()) { 11648 bool SizeIsNegative; 11649 llvm::APSInt Oversized; 11650 11651 TypeSourceInfo *FixedTInfo = 11652 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11653 SizeIsNegative, 11654 Oversized); 11655 if (FixedTInfo) { 11656 Diag(Loc, diag::warn_illegal_constant_array_size); 11657 TInfo = FixedTInfo; 11658 T = FixedTInfo->getType(); 11659 } else { 11660 if (SizeIsNegative) 11661 Diag(Loc, diag::err_typecheck_negative_array_size); 11662 else if (Oversized.getBoolValue()) 11663 Diag(Loc, diag::err_array_too_large) 11664 << Oversized.toString(10); 11665 else 11666 Diag(Loc, diag::err_typecheck_field_variable_size); 11667 InvalidDecl = true; 11668 } 11669 } 11670 11671 // Fields can not have abstract class types 11672 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11673 diag::err_abstract_type_in_decl, 11674 AbstractFieldType)) 11675 InvalidDecl = true; 11676 11677 bool ZeroWidth = false; 11678 // If this is declared as a bit-field, check the bit-field. 11679 if (!InvalidDecl && BitWidth) { 11680 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11681 &ZeroWidth).take(); 11682 if (!BitWidth) { 11683 InvalidDecl = true; 11684 BitWidth = 0; 11685 ZeroWidth = false; 11686 } 11687 } 11688 11689 // Check that 'mutable' is consistent with the type of the declaration. 11690 if (!InvalidDecl && Mutable) { 11691 unsigned DiagID = 0; 11692 if (T->isReferenceType()) 11693 DiagID = diag::err_mutable_reference; 11694 else if (T.isConstQualified()) 11695 DiagID = diag::err_mutable_const; 11696 11697 if (DiagID) { 11698 SourceLocation ErrLoc = Loc; 11699 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11700 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11701 Diag(ErrLoc, DiagID); 11702 Mutable = false; 11703 InvalidDecl = true; 11704 } 11705 } 11706 11707 // C++11 [class.union]p8 (DR1460): 11708 // At most one variant member of a union may have a 11709 // brace-or-equal-initializer. 11710 if (InitStyle != ICIS_NoInit) 11711 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11712 11713 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11714 BitWidth, Mutable, InitStyle); 11715 if (InvalidDecl) 11716 NewFD->setInvalidDecl(); 11717 11718 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11719 Diag(Loc, diag::err_duplicate_member) << II; 11720 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11721 NewFD->setInvalidDecl(); 11722 } 11723 11724 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11725 if (Record->isUnion()) { 11726 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11727 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11728 if (RDecl->getDefinition()) { 11729 // C++ [class.union]p1: An object of a class with a non-trivial 11730 // constructor, a non-trivial copy constructor, a non-trivial 11731 // destructor, or a non-trivial copy assignment operator 11732 // cannot be a member of a union, nor can an array of such 11733 // objects. 11734 if (CheckNontrivialField(NewFD)) 11735 NewFD->setInvalidDecl(); 11736 } 11737 } 11738 11739 // C++ [class.union]p1: If a union contains a member of reference type, 11740 // the program is ill-formed, except when compiling with MSVC extensions 11741 // enabled. 11742 if (EltTy->isReferenceType()) { 11743 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11744 diag::ext_union_member_of_reference_type : 11745 diag::err_union_member_of_reference_type) 11746 << NewFD->getDeclName() << EltTy; 11747 if (!getLangOpts().MicrosoftExt) 11748 NewFD->setInvalidDecl(); 11749 } 11750 } 11751 } 11752 11753 // FIXME: We need to pass in the attributes given an AST 11754 // representation, not a parser representation. 11755 if (D) { 11756 // FIXME: The current scope is almost... but not entirely... correct here. 11757 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11758 11759 if (NewFD->hasAttrs()) 11760 CheckAlignasUnderalignment(NewFD); 11761 } 11762 11763 // In auto-retain/release, infer strong retension for fields of 11764 // retainable type. 11765 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11766 NewFD->setInvalidDecl(); 11767 11768 if (T.isObjCGCWeak()) 11769 Diag(Loc, diag::warn_attribute_weak_on_field); 11770 11771 NewFD->setAccess(AS); 11772 return NewFD; 11773 } 11774 11775 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11776 assert(FD); 11777 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11778 11779 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11780 return false; 11781 11782 QualType EltTy = Context.getBaseElementType(FD->getType()); 11783 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11784 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11785 if (RDecl->getDefinition()) { 11786 // We check for copy constructors before constructors 11787 // because otherwise we'll never get complaints about 11788 // copy constructors. 11789 11790 CXXSpecialMember member = CXXInvalid; 11791 // We're required to check for any non-trivial constructors. Since the 11792 // implicit default constructor is suppressed if there are any 11793 // user-declared constructors, we just need to check that there is a 11794 // trivial default constructor and a trivial copy constructor. (We don't 11795 // worry about move constructors here, since this is a C++98 check.) 11796 if (RDecl->hasNonTrivialCopyConstructor()) 11797 member = CXXCopyConstructor; 11798 else if (!RDecl->hasTrivialDefaultConstructor()) 11799 member = CXXDefaultConstructor; 11800 else if (RDecl->hasNonTrivialCopyAssignment()) 11801 member = CXXCopyAssignment; 11802 else if (RDecl->hasNonTrivialDestructor()) 11803 member = CXXDestructor; 11804 11805 if (member != CXXInvalid) { 11806 if (!getLangOpts().CPlusPlus11 && 11807 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11808 // Objective-C++ ARC: it is an error to have a non-trivial field of 11809 // a union. However, system headers in Objective-C programs 11810 // occasionally have Objective-C lifetime objects within unions, 11811 // and rather than cause the program to fail, we make those 11812 // members unavailable. 11813 SourceLocation Loc = FD->getLocation(); 11814 if (getSourceManager().isInSystemHeader(Loc)) { 11815 if (!FD->hasAttr<UnavailableAttr>()) 11816 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11817 "this system field has retaining ownership", 11818 Loc)); 11819 return false; 11820 } 11821 } 11822 11823 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11824 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11825 diag::err_illegal_union_or_anon_struct_member) 11826 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11827 DiagnoseNontrivial(RDecl, member); 11828 return !getLangOpts().CPlusPlus11; 11829 } 11830 } 11831 } 11832 11833 return false; 11834 } 11835 11836 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11837 /// AST enum value. 11838 static ObjCIvarDecl::AccessControl 11839 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11840 switch (ivarVisibility) { 11841 default: llvm_unreachable("Unknown visitibility kind"); 11842 case tok::objc_private: return ObjCIvarDecl::Private; 11843 case tok::objc_public: return ObjCIvarDecl::Public; 11844 case tok::objc_protected: return ObjCIvarDecl::Protected; 11845 case tok::objc_package: return ObjCIvarDecl::Package; 11846 } 11847 } 11848 11849 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11850 /// in order to create an IvarDecl object for it. 11851 Decl *Sema::ActOnIvar(Scope *S, 11852 SourceLocation DeclStart, 11853 Declarator &D, Expr *BitfieldWidth, 11854 tok::ObjCKeywordKind Visibility) { 11855 11856 IdentifierInfo *II = D.getIdentifier(); 11857 Expr *BitWidth = (Expr*)BitfieldWidth; 11858 SourceLocation Loc = DeclStart; 11859 if (II) Loc = D.getIdentifierLoc(); 11860 11861 // FIXME: Unnamed fields can be handled in various different ways, for 11862 // example, unnamed unions inject all members into the struct namespace! 11863 11864 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11865 QualType T = TInfo->getType(); 11866 11867 if (BitWidth) { 11868 // 6.7.2.1p3, 6.7.2.1p4 11869 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take(); 11870 if (!BitWidth) 11871 D.setInvalidType(); 11872 } else { 11873 // Not a bitfield. 11874 11875 // validate II. 11876 11877 } 11878 if (T->isReferenceType()) { 11879 Diag(Loc, diag::err_ivar_reference_type); 11880 D.setInvalidType(); 11881 } 11882 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11883 // than a variably modified type. 11884 else if (T->isVariablyModifiedType()) { 11885 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11886 D.setInvalidType(); 11887 } 11888 11889 // Get the visibility (access control) for this ivar. 11890 ObjCIvarDecl::AccessControl ac = 11891 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11892 : ObjCIvarDecl::None; 11893 // Must set ivar's DeclContext to its enclosing interface. 11894 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11895 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11896 return 0; 11897 ObjCContainerDecl *EnclosingContext; 11898 if (ObjCImplementationDecl *IMPDecl = 11899 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11900 if (LangOpts.ObjCRuntime.isFragile()) { 11901 // Case of ivar declared in an implementation. Context is that of its class. 11902 EnclosingContext = IMPDecl->getClassInterface(); 11903 assert(EnclosingContext && "Implementation has no class interface!"); 11904 } 11905 else 11906 EnclosingContext = EnclosingDecl; 11907 } else { 11908 if (ObjCCategoryDecl *CDecl = 11909 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 11910 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 11911 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 11912 return 0; 11913 } 11914 } 11915 EnclosingContext = EnclosingDecl; 11916 } 11917 11918 // Construct the decl. 11919 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 11920 DeclStart, Loc, II, T, 11921 TInfo, ac, (Expr *)BitfieldWidth); 11922 11923 if (II) { 11924 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 11925 ForRedeclaration); 11926 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 11927 && !isa<TagDecl>(PrevDecl)) { 11928 Diag(Loc, diag::err_duplicate_member) << II; 11929 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11930 NewID->setInvalidDecl(); 11931 } 11932 } 11933 11934 // Process attributes attached to the ivar. 11935 ProcessDeclAttributes(S, NewID, D); 11936 11937 if (D.isInvalidType()) 11938 NewID->setInvalidDecl(); 11939 11940 // In ARC, infer 'retaining' for ivars of retainable type. 11941 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 11942 NewID->setInvalidDecl(); 11943 11944 if (D.getDeclSpec().isModulePrivateSpecified()) 11945 NewID->setModulePrivate(); 11946 11947 if (II) { 11948 // FIXME: When interfaces are DeclContexts, we'll need to add 11949 // these to the interface. 11950 S->AddDecl(NewID); 11951 IdResolver.AddDecl(NewID); 11952 } 11953 11954 if (LangOpts.ObjCRuntime.isNonFragile() && 11955 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 11956 Diag(Loc, diag::warn_ivars_in_interface); 11957 11958 return NewID; 11959 } 11960 11961 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 11962 /// class and class extensions. For every class \@interface and class 11963 /// extension \@interface, if the last ivar is a bitfield of any type, 11964 /// then add an implicit `char :0` ivar to the end of that interface. 11965 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 11966 SmallVectorImpl<Decl *> &AllIvarDecls) { 11967 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 11968 return; 11969 11970 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 11971 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 11972 11973 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 11974 return; 11975 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 11976 if (!ID) { 11977 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 11978 if (!CD->IsClassExtension()) 11979 return; 11980 } 11981 // No need to add this to end of @implementation. 11982 else 11983 return; 11984 } 11985 // All conditions are met. Add a new bitfield to the tail end of ivars. 11986 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 11987 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 11988 11989 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 11990 DeclLoc, DeclLoc, 0, 11991 Context.CharTy, 11992 Context.getTrivialTypeSourceInfo(Context.CharTy, 11993 DeclLoc), 11994 ObjCIvarDecl::Private, BW, 11995 true); 11996 AllIvarDecls.push_back(Ivar); 11997 } 11998 11999 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12000 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12001 SourceLocation RBrac, AttributeList *Attr) { 12002 assert(EnclosingDecl && "missing record or interface decl"); 12003 12004 // If this is an Objective-C @implementation or category and we have 12005 // new fields here we should reset the layout of the interface since 12006 // it will now change. 12007 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12008 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12009 switch (DC->getKind()) { 12010 default: break; 12011 case Decl::ObjCCategory: 12012 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12013 break; 12014 case Decl::ObjCImplementation: 12015 Context. 12016 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12017 break; 12018 } 12019 } 12020 12021 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12022 12023 // Start counting up the number of named members; make sure to include 12024 // members of anonymous structs and unions in the total. 12025 unsigned NumNamedMembers = 0; 12026 if (Record) { 12027 for (const auto *I : Record->decls()) { 12028 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12029 if (IFD->getDeclName()) 12030 ++NumNamedMembers; 12031 } 12032 } 12033 12034 // Verify that all the fields are okay. 12035 SmallVector<FieldDecl*, 32> RecFields; 12036 12037 bool ARCErrReported = false; 12038 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12039 i != end; ++i) { 12040 FieldDecl *FD = cast<FieldDecl>(*i); 12041 12042 // Get the type for the field. 12043 const Type *FDTy = FD->getType().getTypePtr(); 12044 12045 if (!FD->isAnonymousStructOrUnion()) { 12046 // Remember all fields written by the user. 12047 RecFields.push_back(FD); 12048 } 12049 12050 // If the field is already invalid for some reason, don't emit more 12051 // diagnostics about it. 12052 if (FD->isInvalidDecl()) { 12053 EnclosingDecl->setInvalidDecl(); 12054 continue; 12055 } 12056 12057 // C99 6.7.2.1p2: 12058 // A structure or union shall not contain a member with 12059 // incomplete or function type (hence, a structure shall not 12060 // contain an instance of itself, but may contain a pointer to 12061 // an instance of itself), except that the last member of a 12062 // structure with more than one named member may have incomplete 12063 // array type; such a structure (and any union containing, 12064 // possibly recursively, a member that is such a structure) 12065 // shall not be a member of a structure or an element of an 12066 // array. 12067 if (FDTy->isFunctionType()) { 12068 // Field declared as a function. 12069 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12070 << FD->getDeclName(); 12071 FD->setInvalidDecl(); 12072 EnclosingDecl->setInvalidDecl(); 12073 continue; 12074 } else if (FDTy->isIncompleteArrayType() && Record && 12075 ((i + 1 == Fields.end() && !Record->isUnion()) || 12076 ((getLangOpts().MicrosoftExt || 12077 getLangOpts().CPlusPlus) && 12078 (i + 1 == Fields.end() || Record->isUnion())))) { 12079 // Flexible array member. 12080 // Microsoft and g++ is more permissive regarding flexible array. 12081 // It will accept flexible array in union and also 12082 // as the sole element of a struct/class. 12083 unsigned DiagID = 0; 12084 if (Record->isUnion()) 12085 DiagID = getLangOpts().MicrosoftExt 12086 ? diag::ext_flexible_array_union_ms 12087 : getLangOpts().CPlusPlus 12088 ? diag::ext_flexible_array_union_gnu 12089 : diag::err_flexible_array_union; 12090 else if (Fields.size() == 1) 12091 DiagID = getLangOpts().MicrosoftExt 12092 ? diag::ext_flexible_array_empty_aggregate_ms 12093 : getLangOpts().CPlusPlus 12094 ? diag::ext_flexible_array_empty_aggregate_gnu 12095 : NumNamedMembers < 1 12096 ? diag::err_flexible_array_empty_aggregate 12097 : 0; 12098 12099 if (DiagID) 12100 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12101 << Record->getTagKind(); 12102 // While the layout of types that contain virtual bases is not specified 12103 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12104 // virtual bases after the derived members. This would make a flexible 12105 // array member declared at the end of an object not adjacent to the end 12106 // of the type. 12107 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12108 if (RD->getNumVBases() != 0) 12109 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12110 << FD->getDeclName() << Record->getTagKind(); 12111 if (!getLangOpts().C99) 12112 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12113 << FD->getDeclName() << Record->getTagKind(); 12114 12115 // If the element type has a non-trivial destructor, we would not 12116 // implicitly destroy the elements, so disallow it for now. 12117 // 12118 // FIXME: GCC allows this. We should probably either implicitly delete 12119 // the destructor of the containing class, or just allow this. 12120 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12121 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12122 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12123 << FD->getDeclName() << FD->getType(); 12124 FD->setInvalidDecl(); 12125 EnclosingDecl->setInvalidDecl(); 12126 continue; 12127 } 12128 // Okay, we have a legal flexible array member at the end of the struct. 12129 if (Record) 12130 Record->setHasFlexibleArrayMember(true); 12131 } else if (!FDTy->isDependentType() && 12132 RequireCompleteType(FD->getLocation(), FD->getType(), 12133 diag::err_field_incomplete)) { 12134 // Incomplete type 12135 FD->setInvalidDecl(); 12136 EnclosingDecl->setInvalidDecl(); 12137 continue; 12138 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12139 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12140 // If this is a member of a union, then entire union becomes "flexible". 12141 if (Record && Record->isUnion()) { 12142 Record->setHasFlexibleArrayMember(true); 12143 } else { 12144 // If this is a struct/class and this is not the last element, reject 12145 // it. Note that GCC supports variable sized arrays in the middle of 12146 // structures. 12147 if (i + 1 != Fields.end()) 12148 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12149 << FD->getDeclName() << FD->getType(); 12150 else { 12151 // We support flexible arrays at the end of structs in 12152 // other structs as an extension. 12153 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12154 << FD->getDeclName(); 12155 if (Record) 12156 Record->setHasFlexibleArrayMember(true); 12157 } 12158 } 12159 } 12160 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12161 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12162 diag::err_abstract_type_in_decl, 12163 AbstractIvarType)) { 12164 // Ivars can not have abstract class types 12165 FD->setInvalidDecl(); 12166 } 12167 if (Record && FDTTy->getDecl()->hasObjectMember()) 12168 Record->setHasObjectMember(true); 12169 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12170 Record->setHasVolatileMember(true); 12171 } else if (FDTy->isObjCObjectType()) { 12172 /// A field cannot be an Objective-c object 12173 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12174 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12175 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12176 FD->setType(T); 12177 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12178 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12179 // It's an error in ARC if a field has lifetime. 12180 // We don't want to report this in a system header, though, 12181 // so we just make the field unavailable. 12182 // FIXME: that's really not sufficient; we need to make the type 12183 // itself invalid to, say, initialize or copy. 12184 QualType T = FD->getType(); 12185 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12186 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12187 SourceLocation loc = FD->getLocation(); 12188 if (getSourceManager().isInSystemHeader(loc)) { 12189 if (!FD->hasAttr<UnavailableAttr>()) { 12190 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12191 "this system field has retaining ownership", 12192 loc)); 12193 } 12194 } else { 12195 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12196 << T->isBlockPointerType() << Record->getTagKind(); 12197 } 12198 ARCErrReported = true; 12199 } 12200 } else if (getLangOpts().ObjC1 && 12201 getLangOpts().getGC() != LangOptions::NonGC && 12202 Record && !Record->hasObjectMember()) { 12203 if (FD->getType()->isObjCObjectPointerType() || 12204 FD->getType().isObjCGCStrong()) 12205 Record->setHasObjectMember(true); 12206 else if (Context.getAsArrayType(FD->getType())) { 12207 QualType BaseType = Context.getBaseElementType(FD->getType()); 12208 if (BaseType->isRecordType() && 12209 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12210 Record->setHasObjectMember(true); 12211 else if (BaseType->isObjCObjectPointerType() || 12212 BaseType.isObjCGCStrong()) 12213 Record->setHasObjectMember(true); 12214 } 12215 } 12216 if (Record && FD->getType().isVolatileQualified()) 12217 Record->setHasVolatileMember(true); 12218 // Keep track of the number of named members. 12219 if (FD->getIdentifier()) 12220 ++NumNamedMembers; 12221 } 12222 12223 // Okay, we successfully defined 'Record'. 12224 if (Record) { 12225 bool Completed = false; 12226 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12227 if (!CXXRecord->isInvalidDecl()) { 12228 // Set access bits correctly on the directly-declared conversions. 12229 for (CXXRecordDecl::conversion_iterator 12230 I = CXXRecord->conversion_begin(), 12231 E = CXXRecord->conversion_end(); I != E; ++I) 12232 I.setAccess((*I)->getAccess()); 12233 12234 if (!CXXRecord->isDependentType()) { 12235 if (CXXRecord->hasUserDeclaredDestructor()) { 12236 // Adjust user-defined destructor exception spec. 12237 if (getLangOpts().CPlusPlus11) 12238 AdjustDestructorExceptionSpec(CXXRecord, 12239 CXXRecord->getDestructor()); 12240 } 12241 12242 // Add any implicitly-declared members to this class. 12243 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12244 12245 // If we have virtual base classes, we may end up finding multiple 12246 // final overriders for a given virtual function. Check for this 12247 // problem now. 12248 if (CXXRecord->getNumVBases()) { 12249 CXXFinalOverriderMap FinalOverriders; 12250 CXXRecord->getFinalOverriders(FinalOverriders); 12251 12252 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12253 MEnd = FinalOverriders.end(); 12254 M != MEnd; ++M) { 12255 for (OverridingMethods::iterator SO = M->second.begin(), 12256 SOEnd = M->second.end(); 12257 SO != SOEnd; ++SO) { 12258 assert(SO->second.size() > 0 && 12259 "Virtual function without overridding functions?"); 12260 if (SO->second.size() == 1) 12261 continue; 12262 12263 // C++ [class.virtual]p2: 12264 // In a derived class, if a virtual member function of a base 12265 // class subobject has more than one final overrider the 12266 // program is ill-formed. 12267 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12268 << (const NamedDecl *)M->first << Record; 12269 Diag(M->first->getLocation(), 12270 diag::note_overridden_virtual_function); 12271 for (OverridingMethods::overriding_iterator 12272 OM = SO->second.begin(), 12273 OMEnd = SO->second.end(); 12274 OM != OMEnd; ++OM) 12275 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12276 << (const NamedDecl *)M->first << OM->Method->getParent(); 12277 12278 Record->setInvalidDecl(); 12279 } 12280 } 12281 CXXRecord->completeDefinition(&FinalOverriders); 12282 Completed = true; 12283 } 12284 } 12285 } 12286 } 12287 12288 if (!Completed) 12289 Record->completeDefinition(); 12290 12291 if (Record->hasAttrs()) { 12292 CheckAlignasUnderalignment(Record); 12293 12294 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12295 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12296 IA->getRange(), IA->getBestCase(), 12297 IA->getSemanticSpelling()); 12298 } 12299 12300 // Check if the structure/union declaration is a type that can have zero 12301 // size in C. For C this is a language extension, for C++ it may cause 12302 // compatibility problems. 12303 bool CheckForZeroSize; 12304 if (!getLangOpts().CPlusPlus) { 12305 CheckForZeroSize = true; 12306 } else { 12307 // For C++ filter out types that cannot be referenced in C code. 12308 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12309 CheckForZeroSize = 12310 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12311 !CXXRecord->isDependentType() && 12312 CXXRecord->isCLike(); 12313 } 12314 if (CheckForZeroSize) { 12315 bool ZeroSize = true; 12316 bool IsEmpty = true; 12317 unsigned NonBitFields = 0; 12318 for (RecordDecl::field_iterator I = Record->field_begin(), 12319 E = Record->field_end(); 12320 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12321 IsEmpty = false; 12322 if (I->isUnnamedBitfield()) { 12323 if (I->getBitWidthValue(Context) > 0) 12324 ZeroSize = false; 12325 } else { 12326 ++NonBitFields; 12327 QualType FieldType = I->getType(); 12328 if (FieldType->isIncompleteType() || 12329 !Context.getTypeSizeInChars(FieldType).isZero()) 12330 ZeroSize = false; 12331 } 12332 } 12333 12334 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12335 // allowed in C++, but warn if its declaration is inside 12336 // extern "C" block. 12337 if (ZeroSize) { 12338 Diag(RecLoc, getLangOpts().CPlusPlus ? 12339 diag::warn_zero_size_struct_union_in_extern_c : 12340 diag::warn_zero_size_struct_union_compat) 12341 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12342 } 12343 12344 // Structs without named members are extension in C (C99 6.7.2.1p7), 12345 // but are accepted by GCC. 12346 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12347 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12348 diag::ext_no_named_members_in_struct_union) 12349 << Record->isUnion(); 12350 } 12351 } 12352 } else { 12353 ObjCIvarDecl **ClsFields = 12354 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12355 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12356 ID->setEndOfDefinitionLoc(RBrac); 12357 // Add ivar's to class's DeclContext. 12358 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12359 ClsFields[i]->setLexicalDeclContext(ID); 12360 ID->addDecl(ClsFields[i]); 12361 } 12362 // Must enforce the rule that ivars in the base classes may not be 12363 // duplicates. 12364 if (ID->getSuperClass()) 12365 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12366 } else if (ObjCImplementationDecl *IMPDecl = 12367 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12368 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12369 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12370 // Ivar declared in @implementation never belongs to the implementation. 12371 // Only it is in implementation's lexical context. 12372 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12373 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12374 IMPDecl->setIvarLBraceLoc(LBrac); 12375 IMPDecl->setIvarRBraceLoc(RBrac); 12376 } else if (ObjCCategoryDecl *CDecl = 12377 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12378 // case of ivars in class extension; all other cases have been 12379 // reported as errors elsewhere. 12380 // FIXME. Class extension does not have a LocEnd field. 12381 // CDecl->setLocEnd(RBrac); 12382 // Add ivar's to class extension's DeclContext. 12383 // Diagnose redeclaration of private ivars. 12384 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12385 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12386 if (IDecl) { 12387 if (const ObjCIvarDecl *ClsIvar = 12388 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12389 Diag(ClsFields[i]->getLocation(), 12390 diag::err_duplicate_ivar_declaration); 12391 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12392 continue; 12393 } 12394 for (const auto *Ext : IDecl->known_extensions()) { 12395 if (const ObjCIvarDecl *ClsExtIvar 12396 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12397 Diag(ClsFields[i]->getLocation(), 12398 diag::err_duplicate_ivar_declaration); 12399 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12400 continue; 12401 } 12402 } 12403 } 12404 ClsFields[i]->setLexicalDeclContext(CDecl); 12405 CDecl->addDecl(ClsFields[i]); 12406 } 12407 CDecl->setIvarLBraceLoc(LBrac); 12408 CDecl->setIvarRBraceLoc(RBrac); 12409 } 12410 } 12411 12412 if (Attr) 12413 ProcessDeclAttributeList(S, Record, Attr); 12414 } 12415 12416 /// \brief Determine whether the given integral value is representable within 12417 /// the given type T. 12418 static bool isRepresentableIntegerValue(ASTContext &Context, 12419 llvm::APSInt &Value, 12420 QualType T) { 12421 assert(T->isIntegralType(Context) && "Integral type required!"); 12422 unsigned BitWidth = Context.getIntWidth(T); 12423 12424 if (Value.isUnsigned() || Value.isNonNegative()) { 12425 if (T->isSignedIntegerOrEnumerationType()) 12426 --BitWidth; 12427 return Value.getActiveBits() <= BitWidth; 12428 } 12429 return Value.getMinSignedBits() <= BitWidth; 12430 } 12431 12432 // \brief Given an integral type, return the next larger integral type 12433 // (or a NULL type of no such type exists). 12434 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12435 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12436 // enum checking below. 12437 assert(T->isIntegralType(Context) && "Integral type required!"); 12438 const unsigned NumTypes = 4; 12439 QualType SignedIntegralTypes[NumTypes] = { 12440 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12441 }; 12442 QualType UnsignedIntegralTypes[NumTypes] = { 12443 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12444 Context.UnsignedLongLongTy 12445 }; 12446 12447 unsigned BitWidth = Context.getTypeSize(T); 12448 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12449 : UnsignedIntegralTypes; 12450 for (unsigned I = 0; I != NumTypes; ++I) 12451 if (Context.getTypeSize(Types[I]) > BitWidth) 12452 return Types[I]; 12453 12454 return QualType(); 12455 } 12456 12457 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12458 EnumConstantDecl *LastEnumConst, 12459 SourceLocation IdLoc, 12460 IdentifierInfo *Id, 12461 Expr *Val) { 12462 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12463 llvm::APSInt EnumVal(IntWidth); 12464 QualType EltTy; 12465 12466 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12467 Val = 0; 12468 12469 if (Val) 12470 Val = DefaultLvalueConversion(Val).take(); 12471 12472 if (Val) { 12473 if (Enum->isDependentType() || Val->isTypeDependent()) 12474 EltTy = Context.DependentTy; 12475 else { 12476 SourceLocation ExpLoc; 12477 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12478 !getLangOpts().MSVCCompat) { 12479 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12480 // constant-expression in the enumerator-definition shall be a converted 12481 // constant expression of the underlying type. 12482 EltTy = Enum->getIntegerType(); 12483 ExprResult Converted = 12484 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12485 CCEK_Enumerator); 12486 if (Converted.isInvalid()) 12487 Val = 0; 12488 else 12489 Val = Converted.take(); 12490 } else if (!Val->isValueDependent() && 12491 !(Val = VerifyIntegerConstantExpression(Val, 12492 &EnumVal).take())) { 12493 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12494 } else { 12495 if (Enum->isFixed()) { 12496 EltTy = Enum->getIntegerType(); 12497 12498 // In Obj-C and Microsoft mode, require the enumeration value to be 12499 // representable in the underlying type of the enumeration. In C++11, 12500 // we perform a non-narrowing conversion as part of converted constant 12501 // expression checking. 12502 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12503 if (getLangOpts().MSVCCompat) { 12504 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12505 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12506 } else 12507 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12508 } else 12509 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 12510 } else if (getLangOpts().CPlusPlus) { 12511 // C++11 [dcl.enum]p5: 12512 // If the underlying type is not fixed, the type of each enumerator 12513 // is the type of its initializing value: 12514 // - If an initializer is specified for an enumerator, the 12515 // initializing value has the same type as the expression. 12516 EltTy = Val->getType(); 12517 } else { 12518 // C99 6.7.2.2p2: 12519 // The expression that defines the value of an enumeration constant 12520 // shall be an integer constant expression that has a value 12521 // representable as an int. 12522 12523 // Complain if the value is not representable in an int. 12524 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12525 Diag(IdLoc, diag::ext_enum_value_not_int) 12526 << EnumVal.toString(10) << Val->getSourceRange() 12527 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12528 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12529 // Force the type of the expression to 'int'. 12530 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 12531 } 12532 EltTy = Val->getType(); 12533 } 12534 } 12535 } 12536 } 12537 12538 if (!Val) { 12539 if (Enum->isDependentType()) 12540 EltTy = Context.DependentTy; 12541 else if (!LastEnumConst) { 12542 // C++0x [dcl.enum]p5: 12543 // If the underlying type is not fixed, the type of each enumerator 12544 // is the type of its initializing value: 12545 // - If no initializer is specified for the first enumerator, the 12546 // initializing value has an unspecified integral type. 12547 // 12548 // GCC uses 'int' for its unspecified integral type, as does 12549 // C99 6.7.2.2p3. 12550 if (Enum->isFixed()) { 12551 EltTy = Enum->getIntegerType(); 12552 } 12553 else { 12554 EltTy = Context.IntTy; 12555 } 12556 } else { 12557 // Assign the last value + 1. 12558 EnumVal = LastEnumConst->getInitVal(); 12559 ++EnumVal; 12560 EltTy = LastEnumConst->getType(); 12561 12562 // Check for overflow on increment. 12563 if (EnumVal < LastEnumConst->getInitVal()) { 12564 // C++0x [dcl.enum]p5: 12565 // If the underlying type is not fixed, the type of each enumerator 12566 // is the type of its initializing value: 12567 // 12568 // - Otherwise the type of the initializing value is the same as 12569 // the type of the initializing value of the preceding enumerator 12570 // unless the incremented value is not representable in that type, 12571 // in which case the type is an unspecified integral type 12572 // sufficient to contain the incremented value. If no such type 12573 // exists, the program is ill-formed. 12574 QualType T = getNextLargerIntegralType(Context, EltTy); 12575 if (T.isNull() || Enum->isFixed()) { 12576 // There is no integral type larger enough to represent this 12577 // value. Complain, then allow the value to wrap around. 12578 EnumVal = LastEnumConst->getInitVal(); 12579 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12580 ++EnumVal; 12581 if (Enum->isFixed()) 12582 // When the underlying type is fixed, this is ill-formed. 12583 Diag(IdLoc, diag::err_enumerator_wrapped) 12584 << EnumVal.toString(10) 12585 << EltTy; 12586 else 12587 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12588 << EnumVal.toString(10); 12589 } else { 12590 EltTy = T; 12591 } 12592 12593 // Retrieve the last enumerator's value, extent that type to the 12594 // type that is supposed to be large enough to represent the incremented 12595 // value, then increment. 12596 EnumVal = LastEnumConst->getInitVal(); 12597 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12598 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12599 ++EnumVal; 12600 12601 // If we're not in C++, diagnose the overflow of enumerator values, 12602 // which in C99 means that the enumerator value is not representable in 12603 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12604 // permits enumerator values that are representable in some larger 12605 // integral type. 12606 if (!getLangOpts().CPlusPlus && !T.isNull()) 12607 Diag(IdLoc, diag::warn_enum_value_overflow); 12608 } else if (!getLangOpts().CPlusPlus && 12609 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12610 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12611 Diag(IdLoc, diag::ext_enum_value_not_int) 12612 << EnumVal.toString(10) << 1; 12613 } 12614 } 12615 } 12616 12617 if (!EltTy->isDependentType()) { 12618 // Make the enumerator value match the signedness and size of the 12619 // enumerator's type. 12620 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12621 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12622 } 12623 12624 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12625 Val, EnumVal); 12626 } 12627 12628 12629 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12630 SourceLocation IdLoc, IdentifierInfo *Id, 12631 AttributeList *Attr, 12632 SourceLocation EqualLoc, Expr *Val) { 12633 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12634 EnumConstantDecl *LastEnumConst = 12635 cast_or_null<EnumConstantDecl>(lastEnumConst); 12636 12637 // The scope passed in may not be a decl scope. Zip up the scope tree until 12638 // we find one that is. 12639 S = getNonFieldDeclScope(S); 12640 12641 // Verify that there isn't already something declared with this name in this 12642 // scope. 12643 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12644 ForRedeclaration); 12645 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12646 // Maybe we will complain about the shadowed template parameter. 12647 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12648 // Just pretend that we didn't see the previous declaration. 12649 PrevDecl = 0; 12650 } 12651 12652 if (PrevDecl) { 12653 // When in C++, we may get a TagDecl with the same name; in this case the 12654 // enum constant will 'hide' the tag. 12655 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12656 "Received TagDecl when not in C++!"); 12657 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12658 if (isa<EnumConstantDecl>(PrevDecl)) 12659 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12660 else 12661 Diag(IdLoc, diag::err_redefinition) << Id; 12662 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12663 return 0; 12664 } 12665 } 12666 12667 // C++ [class.mem]p15: 12668 // If T is the name of a class, then each of the following shall have a name 12669 // different from T: 12670 // - every enumerator of every member of class T that is an unscoped 12671 // enumerated type 12672 if (CXXRecordDecl *Record 12673 = dyn_cast<CXXRecordDecl>( 12674 TheEnumDecl->getDeclContext()->getRedeclContext())) 12675 if (!TheEnumDecl->isScoped() && 12676 Record->getIdentifier() && Record->getIdentifier() == Id) 12677 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12678 12679 EnumConstantDecl *New = 12680 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12681 12682 if (New) { 12683 // Process attributes. 12684 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12685 12686 // Register this decl in the current scope stack. 12687 New->setAccess(TheEnumDecl->getAccess()); 12688 PushOnScopeChains(New, S); 12689 } 12690 12691 ActOnDocumentableDecl(New); 12692 12693 return New; 12694 } 12695 12696 // Returns true when the enum initial expression does not trigger the 12697 // duplicate enum warning. A few common cases are exempted as follows: 12698 // Element2 = Element1 12699 // Element2 = Element1 + 1 12700 // Element2 = Element1 - 1 12701 // Where Element2 and Element1 are from the same enum. 12702 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12703 Expr *InitExpr = ECD->getInitExpr(); 12704 if (!InitExpr) 12705 return true; 12706 InitExpr = InitExpr->IgnoreImpCasts(); 12707 12708 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12709 if (!BO->isAdditiveOp()) 12710 return true; 12711 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12712 if (!IL) 12713 return true; 12714 if (IL->getValue() != 1) 12715 return true; 12716 12717 InitExpr = BO->getLHS(); 12718 } 12719 12720 // This checks if the elements are from the same enum. 12721 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12722 if (!DRE) 12723 return true; 12724 12725 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12726 if (!EnumConstant) 12727 return true; 12728 12729 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12730 Enum) 12731 return true; 12732 12733 return false; 12734 } 12735 12736 struct DupKey { 12737 int64_t val; 12738 bool isTombstoneOrEmptyKey; 12739 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12740 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12741 }; 12742 12743 static DupKey GetDupKey(const llvm::APSInt& Val) { 12744 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12745 false); 12746 } 12747 12748 struct DenseMapInfoDupKey { 12749 static DupKey getEmptyKey() { return DupKey(0, true); } 12750 static DupKey getTombstoneKey() { return DupKey(1, true); } 12751 static unsigned getHashValue(const DupKey Key) { 12752 return (unsigned)(Key.val * 37); 12753 } 12754 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12755 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12756 LHS.val == RHS.val; 12757 } 12758 }; 12759 12760 // Emits a warning when an element is implicitly set a value that 12761 // a previous element has already been set to. 12762 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12763 EnumDecl *Enum, 12764 QualType EnumType) { 12765 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12766 Enum->getLocation()) == 12767 DiagnosticsEngine::Ignored) 12768 return; 12769 // Avoid anonymous enums 12770 if (!Enum->getIdentifier()) 12771 return; 12772 12773 // Only check for small enums. 12774 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12775 return; 12776 12777 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12778 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12779 12780 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12781 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12782 ValueToVectorMap; 12783 12784 DuplicatesVector DupVector; 12785 ValueToVectorMap EnumMap; 12786 12787 // Populate the EnumMap with all values represented by enum constants without 12788 // an initialier. 12789 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12790 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12791 12792 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12793 // this constant. Skip this enum since it may be ill-formed. 12794 if (!ECD) { 12795 return; 12796 } 12797 12798 if (ECD->getInitExpr()) 12799 continue; 12800 12801 DupKey Key = GetDupKey(ECD->getInitVal()); 12802 DeclOrVector &Entry = EnumMap[Key]; 12803 12804 // First time encountering this value. 12805 if (Entry.isNull()) 12806 Entry = ECD; 12807 } 12808 12809 // Create vectors for any values that has duplicates. 12810 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12811 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12812 if (!ValidDuplicateEnum(ECD, Enum)) 12813 continue; 12814 12815 DupKey Key = GetDupKey(ECD->getInitVal()); 12816 12817 DeclOrVector& Entry = EnumMap[Key]; 12818 if (Entry.isNull()) 12819 continue; 12820 12821 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12822 // Ensure constants are different. 12823 if (D == ECD) 12824 continue; 12825 12826 // Create new vector and push values onto it. 12827 ECDVector *Vec = new ECDVector(); 12828 Vec->push_back(D); 12829 Vec->push_back(ECD); 12830 12831 // Update entry to point to the duplicates vector. 12832 Entry = Vec; 12833 12834 // Store the vector somewhere we can consult later for quick emission of 12835 // diagnostics. 12836 DupVector.push_back(Vec); 12837 continue; 12838 } 12839 12840 ECDVector *Vec = Entry.get<ECDVector*>(); 12841 // Make sure constants are not added more than once. 12842 if (*Vec->begin() == ECD) 12843 continue; 12844 12845 Vec->push_back(ECD); 12846 } 12847 12848 // Emit diagnostics. 12849 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12850 DupVectorEnd = DupVector.end(); 12851 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12852 ECDVector *Vec = *DupVectorIter; 12853 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12854 12855 // Emit warning for one enum constant. 12856 ECDVector::iterator I = Vec->begin(); 12857 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12858 << (*I)->getName() << (*I)->getInitVal().toString(10) 12859 << (*I)->getSourceRange(); 12860 ++I; 12861 12862 // Emit one note for each of the remaining enum constants with 12863 // the same value. 12864 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12865 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12866 << (*I)->getName() << (*I)->getInitVal().toString(10) 12867 << (*I)->getSourceRange(); 12868 delete Vec; 12869 } 12870 } 12871 12872 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12873 SourceLocation RBraceLoc, Decl *EnumDeclX, 12874 ArrayRef<Decl *> Elements, 12875 Scope *S, AttributeList *Attr) { 12876 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12877 QualType EnumType = Context.getTypeDeclType(Enum); 12878 12879 if (Attr) 12880 ProcessDeclAttributeList(S, Enum, Attr); 12881 12882 if (Enum->isDependentType()) { 12883 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12884 EnumConstantDecl *ECD = 12885 cast_or_null<EnumConstantDecl>(Elements[i]); 12886 if (!ECD) continue; 12887 12888 ECD->setType(EnumType); 12889 } 12890 12891 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12892 return; 12893 } 12894 12895 // TODO: If the result value doesn't fit in an int, it must be a long or long 12896 // long value. ISO C does not support this, but GCC does as an extension, 12897 // emit a warning. 12898 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12899 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12900 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12901 12902 // Verify that all the values are okay, compute the size of the values, and 12903 // reverse the list. 12904 unsigned NumNegativeBits = 0; 12905 unsigned NumPositiveBits = 0; 12906 12907 // Keep track of whether all elements have type int. 12908 bool AllElementsInt = true; 12909 12910 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12911 EnumConstantDecl *ECD = 12912 cast_or_null<EnumConstantDecl>(Elements[i]); 12913 if (!ECD) continue; // Already issued a diagnostic. 12914 12915 const llvm::APSInt &InitVal = ECD->getInitVal(); 12916 12917 // Keep track of the size of positive and negative values. 12918 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 12919 NumPositiveBits = std::max(NumPositiveBits, 12920 (unsigned)InitVal.getActiveBits()); 12921 else 12922 NumNegativeBits = std::max(NumNegativeBits, 12923 (unsigned)InitVal.getMinSignedBits()); 12924 12925 // Keep track of whether every enum element has type int (very commmon). 12926 if (AllElementsInt) 12927 AllElementsInt = ECD->getType() == Context.IntTy; 12928 } 12929 12930 // Figure out the type that should be used for this enum. 12931 QualType BestType; 12932 unsigned BestWidth; 12933 12934 // C++0x N3000 [conv.prom]p3: 12935 // An rvalue of an unscoped enumeration type whose underlying 12936 // type is not fixed can be converted to an rvalue of the first 12937 // of the following types that can represent all the values of 12938 // the enumeration: int, unsigned int, long int, unsigned long 12939 // int, long long int, or unsigned long long int. 12940 // C99 6.4.4.3p2: 12941 // An identifier declared as an enumeration constant has type int. 12942 // The C99 rule is modified by a gcc extension 12943 QualType BestPromotionType; 12944 12945 bool Packed = Enum->hasAttr<PackedAttr>(); 12946 // -fshort-enums is the equivalent to specifying the packed attribute on all 12947 // enum definitions. 12948 if (LangOpts.ShortEnums) 12949 Packed = true; 12950 12951 if (Enum->isFixed()) { 12952 BestType = Enum->getIntegerType(); 12953 if (BestType->isPromotableIntegerType()) 12954 BestPromotionType = Context.getPromotedIntegerType(BestType); 12955 else 12956 BestPromotionType = BestType; 12957 // We don't need to set BestWidth, because BestType is going to be the type 12958 // of the enumerators, but we do anyway because otherwise some compilers 12959 // warn that it might be used uninitialized. 12960 BestWidth = CharWidth; 12961 } 12962 else if (NumNegativeBits) { 12963 // If there is a negative value, figure out the smallest integer type (of 12964 // int/long/longlong) that fits. 12965 // If it's packed, check also if it fits a char or a short. 12966 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 12967 BestType = Context.SignedCharTy; 12968 BestWidth = CharWidth; 12969 } else if (Packed && NumNegativeBits <= ShortWidth && 12970 NumPositiveBits < ShortWidth) { 12971 BestType = Context.ShortTy; 12972 BestWidth = ShortWidth; 12973 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 12974 BestType = Context.IntTy; 12975 BestWidth = IntWidth; 12976 } else { 12977 BestWidth = Context.getTargetInfo().getLongWidth(); 12978 12979 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 12980 BestType = Context.LongTy; 12981 } else { 12982 BestWidth = Context.getTargetInfo().getLongLongWidth(); 12983 12984 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 12985 Diag(Enum->getLocation(), diag::ext_enum_too_large); 12986 BestType = Context.LongLongTy; 12987 } 12988 } 12989 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 12990 } else { 12991 // If there is no negative value, figure out the smallest type that fits 12992 // all of the enumerator values. 12993 // If it's packed, check also if it fits a char or a short. 12994 if (Packed && NumPositiveBits <= CharWidth) { 12995 BestType = Context.UnsignedCharTy; 12996 BestPromotionType = Context.IntTy; 12997 BestWidth = CharWidth; 12998 } else if (Packed && NumPositiveBits <= ShortWidth) { 12999 BestType = Context.UnsignedShortTy; 13000 BestPromotionType = Context.IntTy; 13001 BestWidth = ShortWidth; 13002 } else if (NumPositiveBits <= IntWidth) { 13003 BestType = Context.UnsignedIntTy; 13004 BestWidth = IntWidth; 13005 BestPromotionType 13006 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13007 ? Context.UnsignedIntTy : Context.IntTy; 13008 } else if (NumPositiveBits <= 13009 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13010 BestType = Context.UnsignedLongTy; 13011 BestPromotionType 13012 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13013 ? Context.UnsignedLongTy : Context.LongTy; 13014 } else { 13015 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13016 assert(NumPositiveBits <= BestWidth && 13017 "How could an initializer get larger than ULL?"); 13018 BestType = Context.UnsignedLongLongTy; 13019 BestPromotionType 13020 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13021 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13022 } 13023 } 13024 13025 // Loop over all of the enumerator constants, changing their types to match 13026 // the type of the enum if needed. 13027 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13028 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13029 if (!ECD) continue; // Already issued a diagnostic. 13030 13031 // Standard C says the enumerators have int type, but we allow, as an 13032 // extension, the enumerators to be larger than int size. If each 13033 // enumerator value fits in an int, type it as an int, otherwise type it the 13034 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13035 // that X has type 'int', not 'unsigned'. 13036 13037 // Determine whether the value fits into an int. 13038 llvm::APSInt InitVal = ECD->getInitVal(); 13039 13040 // If it fits into an integer type, force it. Otherwise force it to match 13041 // the enum decl type. 13042 QualType NewTy; 13043 unsigned NewWidth; 13044 bool NewSign; 13045 if (!getLangOpts().CPlusPlus && 13046 !Enum->isFixed() && 13047 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13048 NewTy = Context.IntTy; 13049 NewWidth = IntWidth; 13050 NewSign = true; 13051 } else if (ECD->getType() == BestType) { 13052 // Already the right type! 13053 if (getLangOpts().CPlusPlus) 13054 // C++ [dcl.enum]p4: Following the closing brace of an 13055 // enum-specifier, each enumerator has the type of its 13056 // enumeration. 13057 ECD->setType(EnumType); 13058 continue; 13059 } else { 13060 NewTy = BestType; 13061 NewWidth = BestWidth; 13062 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13063 } 13064 13065 // Adjust the APSInt value. 13066 InitVal = InitVal.extOrTrunc(NewWidth); 13067 InitVal.setIsSigned(NewSign); 13068 ECD->setInitVal(InitVal); 13069 13070 // Adjust the Expr initializer and type. 13071 if (ECD->getInitExpr() && 13072 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13073 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13074 CK_IntegralCast, 13075 ECD->getInitExpr(), 13076 /*base paths*/ 0, 13077 VK_RValue)); 13078 if (getLangOpts().CPlusPlus) 13079 // C++ [dcl.enum]p4: Following the closing brace of an 13080 // enum-specifier, each enumerator has the type of its 13081 // enumeration. 13082 ECD->setType(EnumType); 13083 else 13084 ECD->setType(NewTy); 13085 } 13086 13087 Enum->completeDefinition(BestType, BestPromotionType, 13088 NumPositiveBits, NumNegativeBits); 13089 13090 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13091 13092 // Now that the enum type is defined, ensure it's not been underaligned. 13093 if (Enum->hasAttrs()) 13094 CheckAlignasUnderalignment(Enum); 13095 } 13096 13097 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13098 SourceLocation StartLoc, 13099 SourceLocation EndLoc) { 13100 StringLiteral *AsmString = cast<StringLiteral>(expr); 13101 13102 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13103 AsmString, StartLoc, 13104 EndLoc); 13105 CurContext->addDecl(New); 13106 return New; 13107 } 13108 13109 static void checkModuleImportContext(Sema &S, Module *M, 13110 SourceLocation ImportLoc, 13111 DeclContext *DC) { 13112 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13113 switch (LSD->getLanguage()) { 13114 case LinkageSpecDecl::lang_c: 13115 if (!M->IsExternC) { 13116 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13117 << M->getFullModuleName(); 13118 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13119 return; 13120 } 13121 break; 13122 case LinkageSpecDecl::lang_cxx: 13123 break; 13124 } 13125 DC = LSD->getParent(); 13126 } 13127 13128 while (isa<LinkageSpecDecl>(DC)) 13129 DC = DC->getParent(); 13130 if (!isa<TranslationUnitDecl>(DC)) { 13131 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13132 << M->getFullModuleName() << DC; 13133 S.Diag(cast<Decl>(DC)->getLocStart(), 13134 diag::note_module_import_not_at_top_level) 13135 << DC; 13136 } 13137 } 13138 13139 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13140 SourceLocation ImportLoc, 13141 ModuleIdPath Path) { 13142 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 13143 Module::AllVisible, 13144 /*IsIncludeDirective=*/false); 13145 if (!Mod) 13146 return true; 13147 13148 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13149 13150 SmallVector<SourceLocation, 2> IdentifierLocs; 13151 Module *ModCheck = Mod; 13152 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13153 // If we've run out of module parents, just drop the remaining identifiers. 13154 // We need the length to be consistent. 13155 if (!ModCheck) 13156 break; 13157 ModCheck = ModCheck->Parent; 13158 13159 IdentifierLocs.push_back(Path[I].second); 13160 } 13161 13162 ImportDecl *Import = ImportDecl::Create(Context, 13163 Context.getTranslationUnitDecl(), 13164 AtLoc.isValid()? AtLoc : ImportLoc, 13165 Mod, IdentifierLocs); 13166 Context.getTranslationUnitDecl()->addDecl(Import); 13167 return Import; 13168 } 13169 13170 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13171 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13172 13173 // FIXME: Should we synthesize an ImportDecl here? 13174 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13175 /*Complain=*/true); 13176 } 13177 13178 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) { 13179 // Create the implicit import declaration. 13180 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13181 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13182 Loc, Mod, Loc); 13183 TU->addDecl(ImportD); 13184 Consumer.HandleImplicitImportDecl(ImportD); 13185 13186 // Make the module visible. 13187 PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13188 /*Complain=*/false); 13189 } 13190 13191 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13192 IdentifierInfo* AliasName, 13193 SourceLocation PragmaLoc, 13194 SourceLocation NameLoc, 13195 SourceLocation AliasNameLoc) { 13196 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13197 LookupOrdinaryName); 13198 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13199 AliasName->getName(), 0); 13200 13201 if (PrevDecl) 13202 PrevDecl->addAttr(Attr); 13203 else 13204 (void)ExtnameUndeclaredIdentifiers.insert( 13205 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13206 } 13207 13208 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13209 SourceLocation PragmaLoc, 13210 SourceLocation NameLoc) { 13211 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13212 13213 if (PrevDecl) { 13214 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13215 } else { 13216 (void)WeakUndeclaredIdentifiers.insert( 13217 std::pair<IdentifierInfo*,WeakInfo> 13218 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 13219 } 13220 } 13221 13222 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13223 IdentifierInfo* AliasName, 13224 SourceLocation PragmaLoc, 13225 SourceLocation NameLoc, 13226 SourceLocation AliasNameLoc) { 13227 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13228 LookupOrdinaryName); 13229 WeakInfo W = WeakInfo(Name, NameLoc); 13230 13231 if (PrevDecl) { 13232 if (!PrevDecl->hasAttr<AliasAttr>()) 13233 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13234 DeclApplyPragmaWeak(TUScope, ND, W); 13235 } else { 13236 (void)WeakUndeclaredIdentifiers.insert( 13237 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13238 } 13239 } 13240 13241 Decl *Sema::getObjCDeclContext() const { 13242 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13243 } 13244 13245 AvailabilityResult Sema::getCurContextAvailability() const { 13246 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13247 // If we are within an Objective-C method, we should consult 13248 // both the availability of the method as well as the 13249 // enclosing class. If the class is (say) deprecated, 13250 // the entire method is considered deprecated from the 13251 // purpose of checking if the current context is deprecated. 13252 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13253 AvailabilityResult R = MD->getAvailability(); 13254 if (R != AR_Available) 13255 return R; 13256 D = MD->getClassInterface(); 13257 } 13258 // If we are within an Objective-c @implementation, it 13259 // gets the same availability context as the @interface. 13260 else if (const ObjCImplementationDecl *ID = 13261 dyn_cast<ObjCImplementationDecl>(D)) { 13262 D = ID->getClassInterface(); 13263 } 13264 return D->getAvailability(); 13265 } 13266