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/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Parse/ParseDiagnostic.h" 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 68 bool AllowTemplates=false) 69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowClassTemplates(AllowTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 80 return (IsType || AllowedTemplate) && 81 (AllowInvalidDecl || !ND->isInvalidDecl()); 82 } 83 return !WantClassName && candidate.isKeyword(); 84 } 85 86 private: 87 bool AllowInvalidDecl; 88 bool WantClassName; 89 bool AllowClassTemplates; 90 }; 91 92 } 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw_wchar_t: 112 case tok::kw_bool: 113 case tok::kw___underlying_type: 114 return true; 115 116 case tok::annot_typename: 117 case tok::kw_char16_t: 118 case tok::kw_char32_t: 119 case tok::kw_typeof: 120 case tok::annot_decltype: 121 case tok::kw_decltype: 122 return getLangOpts().CPlusPlus; 123 124 default: 125 break; 126 } 127 128 return false; 129 } 130 131 /// \brief If the identifier refers to a type name within this scope, 132 /// return the declaration of that type. 133 /// 134 /// This routine performs ordinary name lookup of the identifier II 135 /// within the given scope, with optional C++ scope specifier SS, to 136 /// determine whether the name refers to a type. If so, returns an 137 /// opaque pointer (actually a QualType) corresponding to that 138 /// type. Otherwise, returns NULL. 139 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 140 Scope *S, CXXScopeSpec *SS, 141 bool isClassName, bool HasTrailingDot, 142 ParsedType ObjectTypePtr, 143 bool IsCtorOrDtorName, 144 bool WantNontrivialTypeSourceInfo, 145 IdentifierInfo **CorrectedII) { 146 // Determine where we will perform name lookup. 147 DeclContext *LookupCtx = nullptr; 148 if (ObjectTypePtr) { 149 QualType ObjectType = ObjectTypePtr.get(); 150 if (ObjectType->isRecordType()) 151 LookupCtx = computeDeclContext(ObjectType); 152 } else if (SS && SS->isNotEmpty()) { 153 LookupCtx = computeDeclContext(*SS, false); 154 155 if (!LookupCtx) { 156 if (isDependentScopeSpecifier(*SS)) { 157 // C++ [temp.res]p3: 158 // A qualified-id that refers to a type and in which the 159 // nested-name-specifier depends on a template-parameter (14.6.2) 160 // shall be prefixed by the keyword typename to indicate that the 161 // qualified-id denotes a type, forming an 162 // elaborated-type-specifier (7.1.5.3). 163 // 164 // We therefore do not perform any name lookup if the result would 165 // refer to a member of an unknown specialization. 166 if (!isClassName && !IsCtorOrDtorName) 167 return ParsedType(); 168 169 // We know from the grammar that this name refers to a type, 170 // so build a dependent node to describe the type. 171 if (WantNontrivialTypeSourceInfo) 172 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 173 174 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 175 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 176 II, NameLoc); 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 = nullptr; 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 CTK_ErrorRecovery); 223 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 224 TemplateTy Template; 225 bool MemberOfUnknownSpecialization; 226 UnqualifiedId TemplateName; 227 TemplateName.setIdentifier(NewII, NameLoc); 228 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 229 CXXScopeSpec NewSS, *NewSSPtr = SS; 230 if (SS && NNS) { 231 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 232 NewSSPtr = &NewSS; 233 } 234 if (Correction && (NNS || NewII != &II) && 235 // Ignore a correction to a template type as the to-be-corrected 236 // identifier is not a template (typo correction for template names 237 // is handled elsewhere). 238 !(getLangOpts().CPlusPlus && NewSSPtr && 239 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 240 false, Template, MemberOfUnknownSpecialization))) { 241 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 242 isClassName, HasTrailingDot, ObjectTypePtr, 243 IsCtorOrDtorName, 244 WantNontrivialTypeSourceInfo); 245 if (Ty) { 246 diagnoseTypo(Correction, 247 PDiag(diag::err_unknown_type_or_class_name_suggest) 248 << Result.getLookupName() << isClassName); 249 if (SS && NNS) 250 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 251 *CorrectedII = NewII; 252 return Ty; 253 } 254 } 255 } 256 // If typo correction failed or was not performed, fall through 257 case LookupResult::FoundOverloaded: 258 case LookupResult::FoundUnresolvedValue: 259 Result.suppressDiagnostics(); 260 return ParsedType(); 261 262 case LookupResult::Ambiguous: 263 // Recover from type-hiding ambiguities by hiding the type. We'll 264 // do the lookup again when looking for an object, and we can 265 // diagnose the error then. If we don't do this, then the error 266 // about hiding the type will be immediately followed by an error 267 // that only makes sense if the identifier was treated like a type. 268 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 269 Result.suppressDiagnostics(); 270 return ParsedType(); 271 } 272 273 // Look to see if we have a type anywhere in the list of results. 274 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 275 Res != ResEnd; ++Res) { 276 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 277 if (!IIDecl || 278 (*Res)->getLocation().getRawEncoding() < 279 IIDecl->getLocation().getRawEncoding()) 280 IIDecl = *Res; 281 } 282 } 283 284 if (!IIDecl) { 285 // None of the entities we found is a type, so there is no way 286 // to even assume that the result is a type. In this case, don't 287 // complain about the ambiguity. The parser will either try to 288 // perform this lookup again (e.g., as an object name), which 289 // will produce the ambiguity, or will complain that it expected 290 // a type name. 291 Result.suppressDiagnostics(); 292 return ParsedType(); 293 } 294 295 // We found a type within the ambiguous lookup; diagnose the 296 // ambiguity and then return that type. This might be the right 297 // answer, or it might not be, but it suppresses any attempt to 298 // perform the name lookup again. 299 break; 300 301 case LookupResult::Found: 302 IIDecl = Result.getFoundDecl(); 303 break; 304 } 305 306 assert(IIDecl && "Didn't find decl"); 307 308 QualType T; 309 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 310 DiagnoseUseOfDecl(IIDecl, NameLoc); 311 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 // Builds a fake NNS for the given decl context. 347 static NestedNameSpecifier * 348 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 349 for (;; DC = DC->getLookupParent()) { 350 DC = DC->getPrimaryContext(); 351 auto *ND = dyn_cast<NamespaceDecl>(DC); 352 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 353 return NestedNameSpecifier::Create(Context, nullptr, ND); 354 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 355 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 356 RD->getTypeForDecl()); 357 else if (isa<TranslationUnitDecl>(DC)) 358 return NestedNameSpecifier::GlobalSpecifier(Context); 359 } 360 llvm_unreachable("something isn't in TU scope?"); 361 } 362 363 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 364 SourceLocation NameLoc) { 365 // Accepting an undeclared identifier as a default argument for a template 366 // type parameter is a Microsoft extension. 367 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 368 369 // Build a fake DependentNameType that will perform lookup into CurContext at 370 // instantiation time. The name specifier isn't dependent, so template 371 // instantiation won't transform it. It will retry the lookup, however. 372 NestedNameSpecifier *NNS = 373 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 374 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 375 376 // Build type location information. We synthesized the qualifier, so we have 377 // to build a fake NestedNameSpecifierLoc. 378 NestedNameSpecifierLocBuilder NNSLocBuilder; 379 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 380 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 381 382 TypeLocBuilder Builder; 383 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 384 DepTL.setNameLoc(NameLoc); 385 DepTL.setElaboratedKeywordLoc(SourceLocation()); 386 DepTL.setQualifierLoc(QualifierLoc); 387 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 388 } 389 390 /// isTagName() - This method is called *for error recovery purposes only* 391 /// to determine if the specified name is a valid tag name ("struct foo"). If 392 /// so, this returns the TST for the tag corresponding to it (TST_enum, 393 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 394 /// cases in C where the user forgot to specify the tag. 395 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 396 // Do a tag name lookup in this scope. 397 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 398 LookupName(R, S, false); 399 R.suppressDiagnostics(); 400 if (R.getResultKind() == LookupResult::Found) 401 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 402 switch (TD->getTagKind()) { 403 case TTK_Struct: return DeclSpec::TST_struct; 404 case TTK_Interface: return DeclSpec::TST_interface; 405 case TTK_Union: return DeclSpec::TST_union; 406 case TTK_Class: return DeclSpec::TST_class; 407 case TTK_Enum: return DeclSpec::TST_enum; 408 } 409 } 410 411 return DeclSpec::TST_unspecified; 412 } 413 414 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 415 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 416 /// then downgrade the missing typename error to a warning. 417 /// This is needed for MSVC compatibility; Example: 418 /// @code 419 /// template<class T> class A { 420 /// public: 421 /// typedef int TYPE; 422 /// }; 423 /// template<class T> class B : public A<T> { 424 /// public: 425 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 426 /// }; 427 /// @endcode 428 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 429 if (CurContext->isRecord()) { 430 const Type *Ty = SS->getScopeRep()->getAsType(); 431 432 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 433 for (const auto &Base : RD->bases()) 434 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 435 return true; 436 return S->isFunctionPrototypeScope(); 437 } 438 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 439 } 440 441 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 442 SourceLocation IILoc, 443 Scope *S, 444 CXXScopeSpec *SS, 445 ParsedType &SuggestedType, 446 bool AllowClassTemplates) { 447 // We don't have anything to suggest (yet). 448 SuggestedType = ParsedType(); 449 450 // There may have been a typo in the name of the type. Look up typo 451 // results, in case we have something that we can suggest. 452 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 453 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 454 LookupOrdinaryName, S, SS, 455 Validator, CTK_ErrorRecovery)) { 456 if (Corrected.isKeyword()) { 457 // We corrected to a keyword. 458 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 459 II = Corrected.getCorrectionAsIdentifierInfo(); 460 } else { 461 // We found a similarly-named type or interface; suggest that. 462 if (!SS || !SS->isSet()) { 463 diagnoseTypo(Corrected, 464 PDiag(diag::err_unknown_typename_suggest) << II); 465 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 466 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 467 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 468 II->getName().equals(CorrectedStr); 469 diagnoseTypo(Corrected, 470 PDiag(diag::err_unknown_nested_typename_suggest) 471 << II << DC << DroppedSpecifier << SS->getRange()); 472 } else { 473 llvm_unreachable("could not have corrected a typo here"); 474 } 475 476 CXXScopeSpec tmpSS; 477 if (Corrected.getCorrectionSpecifier()) 478 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 479 SourceRange(IILoc)); 480 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 481 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 482 false, ParsedType(), 483 /*IsCtorOrDtorName=*/false, 484 /*NonTrivialTypeSourceInfo=*/true); 485 } 486 return true; 487 } 488 489 if (getLangOpts().CPlusPlus) { 490 // See if II is a class template that the user forgot to pass arguments to. 491 UnqualifiedId Name; 492 Name.setIdentifier(II, IILoc); 493 CXXScopeSpec EmptySS; 494 TemplateTy TemplateResult; 495 bool MemberOfUnknownSpecialization; 496 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 497 Name, ParsedType(), true, TemplateResult, 498 MemberOfUnknownSpecialization) == TNK_Type_template) { 499 TemplateName TplName = TemplateResult.get(); 500 Diag(IILoc, diag::err_template_missing_args) << TplName; 501 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 502 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 503 << TplDecl->getTemplateParameters()->getSourceRange(); 504 } 505 return true; 506 } 507 } 508 509 // FIXME: Should we move the logic that tries to recover from a missing tag 510 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 511 512 if (!SS || (!SS->isSet() && !SS->isInvalid())) 513 Diag(IILoc, diag::err_unknown_typename) << II; 514 else if (DeclContext *DC = computeDeclContext(*SS, false)) 515 Diag(IILoc, diag::err_typename_nested_not_found) 516 << II << DC << SS->getRange(); 517 else if (isDependentScopeSpecifier(*SS)) { 518 unsigned DiagID = diag::err_typename_missing; 519 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 520 DiagID = diag::warn_typename_missing; 521 522 Diag(SS->getRange().getBegin(), DiagID) 523 << SS->getScopeRep() << II->getName() 524 << SourceRange(SS->getRange().getBegin(), IILoc) 525 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 526 SuggestedType = ActOnTypenameType(S, SourceLocation(), 527 *SS, *II, IILoc).get(); 528 } else { 529 assert(SS && SS->isInvalid() && 530 "Invalid scope specifier has already been diagnosed"); 531 } 532 533 return true; 534 } 535 536 /// \brief Determine whether the given result set contains either a type name 537 /// or 538 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 539 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 540 NextToken.is(tok::less); 541 542 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 543 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 544 return true; 545 546 if (CheckTemplate && isa<TemplateDecl>(*I)) 547 return true; 548 } 549 550 return false; 551 } 552 553 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 554 Scope *S, CXXScopeSpec &SS, 555 IdentifierInfo *&Name, 556 SourceLocation NameLoc) { 557 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 558 SemaRef.LookupParsedName(R, S, &SS); 559 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 560 StringRef FixItTagName; 561 switch (Tag->getTagKind()) { 562 case TTK_Class: 563 FixItTagName = "class "; 564 break; 565 566 case TTK_Enum: 567 FixItTagName = "enum "; 568 break; 569 570 case TTK_Struct: 571 FixItTagName = "struct "; 572 break; 573 574 case TTK_Interface: 575 FixItTagName = "__interface "; 576 break; 577 578 case TTK_Union: 579 FixItTagName = "union "; 580 break; 581 } 582 583 StringRef TagName = FixItTagName.drop_back(); 584 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 585 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 586 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 587 588 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 589 I != IEnd; ++I) 590 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 591 << Name << TagName; 592 593 // Replace lookup results with just the tag decl. 594 Result.clear(Sema::LookupTagName); 595 SemaRef.LookupParsedName(Result, S, &SS); 596 return true; 597 } 598 599 return false; 600 } 601 602 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 603 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 604 QualType T, SourceLocation NameLoc) { 605 ASTContext &Context = S.Context; 606 607 TypeLocBuilder Builder; 608 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 609 610 T = S.getElaboratedType(ETK_None, SS, T); 611 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 612 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 613 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 614 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 615 } 616 617 Sema::NameClassification Sema::ClassifyName(Scope *S, 618 CXXScopeSpec &SS, 619 IdentifierInfo *&Name, 620 SourceLocation NameLoc, 621 const Token &NextToken, 622 bool IsAddressOfOperand, 623 CorrectionCandidateCallback *CCC) { 624 DeclarationNameInfo NameInfo(Name, NameLoc); 625 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 626 627 if (NextToken.is(tok::coloncolon)) { 628 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 629 QualType(), false, SS, nullptr, false); 630 } 631 632 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 633 LookupParsedName(Result, S, &SS, !CurMethod); 634 635 // Perform lookup for Objective-C instance variables (including automatically 636 // synthesized instance variables), if we're in an Objective-C method. 637 // FIXME: This lookup really, really needs to be folded in to the normal 638 // unqualified lookup mechanism. 639 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 640 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 641 if (E.get() || E.isInvalid()) 642 return E; 643 } 644 645 bool SecondTry = false; 646 bool IsFilteredTemplateName = false; 647 648 Corrected: 649 switch (Result.getResultKind()) { 650 case LookupResult::NotFound: 651 // If an unqualified-id is followed by a '(', then we have a function 652 // call. 653 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 654 // In C++, this is an ADL-only call. 655 // FIXME: Reference? 656 if (getLangOpts().CPlusPlus) 657 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 658 659 // C90 6.3.2.2: 660 // If the expression that precedes the parenthesized argument list in a 661 // function call consists solely of an identifier, and if no 662 // declaration is visible for this identifier, the identifier is 663 // implicitly declared exactly as if, in the innermost block containing 664 // the function call, the declaration 665 // 666 // extern int identifier (); 667 // 668 // appeared. 669 // 670 // We also allow this in C99 as an extension. 671 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 672 Result.addDecl(D); 673 Result.resolveKind(); 674 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 675 } 676 } 677 678 // In C, we first see whether there is a tag type by the same name, in 679 // which case it's likely that the user just forget to write "enum", 680 // "struct", or "union". 681 if (!getLangOpts().CPlusPlus && !SecondTry && 682 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 683 break; 684 } 685 686 // Perform typo correction to determine if there is another name that is 687 // close to this name. 688 if (!SecondTry && CCC) { 689 SecondTry = true; 690 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 691 Result.getLookupKind(), S, 692 &SS, *CCC, 693 CTK_ErrorRecovery)) { 694 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 695 unsigned QualifiedDiag = diag::err_no_member_suggest; 696 697 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 698 NamedDecl *UnderlyingFirstDecl 699 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 700 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 701 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 702 UnqualifiedDiag = diag::err_no_template_suggest; 703 QualifiedDiag = diag::err_no_member_template_suggest; 704 } else if (UnderlyingFirstDecl && 705 (isa<TypeDecl>(UnderlyingFirstDecl) || 706 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 707 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 708 UnqualifiedDiag = diag::err_unknown_typename_suggest; 709 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 710 } 711 712 if (SS.isEmpty()) { 713 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 714 } else {// FIXME: is this even reachable? Test it. 715 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 716 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 717 Name->getName().equals(CorrectedStr); 718 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 719 << Name << computeDeclContext(SS, false) 720 << DroppedSpecifier << SS.getRange()); 721 } 722 723 // Update the name, so that the caller has the new name. 724 Name = Corrected.getCorrectionAsIdentifierInfo(); 725 726 // Typo correction corrected to a keyword. 727 if (Corrected.isKeyword()) 728 return Name; 729 730 // Also update the LookupResult... 731 // FIXME: This should probably go away at some point 732 Result.clear(); 733 Result.setLookupName(Corrected.getCorrection()); 734 if (FirstDecl) 735 Result.addDecl(FirstDecl); 736 737 // If we found an Objective-C instance variable, let 738 // LookupInObjCMethod build the appropriate expression to 739 // reference the ivar. 740 // FIXME: This is a gross hack. 741 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 742 Result.clear(); 743 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 744 return E; 745 } 746 747 goto Corrected; 748 } 749 } 750 751 // We failed to correct; just fall through and let the parser deal with it. 752 Result.suppressDiagnostics(); 753 return NameClassification::Unknown(); 754 755 case LookupResult::NotFoundInCurrentInstantiation: { 756 // We performed name lookup into the current instantiation, and there were 757 // dependent bases, so we treat this result the same way as any other 758 // dependent nested-name-specifier. 759 760 // C++ [temp.res]p2: 761 // A name used in a template declaration or definition and that is 762 // dependent on a template-parameter is assumed not to name a type 763 // unless the applicable name lookup finds a type name or the name is 764 // qualified by the keyword typename. 765 // 766 // FIXME: If the next token is '<', we might want to ask the parser to 767 // perform some heroics to see if we actually have a 768 // template-argument-list, which would indicate a missing 'template' 769 // keyword here. 770 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 771 NameInfo, IsAddressOfOperand, 772 /*TemplateArgs=*/nullptr); 773 } 774 775 case LookupResult::Found: 776 case LookupResult::FoundOverloaded: 777 case LookupResult::FoundUnresolvedValue: 778 break; 779 780 case LookupResult::Ambiguous: 781 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 782 hasAnyAcceptableTemplateNames(Result)) { 783 // C++ [temp.local]p3: 784 // A lookup that finds an injected-class-name (10.2) can result in an 785 // ambiguity in certain cases (for example, if it is found in more than 786 // one base class). If all of the injected-class-names that are found 787 // refer to specializations of the same class template, and if the name 788 // is followed by a template-argument-list, the reference refers to the 789 // class template itself and not a specialization thereof, and is not 790 // ambiguous. 791 // 792 // This filtering can make an ambiguous result into an unambiguous one, 793 // so try again after filtering out template names. 794 FilterAcceptableTemplateNames(Result); 795 if (!Result.isAmbiguous()) { 796 IsFilteredTemplateName = true; 797 break; 798 } 799 } 800 801 // Diagnose the ambiguity and return an error. 802 return NameClassification::Error(); 803 } 804 805 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 806 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 807 // C++ [temp.names]p3: 808 // After name lookup (3.4) finds that a name is a template-name or that 809 // an operator-function-id or a literal- operator-id refers to a set of 810 // overloaded functions any member of which is a function template if 811 // this is followed by a <, the < is always taken as the delimiter of a 812 // template-argument-list and never as the less-than operator. 813 if (!IsFilteredTemplateName) 814 FilterAcceptableTemplateNames(Result); 815 816 if (!Result.empty()) { 817 bool IsFunctionTemplate; 818 bool IsVarTemplate; 819 TemplateName Template; 820 if (Result.end() - Result.begin() > 1) { 821 IsFunctionTemplate = true; 822 Template = Context.getOverloadedTemplateName(Result.begin(), 823 Result.end()); 824 } else { 825 TemplateDecl *TD 826 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 827 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 828 IsVarTemplate = isa<VarTemplateDecl>(TD); 829 830 if (SS.isSet() && !SS.isInvalid()) 831 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 832 /*TemplateKeyword=*/false, 833 TD); 834 else 835 Template = TemplateName(TD); 836 } 837 838 if (IsFunctionTemplate) { 839 // Function templates always go through overload resolution, at which 840 // point we'll perform the various checks (e.g., accessibility) we need 841 // to based on which function we selected. 842 Result.suppressDiagnostics(); 843 844 return NameClassification::FunctionTemplate(Template); 845 } 846 847 return IsVarTemplate ? NameClassification::VarTemplate(Template) 848 : NameClassification::TypeTemplate(Template); 849 } 850 } 851 852 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 853 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 854 DiagnoseUseOfDecl(Type, NameLoc); 855 QualType T = Context.getTypeDeclType(Type); 856 if (SS.isNotEmpty()) 857 return buildNestedType(*this, SS, T, NameLoc); 858 return ParsedType::make(T); 859 } 860 861 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 862 if (!Class) { 863 // FIXME: It's unfortunate that we don't have a Type node for handling this. 864 if (ObjCCompatibleAliasDecl *Alias = 865 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 866 Class = Alias->getClassInterface(); 867 } 868 869 if (Class) { 870 DiagnoseUseOfDecl(Class, NameLoc); 871 872 if (NextToken.is(tok::period)) { 873 // Interface. <something> is parsed as a property reference expression. 874 // Just return "unknown" as a fall-through for now. 875 Result.suppressDiagnostics(); 876 return NameClassification::Unknown(); 877 } 878 879 QualType T = Context.getObjCInterfaceType(Class); 880 return ParsedType::make(T); 881 } 882 883 // We can have a type template here if we're classifying a template argument. 884 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 885 return NameClassification::TypeTemplate( 886 TemplateName(cast<TemplateDecl>(FirstDecl))); 887 888 // Check for a tag type hidden by a non-type decl in a few cases where it 889 // seems likely a type is wanted instead of the non-type that was found. 890 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 891 if ((NextToken.is(tok::identifier) || 892 (NextIsOp && 893 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 894 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 895 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 896 DiagnoseUseOfDecl(Type, NameLoc); 897 QualType T = Context.getTypeDeclType(Type); 898 if (SS.isNotEmpty()) 899 return buildNestedType(*this, SS, T, NameLoc); 900 return ParsedType::make(T); 901 } 902 903 if (FirstDecl->isCXXClassMember()) 904 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 905 nullptr); 906 907 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 908 return BuildDeclarationNameExpr(SS, Result, ADL); 909 } 910 911 // Determines the context to return to after temporarily entering a 912 // context. This depends in an unnecessarily complicated way on the 913 // exact ordering of callbacks from the parser. 914 DeclContext *Sema::getContainingDC(DeclContext *DC) { 915 916 // Functions defined inline within classes aren't parsed until we've 917 // finished parsing the top-level class, so the top-level class is 918 // the context we'll need to return to. 919 // A Lambda call operator whose parent is a class must not be treated 920 // as an inline member function. A Lambda can be used legally 921 // either as an in-class member initializer or a default argument. These 922 // are parsed once the class has been marked complete and so the containing 923 // context would be the nested class (when the lambda is defined in one); 924 // If the class is not complete, then the lambda is being used in an 925 // ill-formed fashion (such as to specify the width of a bit-field, or 926 // in an array-bound) - in which case we still want to return the 927 // lexically containing DC (which could be a nested class). 928 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 929 DC = DC->getLexicalParent(); 930 931 // A function not defined within a class will always return to its 932 // lexical context. 933 if (!isa<CXXRecordDecl>(DC)) 934 return DC; 935 936 // A C++ inline method/friend is parsed *after* the topmost class 937 // it was declared in is fully parsed ("complete"); the topmost 938 // class is the context we need to return to. 939 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 940 DC = RD; 941 942 // Return the declaration context of the topmost class the inline method is 943 // declared in. 944 return DC; 945 } 946 947 return DC->getLexicalParent(); 948 } 949 950 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 951 assert(getContainingDC(DC) == CurContext && 952 "The next DeclContext should be lexically contained in the current one."); 953 CurContext = DC; 954 S->setEntity(DC); 955 } 956 957 void Sema::PopDeclContext() { 958 assert(CurContext && "DeclContext imbalance!"); 959 960 CurContext = getContainingDC(CurContext); 961 assert(CurContext && "Popped translation unit!"); 962 } 963 964 /// EnterDeclaratorContext - Used when we must lookup names in the context 965 /// of a declarator's nested name specifier. 966 /// 967 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 968 // C++0x [basic.lookup.unqual]p13: 969 // A name used in the definition of a static data member of class 970 // X (after the qualified-id of the static member) is looked up as 971 // if the name was used in a member function of X. 972 // C++0x [basic.lookup.unqual]p14: 973 // If a variable member of a namespace is defined outside of the 974 // scope of its namespace then any name used in the definition of 975 // the variable member (after the declarator-id) is looked up as 976 // if the definition of the variable member occurred in its 977 // namespace. 978 // Both of these imply that we should push a scope whose context 979 // is the semantic context of the declaration. We can't use 980 // PushDeclContext here because that context is not necessarily 981 // lexically contained in the current context. Fortunately, 982 // the containing scope should have the appropriate information. 983 984 assert(!S->getEntity() && "scope already has entity"); 985 986 #ifndef NDEBUG 987 Scope *Ancestor = S->getParent(); 988 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 989 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 990 #endif 991 992 CurContext = DC; 993 S->setEntity(DC); 994 } 995 996 void Sema::ExitDeclaratorContext(Scope *S) { 997 assert(S->getEntity() == CurContext && "Context imbalance!"); 998 999 // Switch back to the lexical context. The safety of this is 1000 // enforced by an assert in EnterDeclaratorContext. 1001 Scope *Ancestor = S->getParent(); 1002 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1003 CurContext = Ancestor->getEntity(); 1004 1005 // We don't need to do anything with the scope, which is going to 1006 // disappear. 1007 } 1008 1009 1010 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1011 // We assume that the caller has already called 1012 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1013 FunctionDecl *FD = D->getAsFunction(); 1014 if (!FD) 1015 return; 1016 1017 // Same implementation as PushDeclContext, but enters the context 1018 // from the lexical parent, rather than the top-level class. 1019 assert(CurContext == FD->getLexicalParent() && 1020 "The next DeclContext should be lexically contained in the current one."); 1021 CurContext = FD; 1022 S->setEntity(CurContext); 1023 1024 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1025 ParmVarDecl *Param = FD->getParamDecl(P); 1026 // If the parameter has an identifier, then add it to the scope 1027 if (Param->getIdentifier()) { 1028 S->AddDecl(Param); 1029 IdResolver.AddDecl(Param); 1030 } 1031 } 1032 } 1033 1034 1035 void Sema::ActOnExitFunctionContext() { 1036 // Same implementation as PopDeclContext, but returns to the lexical parent, 1037 // rather than the top-level class. 1038 assert(CurContext && "DeclContext imbalance!"); 1039 CurContext = CurContext->getLexicalParent(); 1040 assert(CurContext && "Popped translation unit!"); 1041 } 1042 1043 1044 /// \brief Determine whether we allow overloading of the function 1045 /// PrevDecl with another declaration. 1046 /// 1047 /// This routine determines whether overloading is possible, not 1048 /// whether some new function is actually an overload. It will return 1049 /// true in C++ (where we can always provide overloads) or, as an 1050 /// extension, in C when the previous function is already an 1051 /// overloaded function declaration or has the "overloadable" 1052 /// attribute. 1053 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1054 ASTContext &Context) { 1055 if (Context.getLangOpts().CPlusPlus) 1056 return true; 1057 1058 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1059 return true; 1060 1061 return (Previous.getResultKind() == LookupResult::Found 1062 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1063 } 1064 1065 /// Add this decl to the scope shadowed decl chains. 1066 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1067 // Move up the scope chain until we find the nearest enclosing 1068 // non-transparent context. The declaration will be introduced into this 1069 // scope. 1070 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1071 S = S->getParent(); 1072 1073 // Add scoped declarations into their context, so that they can be 1074 // found later. Declarations without a context won't be inserted 1075 // into any context. 1076 if (AddToContext) 1077 CurContext->addDecl(D); 1078 1079 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1080 // are function-local declarations. 1081 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1082 !D->getDeclContext()->getRedeclContext()->Equals( 1083 D->getLexicalDeclContext()->getRedeclContext()) && 1084 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1085 return; 1086 1087 // Template instantiations should also not be pushed into scope. 1088 if (isa<FunctionDecl>(D) && 1089 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1090 return; 1091 1092 // If this replaces anything in the current scope, 1093 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1094 IEnd = IdResolver.end(); 1095 for (; I != IEnd; ++I) { 1096 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1097 S->RemoveDecl(*I); 1098 IdResolver.RemoveDecl(*I); 1099 1100 // Should only need to replace one decl. 1101 break; 1102 } 1103 } 1104 1105 S->AddDecl(D); 1106 1107 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1108 // Implicitly-generated labels may end up getting generated in an order that 1109 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1110 // the label at the appropriate place in the identifier chain. 1111 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1112 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1113 if (IDC == CurContext) { 1114 if (!S->isDeclScope(*I)) 1115 continue; 1116 } else if (IDC->Encloses(CurContext)) 1117 break; 1118 } 1119 1120 IdResolver.InsertDeclAfter(I, D); 1121 } else { 1122 IdResolver.AddDecl(D); 1123 } 1124 } 1125 1126 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1127 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1128 TUScope->AddDecl(D); 1129 } 1130 1131 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1132 bool AllowInlineNamespace) { 1133 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1134 } 1135 1136 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1137 DeclContext *TargetDC = DC->getPrimaryContext(); 1138 do { 1139 if (DeclContext *ScopeDC = S->getEntity()) 1140 if (ScopeDC->getPrimaryContext() == TargetDC) 1141 return S; 1142 } while ((S = S->getParent())); 1143 1144 return nullptr; 1145 } 1146 1147 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1148 DeclContext*, 1149 ASTContext&); 1150 1151 /// Filters out lookup results that don't fall within the given scope 1152 /// as determined by isDeclInScope. 1153 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1154 bool ConsiderLinkage, 1155 bool AllowInlineNamespace) { 1156 LookupResult::Filter F = R.makeFilter(); 1157 while (F.hasNext()) { 1158 NamedDecl *D = F.next(); 1159 1160 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1161 continue; 1162 1163 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1164 continue; 1165 1166 F.erase(); 1167 } 1168 1169 F.done(); 1170 } 1171 1172 static bool isUsingDecl(NamedDecl *D) { 1173 return isa<UsingShadowDecl>(D) || 1174 isa<UnresolvedUsingTypenameDecl>(D) || 1175 isa<UnresolvedUsingValueDecl>(D); 1176 } 1177 1178 /// Removes using shadow declarations from the lookup results. 1179 static void RemoveUsingDecls(LookupResult &R) { 1180 LookupResult::Filter F = R.makeFilter(); 1181 while (F.hasNext()) 1182 if (isUsingDecl(F.next())) 1183 F.erase(); 1184 1185 F.done(); 1186 } 1187 1188 /// \brief Check for this common pattern: 1189 /// @code 1190 /// class S { 1191 /// S(const S&); // DO NOT IMPLEMENT 1192 /// void operator=(const S&); // DO NOT IMPLEMENT 1193 /// }; 1194 /// @endcode 1195 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1196 // FIXME: Should check for private access too but access is set after we get 1197 // the decl here. 1198 if (D->doesThisDeclarationHaveABody()) 1199 return false; 1200 1201 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1202 return CD->isCopyConstructor(); 1203 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1204 return Method->isCopyAssignmentOperator(); 1205 return false; 1206 } 1207 1208 // We need this to handle 1209 // 1210 // typedef struct { 1211 // void *foo() { return 0; } 1212 // } A; 1213 // 1214 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1215 // for example. If 'A', foo will have external linkage. If we have '*A', 1216 // foo will have no linkage. Since we can't know until we get to the end 1217 // of the typedef, this function finds out if D might have non-external linkage. 1218 // Callers should verify at the end of the TU if it D has external linkage or 1219 // not. 1220 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1221 const DeclContext *DC = D->getDeclContext(); 1222 while (!DC->isTranslationUnit()) { 1223 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1224 if (!RD->hasNameForLinkage()) 1225 return true; 1226 } 1227 DC = DC->getParent(); 1228 } 1229 1230 return !D->isExternallyVisible(); 1231 } 1232 1233 // FIXME: This needs to be refactored; some other isInMainFile users want 1234 // these semantics. 1235 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1236 if (S.TUKind != TU_Complete) 1237 return false; 1238 return S.SourceMgr.isInMainFile(Loc); 1239 } 1240 1241 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1242 assert(D); 1243 1244 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1245 return false; 1246 1247 // Ignore all entities declared within templates, and out-of-line definitions 1248 // of members of class templates. 1249 if (D->getDeclContext()->isDependentContext() || 1250 D->getLexicalDeclContext()->isDependentContext()) 1251 return false; 1252 1253 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1254 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1255 return false; 1256 1257 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1258 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1259 return false; 1260 } else { 1261 // 'static inline' functions are defined in headers; don't warn. 1262 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1263 return false; 1264 } 1265 1266 if (FD->doesThisDeclarationHaveABody() && 1267 Context.DeclMustBeEmitted(FD)) 1268 return false; 1269 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1270 // Constants and utility variables are defined in headers with internal 1271 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1272 // like "inline".) 1273 if (!isMainFileLoc(*this, VD->getLocation())) 1274 return false; 1275 1276 if (Context.DeclMustBeEmitted(VD)) 1277 return false; 1278 1279 if (VD->isStaticDataMember() && 1280 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1281 return false; 1282 } else { 1283 return false; 1284 } 1285 1286 // Only warn for unused decls internal to the translation unit. 1287 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1288 // for inline functions defined in the main source file, for instance. 1289 return mightHaveNonExternalLinkage(D); 1290 } 1291 1292 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1293 if (!D) 1294 return; 1295 1296 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1297 const FunctionDecl *First = FD->getFirstDecl(); 1298 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1299 return; // First should already be in the vector. 1300 } 1301 1302 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1303 const VarDecl *First = VD->getFirstDecl(); 1304 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1305 return; // First should already be in the vector. 1306 } 1307 1308 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1309 UnusedFileScopedDecls.push_back(D); 1310 } 1311 1312 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1313 if (D->isInvalidDecl()) 1314 return false; 1315 1316 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1317 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1318 return false; 1319 1320 if (isa<LabelDecl>(D)) 1321 return true; 1322 1323 // White-list anything that isn't a local variable. 1324 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 1325 !D->getDeclContext()->isFunctionOrMethod()) 1326 return false; 1327 1328 // Types of valid local variables should be complete, so this should succeed. 1329 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1330 1331 // White-list anything with an __attribute__((unused)) type. 1332 QualType Ty = VD->getType(); 1333 1334 // Only look at the outermost level of typedef. 1335 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1336 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1337 return false; 1338 } 1339 1340 // If we failed to complete the type for some reason, or if the type is 1341 // dependent, don't diagnose the variable. 1342 if (Ty->isIncompleteType() || Ty->isDependentType()) 1343 return false; 1344 1345 if (const TagType *TT = Ty->getAs<TagType>()) { 1346 const TagDecl *Tag = TT->getDecl(); 1347 if (Tag->hasAttr<UnusedAttr>()) 1348 return false; 1349 1350 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1351 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1352 return false; 1353 1354 if (const Expr *Init = VD->getInit()) { 1355 if (const ExprWithCleanups *Cleanups = 1356 dyn_cast<ExprWithCleanups>(Init)) 1357 Init = Cleanups->getSubExpr(); 1358 const CXXConstructExpr *Construct = 1359 dyn_cast<CXXConstructExpr>(Init); 1360 if (Construct && !Construct->isElidable()) { 1361 CXXConstructorDecl *CD = Construct->getConstructor(); 1362 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1363 return false; 1364 } 1365 } 1366 } 1367 } 1368 1369 // TODO: __attribute__((unused)) templates? 1370 } 1371 1372 return true; 1373 } 1374 1375 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1376 FixItHint &Hint) { 1377 if (isa<LabelDecl>(D)) { 1378 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1379 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1380 if (AfterColon.isInvalid()) 1381 return; 1382 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1383 getCharRange(D->getLocStart(), AfterColon)); 1384 } 1385 return; 1386 } 1387 1388 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1389 /// unless they are marked attr(unused). 1390 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1391 if (!ShouldDiagnoseUnusedDecl(D)) 1392 return; 1393 1394 FixItHint Hint; 1395 GenerateFixForUnusedDecl(D, Context, Hint); 1396 1397 unsigned DiagID; 1398 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1399 DiagID = diag::warn_unused_exception_param; 1400 else if (isa<LabelDecl>(D)) 1401 DiagID = diag::warn_unused_label; 1402 else 1403 DiagID = diag::warn_unused_variable; 1404 1405 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1406 } 1407 1408 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1409 // Verify that we have no forward references left. If so, there was a goto 1410 // or address of a label taken, but no definition of it. Label fwd 1411 // definitions are indicated with a null substmt. 1412 if (L->getStmt() == nullptr) 1413 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1414 } 1415 1416 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1417 S->mergeNRVOIntoParent(); 1418 1419 if (S->decl_empty()) return; 1420 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1421 "Scope shouldn't contain decls!"); 1422 1423 for (auto *TmpD : S->decls()) { 1424 assert(TmpD && "This decl didn't get pushed??"); 1425 1426 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1427 NamedDecl *D = cast<NamedDecl>(TmpD); 1428 1429 if (!D->getDeclName()) continue; 1430 1431 // Diagnose unused variables in this scope. 1432 if (!S->hasUnrecoverableErrorOccurred()) 1433 DiagnoseUnusedDecl(D); 1434 1435 // If this was a forward reference to a label, verify it was defined. 1436 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1437 CheckPoppedLabel(LD, *this); 1438 1439 // Remove this name from our lexical scope. 1440 IdResolver.RemoveDecl(D); 1441 } 1442 } 1443 1444 /// \brief Look for an Objective-C class in the translation unit. 1445 /// 1446 /// \param Id The name of the Objective-C class we're looking for. If 1447 /// typo-correction fixes this name, the Id will be updated 1448 /// to the fixed name. 1449 /// 1450 /// \param IdLoc The location of the name in the translation unit. 1451 /// 1452 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1453 /// if there is no class with the given name. 1454 /// 1455 /// \returns The declaration of the named Objective-C class, or NULL if the 1456 /// class could not be found. 1457 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1458 SourceLocation IdLoc, 1459 bool DoTypoCorrection) { 1460 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1461 // creation from this context. 1462 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1463 1464 if (!IDecl && DoTypoCorrection) { 1465 // Perform typo correction at the given location, but only if we 1466 // find an Objective-C class name. 1467 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1468 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1469 LookupOrdinaryName, TUScope, nullptr, 1470 Validator, CTK_ErrorRecovery)) { 1471 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1472 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1473 Id = IDecl->getIdentifier(); 1474 } 1475 } 1476 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1477 // This routine must always return a class definition, if any. 1478 if (Def && Def->getDefinition()) 1479 Def = Def->getDefinition(); 1480 return Def; 1481 } 1482 1483 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1484 /// from S, where a non-field would be declared. This routine copes 1485 /// with the difference between C and C++ scoping rules in structs and 1486 /// unions. For example, the following code is well-formed in C but 1487 /// ill-formed in C++: 1488 /// @code 1489 /// struct S6 { 1490 /// enum { BAR } e; 1491 /// }; 1492 /// 1493 /// void test_S6() { 1494 /// struct S6 a; 1495 /// a.e = BAR; 1496 /// } 1497 /// @endcode 1498 /// For the declaration of BAR, this routine will return a different 1499 /// scope. The scope S will be the scope of the unnamed enumeration 1500 /// within S6. In C++, this routine will return the scope associated 1501 /// with S6, because the enumeration's scope is a transparent 1502 /// context but structures can contain non-field names. In C, this 1503 /// routine will return the translation unit scope, since the 1504 /// enumeration's scope is a transparent context and structures cannot 1505 /// contain non-field names. 1506 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1507 while (((S->getFlags() & Scope::DeclScope) == 0) || 1508 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1509 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1510 S = S->getParent(); 1511 return S; 1512 } 1513 1514 /// \brief Looks up the declaration of "struct objc_super" and 1515 /// saves it for later use in building builtin declaration of 1516 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1517 /// pre-existing declaration exists no action takes place. 1518 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1519 IdentifierInfo *II) { 1520 if (!II->isStr("objc_msgSendSuper")) 1521 return; 1522 ASTContext &Context = ThisSema.Context; 1523 1524 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1525 SourceLocation(), Sema::LookupTagName); 1526 ThisSema.LookupName(Result, S); 1527 if (Result.getResultKind() == LookupResult::Found) 1528 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1529 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1530 } 1531 1532 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1533 /// file scope. lazily create a decl for it. ForRedeclaration is true 1534 /// if we're creating this built-in in anticipation of redeclaring the 1535 /// built-in. 1536 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 1537 Scope *S, bool ForRedeclaration, 1538 SourceLocation Loc) { 1539 LookupPredefedObjCSuperType(*this, S, II); 1540 1541 Builtin::ID BID = (Builtin::ID)bid; 1542 1543 ASTContext::GetBuiltinTypeError Error; 1544 QualType R = Context.GetBuiltinType(BID, Error); 1545 switch (Error) { 1546 case ASTContext::GE_None: 1547 // Okay 1548 break; 1549 1550 case ASTContext::GE_Missing_stdio: 1551 if (ForRedeclaration) 1552 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 1553 << Context.BuiltinInfo.GetName(BID); 1554 return nullptr; 1555 1556 case ASTContext::GE_Missing_setjmp: 1557 if (ForRedeclaration) 1558 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 1559 << Context.BuiltinInfo.GetName(BID); 1560 return nullptr; 1561 1562 case ASTContext::GE_Missing_ucontext: 1563 if (ForRedeclaration) 1564 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 1565 << Context.BuiltinInfo.GetName(BID); 1566 return nullptr; 1567 } 1568 1569 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 1570 Diag(Loc, diag::ext_implicit_lib_function_decl) 1571 << Context.BuiltinInfo.GetName(BID) 1572 << R; 1573 if (Context.BuiltinInfo.getHeaderName(BID) && 1574 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 1575 != DiagnosticsEngine::Ignored) 1576 Diag(Loc, diag::note_please_include_header) 1577 << Context.BuiltinInfo.getHeaderName(BID) 1578 << Context.BuiltinInfo.GetName(BID); 1579 } 1580 1581 DeclContext *Parent = Context.getTranslationUnitDecl(); 1582 if (getLangOpts().CPlusPlus) { 1583 LinkageSpecDecl *CLinkageDecl = 1584 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1585 LinkageSpecDecl::lang_c, false); 1586 CLinkageDecl->setImplicit(); 1587 Parent->addDecl(CLinkageDecl); 1588 Parent = CLinkageDecl; 1589 } 1590 1591 FunctionDecl *New = FunctionDecl::Create(Context, 1592 Parent, 1593 Loc, Loc, II, R, /*TInfo=*/nullptr, 1594 SC_Extern, 1595 false, 1596 /*hasPrototype=*/true); 1597 New->setImplicit(); 1598 1599 // Create Decl objects for each parameter, adding them to the 1600 // FunctionDecl. 1601 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1602 SmallVector<ParmVarDecl*, 16> Params; 1603 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1604 ParmVarDecl *parm = 1605 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1606 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1607 SC_None, nullptr); 1608 parm->setScopeInfo(0, i); 1609 Params.push_back(parm); 1610 } 1611 New->setParams(Params); 1612 } 1613 1614 AddKnownFunctionAttributes(New); 1615 RegisterLocallyScopedExternCDecl(New, S); 1616 1617 // TUScope is the translation-unit scope to insert this function into. 1618 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1619 // relate Scopes to DeclContexts, and probably eliminate CurContext 1620 // entirely, but we're not there yet. 1621 DeclContext *SavedContext = CurContext; 1622 CurContext = Parent; 1623 PushOnScopeChains(New, TUScope); 1624 CurContext = SavedContext; 1625 return New; 1626 } 1627 1628 /// \brief Filter out any previous declarations that the given declaration 1629 /// should not consider because they are not permitted to conflict, e.g., 1630 /// because they come from hidden sub-modules and do not refer to the same 1631 /// entity. 1632 static void filterNonConflictingPreviousDecls(ASTContext &context, 1633 NamedDecl *decl, 1634 LookupResult &previous){ 1635 // This is only interesting when modules are enabled. 1636 if (!context.getLangOpts().Modules) 1637 return; 1638 1639 // Empty sets are uninteresting. 1640 if (previous.empty()) 1641 return; 1642 1643 LookupResult::Filter filter = previous.makeFilter(); 1644 while (filter.hasNext()) { 1645 NamedDecl *old = filter.next(); 1646 1647 // Non-hidden declarations are never ignored. 1648 if (!old->isHidden()) 1649 continue; 1650 1651 if (!old->isExternallyVisible()) 1652 filter.erase(); 1653 } 1654 1655 filter.done(); 1656 } 1657 1658 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1659 QualType OldType; 1660 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1661 OldType = OldTypedef->getUnderlyingType(); 1662 else 1663 OldType = Context.getTypeDeclType(Old); 1664 QualType NewType = New->getUnderlyingType(); 1665 1666 if (NewType->isVariablyModifiedType()) { 1667 // Must not redefine a typedef with a variably-modified type. 1668 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1669 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1670 << Kind << NewType; 1671 if (Old->getLocation().isValid()) 1672 Diag(Old->getLocation(), diag::note_previous_definition); 1673 New->setInvalidDecl(); 1674 return true; 1675 } 1676 1677 if (OldType != NewType && 1678 !OldType->isDependentType() && 1679 !NewType->isDependentType() && 1680 !Context.hasSameType(OldType, NewType)) { 1681 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1682 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1683 << Kind << NewType << OldType; 1684 if (Old->getLocation().isValid()) 1685 Diag(Old->getLocation(), diag::note_previous_definition); 1686 New->setInvalidDecl(); 1687 return true; 1688 } 1689 return false; 1690 } 1691 1692 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1693 /// same name and scope as a previous declaration 'Old'. Figure out 1694 /// how to resolve this situation, merging decls or emitting 1695 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1696 /// 1697 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1698 // If the new decl is known invalid already, don't bother doing any 1699 // merging checks. 1700 if (New->isInvalidDecl()) return; 1701 1702 // Allow multiple definitions for ObjC built-in typedefs. 1703 // FIXME: Verify the underlying types are equivalent! 1704 if (getLangOpts().ObjC1) { 1705 const IdentifierInfo *TypeID = New->getIdentifier(); 1706 switch (TypeID->getLength()) { 1707 default: break; 1708 case 2: 1709 { 1710 if (!TypeID->isStr("id")) 1711 break; 1712 QualType T = New->getUnderlyingType(); 1713 if (!T->isPointerType()) 1714 break; 1715 if (!T->isVoidPointerType()) { 1716 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1717 if (!PT->isStructureType()) 1718 break; 1719 } 1720 Context.setObjCIdRedefinitionType(T); 1721 // Install the built-in type for 'id', ignoring the current definition. 1722 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1723 return; 1724 } 1725 case 5: 1726 if (!TypeID->isStr("Class")) 1727 break; 1728 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1729 // Install the built-in type for 'Class', ignoring the current definition. 1730 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1731 return; 1732 case 3: 1733 if (!TypeID->isStr("SEL")) 1734 break; 1735 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1736 // Install the built-in type for 'SEL', ignoring the current definition. 1737 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1738 return; 1739 } 1740 // Fall through - the typedef name was not a builtin type. 1741 } 1742 1743 // Verify the old decl was also a type. 1744 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1745 if (!Old) { 1746 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1747 << New->getDeclName(); 1748 1749 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1750 if (OldD->getLocation().isValid()) 1751 Diag(OldD->getLocation(), diag::note_previous_definition); 1752 1753 return New->setInvalidDecl(); 1754 } 1755 1756 // If the old declaration is invalid, just give up here. 1757 if (Old->isInvalidDecl()) 1758 return New->setInvalidDecl(); 1759 1760 // If the typedef types are not identical, reject them in all languages and 1761 // with any extensions enabled. 1762 if (isIncompatibleTypedef(Old, New)) 1763 return; 1764 1765 // The types match. Link up the redeclaration chain and merge attributes if 1766 // the old declaration was a typedef. 1767 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1768 New->setPreviousDecl(Typedef); 1769 mergeDeclAttributes(New, Old); 1770 } 1771 1772 if (getLangOpts().MicrosoftExt) 1773 return; 1774 1775 if (getLangOpts().CPlusPlus) { 1776 // C++ [dcl.typedef]p2: 1777 // In a given non-class scope, a typedef specifier can be used to 1778 // redefine the name of any type declared in that scope to refer 1779 // to the type to which it already refers. 1780 if (!isa<CXXRecordDecl>(CurContext)) 1781 return; 1782 1783 // C++0x [dcl.typedef]p4: 1784 // In a given class scope, a typedef specifier can be used to redefine 1785 // any class-name declared in that scope that is not also a typedef-name 1786 // to refer to the type to which it already refers. 1787 // 1788 // This wording came in via DR424, which was a correction to the 1789 // wording in DR56, which accidentally banned code like: 1790 // 1791 // struct S { 1792 // typedef struct A { } A; 1793 // }; 1794 // 1795 // in the C++03 standard. We implement the C++0x semantics, which 1796 // allow the above but disallow 1797 // 1798 // struct S { 1799 // typedef int I; 1800 // typedef int I; 1801 // }; 1802 // 1803 // since that was the intent of DR56. 1804 if (!isa<TypedefNameDecl>(Old)) 1805 return; 1806 1807 Diag(New->getLocation(), diag::err_redefinition) 1808 << New->getDeclName(); 1809 Diag(Old->getLocation(), diag::note_previous_definition); 1810 return New->setInvalidDecl(); 1811 } 1812 1813 // Modules always permit redefinition of typedefs, as does C11. 1814 if (getLangOpts().Modules || getLangOpts().C11) 1815 return; 1816 1817 // If we have a redefinition of a typedef in C, emit a warning. This warning 1818 // is normally mapped to an error, but can be controlled with 1819 // -Wtypedef-redefinition. If either the original or the redefinition is 1820 // in a system header, don't emit this for compatibility with GCC. 1821 if (getDiagnostics().getSuppressSystemWarnings() && 1822 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1823 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1824 return; 1825 1826 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 1827 << New->getDeclName(); 1828 Diag(Old->getLocation(), diag::note_previous_definition); 1829 return; 1830 } 1831 1832 /// DeclhasAttr - returns true if decl Declaration already has the target 1833 /// attribute. 1834 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1835 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1836 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1837 for (const auto *i : D->attrs()) 1838 if (i->getKind() == A->getKind()) { 1839 if (Ann) { 1840 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1841 return true; 1842 continue; 1843 } 1844 // FIXME: Don't hardcode this check 1845 if (OA && isa<OwnershipAttr>(i)) 1846 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 1847 return true; 1848 } 1849 1850 return false; 1851 } 1852 1853 static bool isAttributeTargetADefinition(Decl *D) { 1854 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 1855 return VD->isThisDeclarationADefinition(); 1856 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1857 return TD->isCompleteDefinition() || TD->isBeingDefined(); 1858 return true; 1859 } 1860 1861 /// Merge alignment attributes from \p Old to \p New, taking into account the 1862 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 1863 /// 1864 /// \return \c true if any attributes were added to \p New. 1865 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 1866 // Look for alignas attributes on Old, and pick out whichever attribute 1867 // specifies the strictest alignment requirement. 1868 AlignedAttr *OldAlignasAttr = nullptr; 1869 AlignedAttr *OldStrictestAlignAttr = nullptr; 1870 unsigned OldAlign = 0; 1871 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 1872 // FIXME: We have no way of representing inherited dependent alignments 1873 // in a case like: 1874 // template<int A, int B> struct alignas(A) X; 1875 // template<int A, int B> struct alignas(B) X {}; 1876 // For now, we just ignore any alignas attributes which are not on the 1877 // definition in such a case. 1878 if (I->isAlignmentDependent()) 1879 return false; 1880 1881 if (I->isAlignas()) 1882 OldAlignasAttr = I; 1883 1884 unsigned Align = I->getAlignment(S.Context); 1885 if (Align > OldAlign) { 1886 OldAlign = Align; 1887 OldStrictestAlignAttr = I; 1888 } 1889 } 1890 1891 // Look for alignas attributes on New. 1892 AlignedAttr *NewAlignasAttr = nullptr; 1893 unsigned NewAlign = 0; 1894 for (auto *I : New->specific_attrs<AlignedAttr>()) { 1895 if (I->isAlignmentDependent()) 1896 return false; 1897 1898 if (I->isAlignas()) 1899 NewAlignasAttr = I; 1900 1901 unsigned Align = I->getAlignment(S.Context); 1902 if (Align > NewAlign) 1903 NewAlign = Align; 1904 } 1905 1906 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 1907 // Both declarations have 'alignas' attributes. We require them to match. 1908 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 1909 // fall short. (If two declarations both have alignas, they must both match 1910 // every definition, and so must match each other if there is a definition.) 1911 1912 // If either declaration only contains 'alignas(0)' specifiers, then it 1913 // specifies the natural alignment for the type. 1914 if (OldAlign == 0 || NewAlign == 0) { 1915 QualType Ty; 1916 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 1917 Ty = VD->getType(); 1918 else 1919 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 1920 1921 if (OldAlign == 0) 1922 OldAlign = S.Context.getTypeAlign(Ty); 1923 if (NewAlign == 0) 1924 NewAlign = S.Context.getTypeAlign(Ty); 1925 } 1926 1927 if (OldAlign != NewAlign) { 1928 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 1929 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 1930 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 1931 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 1932 } 1933 } 1934 1935 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 1936 // C++11 [dcl.align]p6: 1937 // if any declaration of an entity has an alignment-specifier, 1938 // every defining declaration of that entity shall specify an 1939 // equivalent alignment. 1940 // C11 6.7.5/7: 1941 // If the definition of an object does not have an alignment 1942 // specifier, any other declaration of that object shall also 1943 // have no alignment specifier. 1944 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 1945 << OldAlignasAttr; 1946 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 1947 << OldAlignasAttr; 1948 } 1949 1950 bool AnyAdded = false; 1951 1952 // Ensure we have an attribute representing the strictest alignment. 1953 if (OldAlign > NewAlign) { 1954 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 1955 Clone->setInherited(true); 1956 New->addAttr(Clone); 1957 AnyAdded = true; 1958 } 1959 1960 // Ensure we have an alignas attribute if the old declaration had one. 1961 if (OldAlignasAttr && !NewAlignasAttr && 1962 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 1963 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 1964 Clone->setInherited(true); 1965 New->addAttr(Clone); 1966 AnyAdded = true; 1967 } 1968 1969 return AnyAdded; 1970 } 1971 1972 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 1973 const InheritableAttr *Attr, bool Override) { 1974 InheritableAttr *NewAttr = nullptr; 1975 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 1976 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 1977 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 1978 AA->getIntroduced(), AA->getDeprecated(), 1979 AA->getObsoleted(), AA->getUnavailable(), 1980 AA->getMessage(), Override, 1981 AttrSpellingListIndex); 1982 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 1983 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1984 AttrSpellingListIndex); 1985 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 1986 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 1987 AttrSpellingListIndex); 1988 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 1989 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 1990 AttrSpellingListIndex); 1991 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 1992 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 1993 AttrSpellingListIndex); 1994 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 1995 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 1996 FA->getFormatIdx(), FA->getFirstArg(), 1997 AttrSpellingListIndex); 1998 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 1999 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2000 AttrSpellingListIndex); 2001 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2002 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2003 AttrSpellingListIndex, 2004 IA->getSemanticSpelling()); 2005 else if (isa<AlignedAttr>(Attr)) 2006 // AlignedAttrs are handled separately, because we need to handle all 2007 // such attributes on a declaration at the same time. 2008 NewAttr = nullptr; 2009 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2010 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2011 2012 if (NewAttr) { 2013 NewAttr->setInherited(true); 2014 D->addAttr(NewAttr); 2015 return true; 2016 } 2017 2018 return false; 2019 } 2020 2021 static const Decl *getDefinition(const Decl *D) { 2022 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2023 return TD->getDefinition(); 2024 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2025 const VarDecl *Def = VD->getDefinition(); 2026 if (Def) 2027 return Def; 2028 return VD->getActingDefinition(); 2029 } 2030 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2031 const FunctionDecl* Def; 2032 if (FD->isDefined(Def)) 2033 return Def; 2034 } 2035 return nullptr; 2036 } 2037 2038 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2039 for (const auto *Attribute : D->attrs()) 2040 if (Attribute->getKind() == Kind) 2041 return true; 2042 return false; 2043 } 2044 2045 /// checkNewAttributesAfterDef - If we already have a definition, check that 2046 /// there are no new attributes in this declaration. 2047 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2048 if (!New->hasAttrs()) 2049 return; 2050 2051 const Decl *Def = getDefinition(Old); 2052 if (!Def || Def == New) 2053 return; 2054 2055 AttrVec &NewAttributes = New->getAttrs(); 2056 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2057 const Attr *NewAttribute = NewAttributes[I]; 2058 2059 if (isa<AliasAttr>(NewAttribute)) { 2060 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2061 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2062 else { 2063 VarDecl *VD = cast<VarDecl>(New); 2064 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2065 VarDecl::TentativeDefinition 2066 ? diag::err_alias_after_tentative 2067 : diag::err_redefinition; 2068 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2069 S.Diag(Def->getLocation(), diag::note_previous_definition); 2070 VD->setInvalidDecl(); 2071 } 2072 ++I; 2073 continue; 2074 } 2075 2076 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2077 // Tentative definitions are only interesting for the alias check above. 2078 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2079 ++I; 2080 continue; 2081 } 2082 } 2083 2084 if (hasAttribute(Def, NewAttribute->getKind())) { 2085 ++I; 2086 continue; // regular attr merging will take care of validating this. 2087 } 2088 2089 if (isa<C11NoReturnAttr>(NewAttribute)) { 2090 // C's _Noreturn is allowed to be added to a function after it is defined. 2091 ++I; 2092 continue; 2093 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2094 if (AA->isAlignas()) { 2095 // C++11 [dcl.align]p6: 2096 // if any declaration of an entity has an alignment-specifier, 2097 // every defining declaration of that entity shall specify an 2098 // equivalent alignment. 2099 // C11 6.7.5/7: 2100 // If the definition of an object does not have an alignment 2101 // specifier, any other declaration of that object shall also 2102 // have no alignment specifier. 2103 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2104 << AA; 2105 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2106 << AA; 2107 NewAttributes.erase(NewAttributes.begin() + I); 2108 --E; 2109 continue; 2110 } 2111 } 2112 2113 S.Diag(NewAttribute->getLocation(), 2114 diag::warn_attribute_precede_definition); 2115 S.Diag(Def->getLocation(), diag::note_previous_definition); 2116 NewAttributes.erase(NewAttributes.begin() + I); 2117 --E; 2118 } 2119 } 2120 2121 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2122 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2123 AvailabilityMergeKind AMK) { 2124 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2125 UsedAttr *NewAttr = OldAttr->clone(Context); 2126 NewAttr->setInherited(true); 2127 New->addAttr(NewAttr); 2128 } 2129 2130 if (!Old->hasAttrs() && !New->hasAttrs()) 2131 return; 2132 2133 // attributes declared post-definition are currently ignored 2134 checkNewAttributesAfterDef(*this, New, Old); 2135 2136 if (!Old->hasAttrs()) 2137 return; 2138 2139 bool foundAny = New->hasAttrs(); 2140 2141 // Ensure that any moving of objects within the allocated map is done before 2142 // we process them. 2143 if (!foundAny) New->setAttrs(AttrVec()); 2144 2145 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2146 bool Override = false; 2147 // Ignore deprecated/unavailable/availability attributes if requested. 2148 if (isa<DeprecatedAttr>(I) || 2149 isa<UnavailableAttr>(I) || 2150 isa<AvailabilityAttr>(I)) { 2151 switch (AMK) { 2152 case AMK_None: 2153 continue; 2154 2155 case AMK_Redeclaration: 2156 break; 2157 2158 case AMK_Override: 2159 Override = true; 2160 break; 2161 } 2162 } 2163 2164 // Already handled. 2165 if (isa<UsedAttr>(I)) 2166 continue; 2167 2168 if (mergeDeclAttribute(*this, New, I, Override)) 2169 foundAny = true; 2170 } 2171 2172 if (mergeAlignedAttrs(*this, New, Old)) 2173 foundAny = true; 2174 2175 if (!foundAny) New->dropAttrs(); 2176 } 2177 2178 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2179 /// to the new one. 2180 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2181 const ParmVarDecl *oldDecl, 2182 Sema &S) { 2183 // C++11 [dcl.attr.depend]p2: 2184 // The first declaration of a function shall specify the 2185 // carries_dependency attribute for its declarator-id if any declaration 2186 // of the function specifies the carries_dependency attribute. 2187 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2188 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2189 S.Diag(CDA->getLocation(), 2190 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2191 // Find the first declaration of the parameter. 2192 // FIXME: Should we build redeclaration chains for function parameters? 2193 const FunctionDecl *FirstFD = 2194 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2195 const ParmVarDecl *FirstVD = 2196 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2197 S.Diag(FirstVD->getLocation(), 2198 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2199 } 2200 2201 if (!oldDecl->hasAttrs()) 2202 return; 2203 2204 bool foundAny = newDecl->hasAttrs(); 2205 2206 // Ensure that any moving of objects within the allocated map is 2207 // done before we process them. 2208 if (!foundAny) newDecl->setAttrs(AttrVec()); 2209 2210 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2211 if (!DeclHasAttr(newDecl, I)) { 2212 InheritableAttr *newAttr = 2213 cast<InheritableParamAttr>(I->clone(S.Context)); 2214 newAttr->setInherited(true); 2215 newDecl->addAttr(newAttr); 2216 foundAny = true; 2217 } 2218 } 2219 2220 if (!foundAny) newDecl->dropAttrs(); 2221 } 2222 2223 namespace { 2224 2225 /// Used in MergeFunctionDecl to keep track of function parameters in 2226 /// C. 2227 struct GNUCompatibleParamWarning { 2228 ParmVarDecl *OldParm; 2229 ParmVarDecl *NewParm; 2230 QualType PromotedType; 2231 }; 2232 2233 } 2234 2235 /// getSpecialMember - get the special member enum for a method. 2236 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2237 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2238 if (Ctor->isDefaultConstructor()) 2239 return Sema::CXXDefaultConstructor; 2240 2241 if (Ctor->isCopyConstructor()) 2242 return Sema::CXXCopyConstructor; 2243 2244 if (Ctor->isMoveConstructor()) 2245 return Sema::CXXMoveConstructor; 2246 } else if (isa<CXXDestructorDecl>(MD)) { 2247 return Sema::CXXDestructor; 2248 } else if (MD->isCopyAssignmentOperator()) { 2249 return Sema::CXXCopyAssignment; 2250 } else if (MD->isMoveAssignmentOperator()) { 2251 return Sema::CXXMoveAssignment; 2252 } 2253 2254 return Sema::CXXInvalid; 2255 } 2256 2257 /// canRedefineFunction - checks if a function can be redefined. Currently, 2258 /// only extern inline functions can be redefined, and even then only in 2259 /// GNU89 mode. 2260 static bool canRedefineFunction(const FunctionDecl *FD, 2261 const LangOptions& LangOpts) { 2262 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2263 !LangOpts.CPlusPlus && 2264 FD->isInlineSpecified() && 2265 FD->getStorageClass() == SC_Extern); 2266 } 2267 2268 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2269 const AttributedType *AT = T->getAs<AttributedType>(); 2270 while (AT && !AT->isCallingConv()) 2271 AT = AT->getModifiedType()->getAs<AttributedType>(); 2272 return AT; 2273 } 2274 2275 template <typename T> 2276 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2277 const DeclContext *DC = Old->getDeclContext(); 2278 if (DC->isRecord()) 2279 return false; 2280 2281 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2282 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2283 return true; 2284 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2285 return true; 2286 return false; 2287 } 2288 2289 /// MergeFunctionDecl - We just parsed a function 'New' from 2290 /// declarator D which has the same name and scope as a previous 2291 /// declaration 'Old'. Figure out how to resolve this situation, 2292 /// merging decls or emitting diagnostics as appropriate. 2293 /// 2294 /// In C++, New and Old must be declarations that are not 2295 /// overloaded. Use IsOverload to determine whether New and Old are 2296 /// overloaded, and to select the Old declaration that New should be 2297 /// merged with. 2298 /// 2299 /// Returns true if there was an error, false otherwise. 2300 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2301 Scope *S, bool MergeTypeWithOld) { 2302 // Verify the old decl was also a function. 2303 FunctionDecl *Old = OldD->getAsFunction(); 2304 if (!Old) { 2305 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2306 if (New->getFriendObjectKind()) { 2307 Diag(New->getLocation(), diag::err_using_decl_friend); 2308 Diag(Shadow->getTargetDecl()->getLocation(), 2309 diag::note_using_decl_target); 2310 Diag(Shadow->getUsingDecl()->getLocation(), 2311 diag::note_using_decl) << 0; 2312 return true; 2313 } 2314 2315 // C++11 [namespace.udecl]p14: 2316 // If a function declaration in namespace scope or block scope has the 2317 // same name and the same parameter-type-list as a function introduced 2318 // by a using-declaration, and the declarations do not declare the same 2319 // function, the program is ill-formed. 2320 2321 // Check whether the two declarations might declare the same function. 2322 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2323 if (Old && 2324 !Old->getDeclContext()->getRedeclContext()->Equals( 2325 New->getDeclContext()->getRedeclContext()) && 2326 !(Old->isExternC() && New->isExternC())) 2327 Old = nullptr; 2328 2329 if (!Old) { 2330 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2331 Diag(Shadow->getTargetDecl()->getLocation(), 2332 diag::note_using_decl_target); 2333 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2334 return true; 2335 } 2336 OldD = Old; 2337 } else { 2338 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2339 << New->getDeclName(); 2340 Diag(OldD->getLocation(), diag::note_previous_definition); 2341 return true; 2342 } 2343 } 2344 2345 // If the old declaration is invalid, just give up here. 2346 if (Old->isInvalidDecl()) 2347 return true; 2348 2349 // Determine whether the previous declaration was a definition, 2350 // implicit declaration, or a declaration. 2351 diag::kind PrevDiag; 2352 SourceLocation OldLocation = Old->getLocation(); 2353 if (Old->isThisDeclarationADefinition()) 2354 PrevDiag = diag::note_previous_definition; 2355 else if (Old->isImplicit()) { 2356 PrevDiag = diag::note_previous_implicit_declaration; 2357 if (OldLocation.isInvalid()) 2358 OldLocation = New->getLocation(); 2359 } else 2360 PrevDiag = diag::note_previous_declaration; 2361 2362 // Don't complain about this if we're in GNU89 mode and the old function 2363 // is an extern inline function. 2364 // Don't complain about specializations. They are not supposed to have 2365 // storage classes. 2366 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2367 New->getStorageClass() == SC_Static && 2368 Old->hasExternalFormalLinkage() && 2369 !New->getTemplateSpecializationInfo() && 2370 !canRedefineFunction(Old, getLangOpts())) { 2371 if (getLangOpts().MicrosoftExt) { 2372 Diag(New->getLocation(), diag::warn_static_non_static) << New; 2373 Diag(OldLocation, PrevDiag); 2374 } else { 2375 Diag(New->getLocation(), diag::err_static_non_static) << New; 2376 Diag(OldLocation, PrevDiag); 2377 return true; 2378 } 2379 } 2380 2381 2382 // If a function is first declared with a calling convention, but is later 2383 // declared or defined without one, all following decls assume the calling 2384 // convention of the first. 2385 // 2386 // It's OK if a function is first declared without a calling convention, 2387 // but is later declared or defined with the default calling convention. 2388 // 2389 // To test if either decl has an explicit calling convention, we look for 2390 // AttributedType sugar nodes on the type as written. If they are missing or 2391 // were canonicalized away, we assume the calling convention was implicit. 2392 // 2393 // Note also that we DO NOT return at this point, because we still have 2394 // other tests to run. 2395 QualType OldQType = Context.getCanonicalType(Old->getType()); 2396 QualType NewQType = Context.getCanonicalType(New->getType()); 2397 const FunctionType *OldType = cast<FunctionType>(OldQType); 2398 const FunctionType *NewType = cast<FunctionType>(NewQType); 2399 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2400 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2401 bool RequiresAdjustment = false; 2402 2403 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2404 FunctionDecl *First = Old->getFirstDecl(); 2405 const FunctionType *FT = 2406 First->getType().getCanonicalType()->castAs<FunctionType>(); 2407 FunctionType::ExtInfo FI = FT->getExtInfo(); 2408 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2409 if (!NewCCExplicit) { 2410 // Inherit the CC from the previous declaration if it was specified 2411 // there but not here. 2412 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2413 RequiresAdjustment = true; 2414 } else { 2415 // Calling conventions aren't compatible, so complain. 2416 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2417 Diag(New->getLocation(), diag::err_cconv_change) 2418 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2419 << !FirstCCExplicit 2420 << (!FirstCCExplicit ? "" : 2421 FunctionType::getNameForCallConv(FI.getCC())); 2422 2423 // Put the note on the first decl, since it is the one that matters. 2424 Diag(First->getLocation(), diag::note_previous_declaration); 2425 return true; 2426 } 2427 } 2428 2429 // FIXME: diagnose the other way around? 2430 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2431 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2432 RequiresAdjustment = true; 2433 } 2434 2435 // Merge regparm attribute. 2436 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2437 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2438 if (NewTypeInfo.getHasRegParm()) { 2439 Diag(New->getLocation(), diag::err_regparm_mismatch) 2440 << NewType->getRegParmType() 2441 << OldType->getRegParmType(); 2442 Diag(OldLocation, diag::note_previous_declaration); 2443 return true; 2444 } 2445 2446 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2447 RequiresAdjustment = true; 2448 } 2449 2450 // Merge ns_returns_retained attribute. 2451 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2452 if (NewTypeInfo.getProducesResult()) { 2453 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2454 Diag(OldLocation, diag::note_previous_declaration); 2455 return true; 2456 } 2457 2458 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2459 RequiresAdjustment = true; 2460 } 2461 2462 if (RequiresAdjustment) { 2463 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2464 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2465 New->setType(QualType(AdjustedType, 0)); 2466 NewQType = Context.getCanonicalType(New->getType()); 2467 NewType = cast<FunctionType>(NewQType); 2468 } 2469 2470 // If this redeclaration makes the function inline, we may need to add it to 2471 // UndefinedButUsed. 2472 if (!Old->isInlined() && New->isInlined() && 2473 !New->hasAttr<GNUInlineAttr>() && 2474 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2475 Old->isUsed(false) && 2476 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2477 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2478 SourceLocation())); 2479 2480 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2481 // about it. 2482 if (New->hasAttr<GNUInlineAttr>() && 2483 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2484 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2485 } 2486 2487 if (getLangOpts().CPlusPlus) { 2488 // (C++98 13.1p2): 2489 // Certain function declarations cannot be overloaded: 2490 // -- Function declarations that differ only in the return type 2491 // cannot be overloaded. 2492 2493 // Go back to the type source info to compare the declared return types, 2494 // per C++1y [dcl.type.auto]p13: 2495 // Redeclarations or specializations of a function or function template 2496 // with a declared return type that uses a placeholder type shall also 2497 // use that placeholder, not a deduced type. 2498 QualType OldDeclaredReturnType = 2499 (Old->getTypeSourceInfo() 2500 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2501 : OldType)->getReturnType(); 2502 QualType NewDeclaredReturnType = 2503 (New->getTypeSourceInfo() 2504 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2505 : NewType)->getReturnType(); 2506 QualType ResQT; 2507 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2508 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2509 New->isLocalExternDecl())) { 2510 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2511 OldDeclaredReturnType->isObjCObjectPointerType()) 2512 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2513 if (ResQT.isNull()) { 2514 if (New->isCXXClassMember() && New->isOutOfLine()) 2515 Diag(New->getLocation(), 2516 diag::err_member_def_does_not_match_ret_type) << New; 2517 else 2518 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 2519 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2520 return true; 2521 } 2522 else 2523 NewQType = ResQT; 2524 } 2525 2526 QualType OldReturnType = OldType->getReturnType(); 2527 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2528 if (OldReturnType != NewReturnType) { 2529 // If this function has a deduced return type and has already been 2530 // defined, copy the deduced value from the old declaration. 2531 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2532 if (OldAT && OldAT->isDeduced()) { 2533 New->setType( 2534 SubstAutoType(New->getType(), 2535 OldAT->isDependentType() ? Context.DependentTy 2536 : OldAT->getDeducedType())); 2537 NewQType = Context.getCanonicalType( 2538 SubstAutoType(NewQType, 2539 OldAT->isDependentType() ? Context.DependentTy 2540 : OldAT->getDeducedType())); 2541 } 2542 } 2543 2544 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2545 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2546 if (OldMethod && NewMethod) { 2547 // Preserve triviality. 2548 NewMethod->setTrivial(OldMethod->isTrivial()); 2549 2550 // MSVC allows explicit template specialization at class scope: 2551 // 2 CXXMethodDecls referring to the same function will be injected. 2552 // We don't want a redeclaration error. 2553 bool IsClassScopeExplicitSpecialization = 2554 OldMethod->isFunctionTemplateSpecialization() && 2555 NewMethod->isFunctionTemplateSpecialization(); 2556 bool isFriend = NewMethod->getFriendObjectKind(); 2557 2558 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2559 !IsClassScopeExplicitSpecialization) { 2560 // -- Member function declarations with the same name and the 2561 // same parameter types cannot be overloaded if any of them 2562 // is a static member function declaration. 2563 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2564 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2565 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2566 return true; 2567 } 2568 2569 // C++ [class.mem]p1: 2570 // [...] A member shall not be declared twice in the 2571 // member-specification, except that a nested class or member 2572 // class template can be declared and then later defined. 2573 if (ActiveTemplateInstantiations.empty()) { 2574 unsigned NewDiag; 2575 if (isa<CXXConstructorDecl>(OldMethod)) 2576 NewDiag = diag::err_constructor_redeclared; 2577 else if (isa<CXXDestructorDecl>(NewMethod)) 2578 NewDiag = diag::err_destructor_redeclared; 2579 else if (isa<CXXConversionDecl>(NewMethod)) 2580 NewDiag = diag::err_conv_function_redeclared; 2581 else 2582 NewDiag = diag::err_member_redeclared; 2583 2584 Diag(New->getLocation(), NewDiag); 2585 } else { 2586 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2587 << New << New->getType(); 2588 } 2589 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2590 2591 // Complain if this is an explicit declaration of a special 2592 // member that was initially declared implicitly. 2593 // 2594 // As an exception, it's okay to befriend such methods in order 2595 // to permit the implicit constructor/destructor/operator calls. 2596 } else if (OldMethod->isImplicit()) { 2597 if (isFriend) { 2598 NewMethod->setImplicit(); 2599 } else { 2600 Diag(NewMethod->getLocation(), 2601 diag::err_definition_of_implicitly_declared_member) 2602 << New << getSpecialMember(OldMethod); 2603 return true; 2604 } 2605 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2606 Diag(NewMethod->getLocation(), 2607 diag::err_definition_of_explicitly_defaulted_member) 2608 << getSpecialMember(OldMethod); 2609 return true; 2610 } 2611 } 2612 2613 // C++11 [dcl.attr.noreturn]p1: 2614 // The first declaration of a function shall specify the noreturn 2615 // attribute if any declaration of that function specifies the noreturn 2616 // attribute. 2617 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2618 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2619 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2620 Diag(Old->getFirstDecl()->getLocation(), 2621 diag::note_noreturn_missing_first_decl); 2622 } 2623 2624 // C++11 [dcl.attr.depend]p2: 2625 // The first declaration of a function shall specify the 2626 // carries_dependency attribute for its declarator-id if any declaration 2627 // of the function specifies the carries_dependency attribute. 2628 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2629 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2630 Diag(CDA->getLocation(), 2631 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2632 Diag(Old->getFirstDecl()->getLocation(), 2633 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2634 } 2635 2636 // (C++98 8.3.5p3): 2637 // All declarations for a function shall agree exactly in both the 2638 // return type and the parameter-type-list. 2639 // We also want to respect all the extended bits except noreturn. 2640 2641 // noreturn should now match unless the old type info didn't have it. 2642 QualType OldQTypeForComparison = OldQType; 2643 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2644 assert(OldQType == QualType(OldType, 0)); 2645 const FunctionType *OldTypeForComparison 2646 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2647 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2648 assert(OldQTypeForComparison.isCanonical()); 2649 } 2650 2651 if (haveIncompatibleLanguageLinkages(Old, New)) { 2652 // As a special case, retain the language linkage from previous 2653 // declarations of a friend function as an extension. 2654 // 2655 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2656 // and is useful because there's otherwise no way to specify language 2657 // linkage within class scope. 2658 // 2659 // Check cautiously as the friend object kind isn't yet complete. 2660 if (New->getFriendObjectKind() != Decl::FOK_None) { 2661 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2662 Diag(OldLocation, PrevDiag); 2663 } else { 2664 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2665 Diag(OldLocation, PrevDiag); 2666 return true; 2667 } 2668 } 2669 2670 if (OldQTypeForComparison == NewQType) 2671 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2672 2673 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2674 New->isLocalExternDecl()) { 2675 // It's OK if we couldn't merge types for a local function declaraton 2676 // if either the old or new type is dependent. We'll merge the types 2677 // when we instantiate the function. 2678 return false; 2679 } 2680 2681 // Fall through for conflicting redeclarations and redefinitions. 2682 } 2683 2684 // C: Function types need to be compatible, not identical. This handles 2685 // duplicate function decls like "void f(int); void f(enum X);" properly. 2686 if (!getLangOpts().CPlusPlus && 2687 Context.typesAreCompatible(OldQType, NewQType)) { 2688 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2689 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2690 const FunctionProtoType *OldProto = nullptr; 2691 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2692 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2693 // The old declaration provided a function prototype, but the 2694 // new declaration does not. Merge in the prototype. 2695 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2696 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2697 NewQType = 2698 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2699 OldProto->getExtProtoInfo()); 2700 New->setType(NewQType); 2701 New->setHasInheritedPrototype(); 2702 2703 // Synthesize parameters with the same types. 2704 SmallVector<ParmVarDecl*, 16> Params; 2705 for (const auto &ParamType : OldProto->param_types()) { 2706 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2707 SourceLocation(), nullptr, 2708 ParamType, /*TInfo=*/nullptr, 2709 SC_None, nullptr); 2710 Param->setScopeInfo(0, Params.size()); 2711 Param->setImplicit(); 2712 Params.push_back(Param); 2713 } 2714 2715 New->setParams(Params); 2716 } 2717 2718 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2719 } 2720 2721 // GNU C permits a K&R definition to follow a prototype declaration 2722 // if the declared types of the parameters in the K&R definition 2723 // match the types in the prototype declaration, even when the 2724 // promoted types of the parameters from the K&R definition differ 2725 // from the types in the prototype. GCC then keeps the types from 2726 // the prototype. 2727 // 2728 // If a variadic prototype is followed by a non-variadic K&R definition, 2729 // the K&R definition becomes variadic. This is sort of an edge case, but 2730 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2731 // C99 6.9.1p8. 2732 if (!getLangOpts().CPlusPlus && 2733 Old->hasPrototype() && !New->hasPrototype() && 2734 New->getType()->getAs<FunctionProtoType>() && 2735 Old->getNumParams() == New->getNumParams()) { 2736 SmallVector<QualType, 16> ArgTypes; 2737 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2738 const FunctionProtoType *OldProto 2739 = Old->getType()->getAs<FunctionProtoType>(); 2740 const FunctionProtoType *NewProto 2741 = New->getType()->getAs<FunctionProtoType>(); 2742 2743 // Determine whether this is the GNU C extension. 2744 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2745 NewProto->getReturnType()); 2746 bool LooseCompatible = !MergedReturn.isNull(); 2747 for (unsigned Idx = 0, End = Old->getNumParams(); 2748 LooseCompatible && Idx != End; ++Idx) { 2749 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2750 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2751 if (Context.typesAreCompatible(OldParm->getType(), 2752 NewProto->getParamType(Idx))) { 2753 ArgTypes.push_back(NewParm->getType()); 2754 } else if (Context.typesAreCompatible(OldParm->getType(), 2755 NewParm->getType(), 2756 /*CompareUnqualified=*/true)) { 2757 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2758 NewProto->getParamType(Idx) }; 2759 Warnings.push_back(Warn); 2760 ArgTypes.push_back(NewParm->getType()); 2761 } else 2762 LooseCompatible = false; 2763 } 2764 2765 if (LooseCompatible) { 2766 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2767 Diag(Warnings[Warn].NewParm->getLocation(), 2768 diag::ext_param_promoted_not_compatible_with_prototype) 2769 << Warnings[Warn].PromotedType 2770 << Warnings[Warn].OldParm->getType(); 2771 if (Warnings[Warn].OldParm->getLocation().isValid()) 2772 Diag(Warnings[Warn].OldParm->getLocation(), 2773 diag::note_previous_declaration); 2774 } 2775 2776 if (MergeTypeWithOld) 2777 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2778 OldProto->getExtProtoInfo())); 2779 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2780 } 2781 2782 // Fall through to diagnose conflicting types. 2783 } 2784 2785 // A function that has already been declared has been redeclared or 2786 // defined with a different type; show an appropriate diagnostic. 2787 2788 // If the previous declaration was an implicitly-generated builtin 2789 // declaration, then at the very least we should use a specialized note. 2790 unsigned BuiltinID; 2791 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2792 // If it's actually a library-defined builtin function like 'malloc' 2793 // or 'printf', just warn about the incompatible redeclaration. 2794 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2795 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2796 Diag(OldLocation, diag::note_previous_builtin_declaration) 2797 << Old << Old->getType(); 2798 2799 // If this is a global redeclaration, just forget hereafter 2800 // about the "builtin-ness" of the function. 2801 // 2802 // Doing this for local extern declarations is problematic. If 2803 // the builtin declaration remains visible, a second invalid 2804 // local declaration will produce a hard error; if it doesn't 2805 // remain visible, a single bogus local redeclaration (which is 2806 // actually only a warning) could break all the downstream code. 2807 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2808 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2809 2810 return false; 2811 } 2812 2813 PrevDiag = diag::note_previous_builtin_declaration; 2814 } 2815 2816 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2817 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2818 return true; 2819 } 2820 2821 /// \brief Completes the merge of two function declarations that are 2822 /// known to be compatible. 2823 /// 2824 /// This routine handles the merging of attributes and other 2825 /// properties of function declarations from the old declaration to 2826 /// the new declaration, once we know that New is in fact a 2827 /// redeclaration of Old. 2828 /// 2829 /// \returns false 2830 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2831 Scope *S, bool MergeTypeWithOld) { 2832 // Merge the attributes 2833 mergeDeclAttributes(New, Old); 2834 2835 // Merge "pure" flag. 2836 if (Old->isPure()) 2837 New->setPure(); 2838 2839 // Merge "used" flag. 2840 if (Old->getMostRecentDecl()->isUsed(false)) 2841 New->setIsUsed(); 2842 2843 // Merge attributes from the parameters. These can mismatch with K&R 2844 // declarations. 2845 if (New->getNumParams() == Old->getNumParams()) 2846 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 2847 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 2848 *this); 2849 2850 if (getLangOpts().CPlusPlus) 2851 return MergeCXXFunctionDecl(New, Old, S); 2852 2853 // Merge the function types so the we get the composite types for the return 2854 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 2855 // was visible. 2856 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 2857 if (!Merged.isNull() && MergeTypeWithOld) 2858 New->setType(Merged); 2859 2860 return false; 2861 } 2862 2863 2864 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 2865 ObjCMethodDecl *oldMethod) { 2866 2867 // Merge the attributes, including deprecated/unavailable 2868 AvailabilityMergeKind MergeKind = 2869 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 2870 : AMK_Override; 2871 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 2872 2873 // Merge attributes from the parameters. 2874 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 2875 oe = oldMethod->param_end(); 2876 for (ObjCMethodDecl::param_iterator 2877 ni = newMethod->param_begin(), ne = newMethod->param_end(); 2878 ni != ne && oi != oe; ++ni, ++oi) 2879 mergeParamDeclAttributes(*ni, *oi, *this); 2880 2881 CheckObjCMethodOverride(newMethod, oldMethod); 2882 } 2883 2884 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 2885 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 2886 /// emitting diagnostics as appropriate. 2887 /// 2888 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 2889 /// to here in AddInitializerToDecl. We can't check them before the initializer 2890 /// is attached. 2891 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 2892 bool MergeTypeWithOld) { 2893 if (New->isInvalidDecl() || Old->isInvalidDecl()) 2894 return; 2895 2896 QualType MergedT; 2897 if (getLangOpts().CPlusPlus) { 2898 if (New->getType()->isUndeducedType()) { 2899 // We don't know what the new type is until the initializer is attached. 2900 return; 2901 } else if (Context.hasSameType(New->getType(), Old->getType())) { 2902 // These could still be something that needs exception specs checked. 2903 return MergeVarDeclExceptionSpecs(New, Old); 2904 } 2905 // C++ [basic.link]p10: 2906 // [...] the types specified by all declarations referring to a given 2907 // object or function shall be identical, except that declarations for an 2908 // array object can specify array types that differ by the presence or 2909 // absence of a major array bound (8.3.4). 2910 else if (Old->getType()->isIncompleteArrayType() && 2911 New->getType()->isArrayType()) { 2912 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2913 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2914 if (Context.hasSameType(OldArray->getElementType(), 2915 NewArray->getElementType())) 2916 MergedT = New->getType(); 2917 } else if (Old->getType()->isArrayType() && 2918 New->getType()->isIncompleteArrayType()) { 2919 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 2920 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 2921 if (Context.hasSameType(OldArray->getElementType(), 2922 NewArray->getElementType())) 2923 MergedT = Old->getType(); 2924 } else if (New->getType()->isObjCObjectPointerType() && 2925 Old->getType()->isObjCObjectPointerType()) { 2926 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 2927 Old->getType()); 2928 } 2929 } else { 2930 // C 6.2.7p2: 2931 // All declarations that refer to the same object or function shall have 2932 // compatible type. 2933 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 2934 } 2935 if (MergedT.isNull()) { 2936 // It's OK if we couldn't merge types if either type is dependent, for a 2937 // block-scope variable. In other cases (static data members of class 2938 // templates, variable templates, ...), we require the types to be 2939 // equivalent. 2940 // FIXME: The C++ standard doesn't say anything about this. 2941 if ((New->getType()->isDependentType() || 2942 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 2943 // If the old type was dependent, we can't merge with it, so the new type 2944 // becomes dependent for now. We'll reproduce the original type when we 2945 // instantiate the TypeSourceInfo for the variable. 2946 if (!New->getType()->isDependentType() && MergeTypeWithOld) 2947 New->setType(Context.DependentTy); 2948 return; 2949 } 2950 2951 // FIXME: Even if this merging succeeds, some other non-visible declaration 2952 // of this variable might have an incompatible type. For instance: 2953 // 2954 // extern int arr[]; 2955 // void f() { extern int arr[2]; } 2956 // void g() { extern int arr[3]; } 2957 // 2958 // Neither C nor C++ requires a diagnostic for this, but we should still try 2959 // to diagnose it. 2960 Diag(New->getLocation(), diag::err_redefinition_different_type) 2961 << New->getDeclName() << New->getType() << Old->getType(); 2962 Diag(Old->getLocation(), diag::note_previous_definition); 2963 return New->setInvalidDecl(); 2964 } 2965 2966 // Don't actually update the type on the new declaration if the old 2967 // declaration was an extern declaration in a different scope. 2968 if (MergeTypeWithOld) 2969 New->setType(MergedT); 2970 } 2971 2972 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 2973 LookupResult &Previous) { 2974 // C11 6.2.7p4: 2975 // For an identifier with internal or external linkage declared 2976 // in a scope in which a prior declaration of that identifier is 2977 // visible, if the prior declaration specifies internal or 2978 // external linkage, the type of the identifier at the later 2979 // declaration becomes the composite type. 2980 // 2981 // If the variable isn't visible, we do not merge with its type. 2982 if (Previous.isShadowed()) 2983 return false; 2984 2985 if (S.getLangOpts().CPlusPlus) { 2986 // C++11 [dcl.array]p3: 2987 // If there is a preceding declaration of the entity in the same 2988 // scope in which the bound was specified, an omitted array bound 2989 // is taken to be the same as in that earlier declaration. 2990 return NewVD->isPreviousDeclInSameBlockScope() || 2991 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 2992 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 2993 } else { 2994 // If the old declaration was function-local, don't merge with its 2995 // type unless we're in the same function. 2996 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 2997 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 2998 } 2999 } 3000 3001 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3002 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3003 /// situation, merging decls or emitting diagnostics as appropriate. 3004 /// 3005 /// Tentative definition rules (C99 6.9.2p2) are checked by 3006 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3007 /// definitions here, since the initializer hasn't been attached. 3008 /// 3009 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3010 // If the new decl is already invalid, don't do any other checking. 3011 if (New->isInvalidDecl()) 3012 return; 3013 3014 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3015 3016 // Verify the old decl was also a variable or variable template. 3017 VarDecl *Old = nullptr; 3018 VarTemplateDecl *OldTemplate = nullptr; 3019 if (Previous.isSingleResult()) { 3020 if (NewTemplate) { 3021 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3022 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3023 } else 3024 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3025 } 3026 if (!Old) { 3027 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3028 << New->getDeclName(); 3029 Diag(Previous.getRepresentativeDecl()->getLocation(), 3030 diag::note_previous_definition); 3031 return New->setInvalidDecl(); 3032 } 3033 3034 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3035 return; 3036 3037 // Ensure the template parameters are compatible. 3038 if (NewTemplate && 3039 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3040 OldTemplate->getTemplateParameters(), 3041 /*Complain=*/true, TPL_TemplateMatch)) 3042 return; 3043 3044 // C++ [class.mem]p1: 3045 // A member shall not be declared twice in the member-specification [...] 3046 // 3047 // Here, we need only consider static data members. 3048 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3049 Diag(New->getLocation(), diag::err_duplicate_member) 3050 << New->getIdentifier(); 3051 Diag(Old->getLocation(), diag::note_previous_declaration); 3052 New->setInvalidDecl(); 3053 } 3054 3055 mergeDeclAttributes(New, Old); 3056 // Warn if an already-declared variable is made a weak_import in a subsequent 3057 // declaration 3058 if (New->hasAttr<WeakImportAttr>() && 3059 Old->getStorageClass() == SC_None && 3060 !Old->hasAttr<WeakImportAttr>()) { 3061 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3062 Diag(Old->getLocation(), diag::note_previous_definition); 3063 // Remove weak_import attribute on new declaration. 3064 New->dropAttr<WeakImportAttr>(); 3065 } 3066 3067 // Merge the types. 3068 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3069 3070 if (New->isInvalidDecl()) 3071 return; 3072 3073 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3074 if (New->getStorageClass() == SC_Static && 3075 !New->isStaticDataMember() && 3076 Old->hasExternalFormalLinkage()) { 3077 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 3078 Diag(Old->getLocation(), diag::note_previous_definition); 3079 return New->setInvalidDecl(); 3080 } 3081 // C99 6.2.2p4: 3082 // For an identifier declared with the storage-class specifier 3083 // extern in a scope in which a prior declaration of that 3084 // identifier is visible,23) if the prior declaration specifies 3085 // internal or external linkage, the linkage of the identifier at 3086 // the later declaration is the same as the linkage specified at 3087 // the prior declaration. If no prior declaration is visible, or 3088 // if the prior declaration specifies no linkage, then the 3089 // identifier has external linkage. 3090 if (New->hasExternalStorage() && Old->hasLinkage()) 3091 /* Okay */; 3092 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3093 !New->isStaticDataMember() && 3094 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3095 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3096 Diag(Old->getLocation(), diag::note_previous_definition); 3097 return New->setInvalidDecl(); 3098 } 3099 3100 // Check if extern is followed by non-extern and vice-versa. 3101 if (New->hasExternalStorage() && 3102 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3103 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3104 Diag(Old->getLocation(), diag::note_previous_definition); 3105 return New->setInvalidDecl(); 3106 } 3107 if (Old->hasLinkage() && New->isLocalVarDecl() && 3108 !New->hasExternalStorage()) { 3109 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3110 Diag(Old->getLocation(), diag::note_previous_definition); 3111 return New->setInvalidDecl(); 3112 } 3113 3114 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3115 3116 // FIXME: The test for external storage here seems wrong? We still 3117 // need to check for mismatches. 3118 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3119 // Don't complain about out-of-line definitions of static members. 3120 !(Old->getLexicalDeclContext()->isRecord() && 3121 !New->getLexicalDeclContext()->isRecord())) { 3122 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3123 Diag(Old->getLocation(), diag::note_previous_definition); 3124 return New->setInvalidDecl(); 3125 } 3126 3127 if (New->getTLSKind() != Old->getTLSKind()) { 3128 if (!Old->getTLSKind()) { 3129 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3130 Diag(Old->getLocation(), diag::note_previous_declaration); 3131 } else if (!New->getTLSKind()) { 3132 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3133 Diag(Old->getLocation(), diag::note_previous_declaration); 3134 } else { 3135 // Do not allow redeclaration to change the variable between requiring 3136 // static and dynamic initialization. 3137 // FIXME: GCC allows this, but uses the TLS keyword on the first 3138 // declaration to determine the kind. Do we need to be compatible here? 3139 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3140 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3141 Diag(Old->getLocation(), diag::note_previous_declaration); 3142 } 3143 } 3144 3145 // C++ doesn't have tentative definitions, so go right ahead and check here. 3146 const VarDecl *Def; 3147 if (getLangOpts().CPlusPlus && 3148 New->isThisDeclarationADefinition() == VarDecl::Definition && 3149 (Def = Old->getDefinition())) { 3150 Diag(New->getLocation(), diag::err_redefinition) << New; 3151 Diag(Def->getLocation(), diag::note_previous_definition); 3152 New->setInvalidDecl(); 3153 return; 3154 } 3155 3156 if (haveIncompatibleLanguageLinkages(Old, New)) { 3157 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3158 Diag(Old->getLocation(), diag::note_previous_definition); 3159 New->setInvalidDecl(); 3160 return; 3161 } 3162 3163 // Merge "used" flag. 3164 if (Old->getMostRecentDecl()->isUsed(false)) 3165 New->setIsUsed(); 3166 3167 // Keep a chain of previous declarations. 3168 New->setPreviousDecl(Old); 3169 if (NewTemplate) 3170 NewTemplate->setPreviousDecl(OldTemplate); 3171 3172 // Inherit access appropriately. 3173 New->setAccess(Old->getAccess()); 3174 if (NewTemplate) 3175 NewTemplate->setAccess(New->getAccess()); 3176 } 3177 3178 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3179 /// no declarator (e.g. "struct foo;") is parsed. 3180 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3181 DeclSpec &DS) { 3182 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3183 } 3184 3185 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3186 if (!S.Context.getLangOpts().CPlusPlus) 3187 return; 3188 3189 if (isa<CXXRecordDecl>(Tag->getParent())) { 3190 // If this tag is the direct child of a class, number it if 3191 // it is anonymous. 3192 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3193 return; 3194 MangleNumberingContext &MCtx = 3195 S.Context.getManglingNumberContext(Tag->getParent()); 3196 S.Context.setManglingNumber( 3197 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3198 return; 3199 } 3200 3201 // If this tag isn't a direct child of a class, number it if it is local. 3202 Decl *ManglingContextDecl; 3203 if (MangleNumberingContext *MCtx = 3204 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3205 ManglingContextDecl)) { 3206 S.Context.setManglingNumber( 3207 Tag, 3208 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3209 } 3210 } 3211 3212 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3213 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3214 /// parameters to cope with template friend declarations. 3215 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3216 DeclSpec &DS, 3217 MultiTemplateParamsArg TemplateParams, 3218 bool IsExplicitInstantiation) { 3219 Decl *TagD = nullptr; 3220 TagDecl *Tag = nullptr; 3221 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3222 DS.getTypeSpecType() == DeclSpec::TST_struct || 3223 DS.getTypeSpecType() == DeclSpec::TST_interface || 3224 DS.getTypeSpecType() == DeclSpec::TST_union || 3225 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3226 TagD = DS.getRepAsDecl(); 3227 3228 if (!TagD) // We probably had an error 3229 return nullptr; 3230 3231 // Note that the above type specs guarantee that the 3232 // type rep is a Decl, whereas in many of the others 3233 // it's a Type. 3234 if (isa<TagDecl>(TagD)) 3235 Tag = cast<TagDecl>(TagD); 3236 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3237 Tag = CTD->getTemplatedDecl(); 3238 } 3239 3240 if (Tag) { 3241 HandleTagNumbering(*this, Tag, S); 3242 Tag->setFreeStanding(); 3243 if (Tag->isInvalidDecl()) 3244 return Tag; 3245 } 3246 3247 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3248 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3249 // or incomplete types shall not be restrict-qualified." 3250 if (TypeQuals & DeclSpec::TQ_restrict) 3251 Diag(DS.getRestrictSpecLoc(), 3252 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3253 << DS.getSourceRange(); 3254 } 3255 3256 if (DS.isConstexprSpecified()) { 3257 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3258 // and definitions of functions and variables. 3259 if (Tag) 3260 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3261 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3262 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3263 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3264 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3265 else 3266 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3267 // Don't emit warnings after this error. 3268 return TagD; 3269 } 3270 3271 DiagnoseFunctionSpecifiers(DS); 3272 3273 if (DS.isFriendSpecified()) { 3274 // If we're dealing with a decl but not a TagDecl, assume that 3275 // whatever routines created it handled the friendship aspect. 3276 if (TagD && !Tag) 3277 return nullptr; 3278 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3279 } 3280 3281 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3282 bool IsExplicitSpecialization = 3283 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3284 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3285 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3286 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3287 // nested-name-specifier unless it is an explicit instantiation 3288 // or an explicit specialization. 3289 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3290 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3291 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3292 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3293 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3294 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3295 << SS.getRange(); 3296 return nullptr; 3297 } 3298 3299 // Track whether this decl-specifier declares anything. 3300 bool DeclaresAnything = true; 3301 3302 // Handle anonymous struct definitions. 3303 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3304 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3305 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3306 if (getLangOpts().CPlusPlus || 3307 Record->getDeclContext()->isRecord()) 3308 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3309 3310 DeclaresAnything = false; 3311 } 3312 } 3313 3314 // Check for Microsoft C extension: anonymous struct member. 3315 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 3316 CurContext->isRecord() && 3317 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3318 // Handle 2 kinds of anonymous struct: 3319 // struct STRUCT; 3320 // and 3321 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3322 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 3323 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 3324 (DS.getTypeSpecType() == DeclSpec::TST_typename && 3325 DS.getRepAsType().get()->isStructureType())) { 3326 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 3327 << DS.getSourceRange(); 3328 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3329 } 3330 } 3331 3332 // Skip all the checks below if we have a type error. 3333 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3334 (TagD && TagD->isInvalidDecl())) 3335 return TagD; 3336 3337 if (getLangOpts().CPlusPlus && 3338 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3339 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3340 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3341 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3342 DeclaresAnything = false; 3343 3344 if (!DS.isMissingDeclaratorOk()) { 3345 // Customize diagnostic for a typedef missing a name. 3346 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3347 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3348 << DS.getSourceRange(); 3349 else 3350 DeclaresAnything = false; 3351 } 3352 3353 if (DS.isModulePrivateSpecified() && 3354 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3355 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3356 << Tag->getTagKind() 3357 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3358 3359 ActOnDocumentableDecl(TagD); 3360 3361 // C 6.7/2: 3362 // A declaration [...] shall declare at least a declarator [...], a tag, 3363 // or the members of an enumeration. 3364 // C++ [dcl.dcl]p3: 3365 // [If there are no declarators], and except for the declaration of an 3366 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3367 // names into the program, or shall redeclare a name introduced by a 3368 // previous declaration. 3369 if (!DeclaresAnything) { 3370 // In C, we allow this as a (popular) extension / bug. Don't bother 3371 // producing further diagnostics for redundant qualifiers after this. 3372 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3373 return TagD; 3374 } 3375 3376 // C++ [dcl.stc]p1: 3377 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3378 // init-declarator-list of the declaration shall not be empty. 3379 // C++ [dcl.fct.spec]p1: 3380 // If a cv-qualifier appears in a decl-specifier-seq, the 3381 // init-declarator-list of the declaration shall not be empty. 3382 // 3383 // Spurious qualifiers here appear to be valid in C. 3384 unsigned DiagID = diag::warn_standalone_specifier; 3385 if (getLangOpts().CPlusPlus) 3386 DiagID = diag::ext_standalone_specifier; 3387 3388 // Note that a linkage-specification sets a storage class, but 3389 // 'extern "C" struct foo;' is actually valid and not theoretically 3390 // useless. 3391 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3392 if (SCS == DeclSpec::SCS_mutable) 3393 // Since mutable is not a viable storage class specifier in C, there is 3394 // no reason to treat it as an extension. Instead, diagnose as an error. 3395 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3396 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3397 Diag(DS.getStorageClassSpecLoc(), DiagID) 3398 << DeclSpec::getSpecifierName(SCS); 3399 } 3400 3401 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3402 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3403 << DeclSpec::getSpecifierName(TSCS); 3404 if (DS.getTypeQualifiers()) { 3405 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3406 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3407 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3408 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3409 // Restrict is covered above. 3410 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3411 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3412 } 3413 3414 // Warn about ignored type attributes, for example: 3415 // __attribute__((aligned)) struct A; 3416 // Attributes should be placed after tag to apply to type declaration. 3417 if (!DS.getAttributes().empty()) { 3418 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3419 if (TypeSpecType == DeclSpec::TST_class || 3420 TypeSpecType == DeclSpec::TST_struct || 3421 TypeSpecType == DeclSpec::TST_interface || 3422 TypeSpecType == DeclSpec::TST_union || 3423 TypeSpecType == DeclSpec::TST_enum) { 3424 AttributeList* attrs = DS.getAttributes().getList(); 3425 while (attrs) { 3426 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3427 << attrs->getName() 3428 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3429 TypeSpecType == DeclSpec::TST_struct ? 1 : 3430 TypeSpecType == DeclSpec::TST_union ? 2 : 3431 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3432 attrs = attrs->getNext(); 3433 } 3434 } 3435 } 3436 3437 return TagD; 3438 } 3439 3440 /// We are trying to inject an anonymous member into the given scope; 3441 /// check if there's an existing declaration that can't be overloaded. 3442 /// 3443 /// \return true if this is a forbidden redeclaration 3444 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3445 Scope *S, 3446 DeclContext *Owner, 3447 DeclarationName Name, 3448 SourceLocation NameLoc, 3449 unsigned diagnostic) { 3450 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3451 Sema::ForRedeclaration); 3452 if (!SemaRef.LookupName(R, S)) return false; 3453 3454 if (R.getAsSingle<TagDecl>()) 3455 return false; 3456 3457 // Pick a representative declaration. 3458 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3459 assert(PrevDecl && "Expected a non-null Decl"); 3460 3461 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3462 return false; 3463 3464 SemaRef.Diag(NameLoc, diagnostic) << Name; 3465 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3466 3467 return true; 3468 } 3469 3470 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3471 /// anonymous struct or union AnonRecord into the owning context Owner 3472 /// and scope S. This routine will be invoked just after we realize 3473 /// that an unnamed union or struct is actually an anonymous union or 3474 /// struct, e.g., 3475 /// 3476 /// @code 3477 /// union { 3478 /// int i; 3479 /// float f; 3480 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3481 /// // f into the surrounding scope.x 3482 /// @endcode 3483 /// 3484 /// This routine is recursive, injecting the names of nested anonymous 3485 /// structs/unions into the owning context and scope as well. 3486 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3487 DeclContext *Owner, 3488 RecordDecl *AnonRecord, 3489 AccessSpecifier AS, 3490 SmallVectorImpl<NamedDecl *> &Chaining, 3491 bool MSAnonStruct) { 3492 unsigned diagKind 3493 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3494 : diag::err_anonymous_struct_member_redecl; 3495 3496 bool Invalid = false; 3497 3498 // Look every FieldDecl and IndirectFieldDecl with a name. 3499 for (auto *D : AnonRecord->decls()) { 3500 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3501 cast<NamedDecl>(D)->getDeclName()) { 3502 ValueDecl *VD = cast<ValueDecl>(D); 3503 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3504 VD->getLocation(), diagKind)) { 3505 // C++ [class.union]p2: 3506 // The names of the members of an anonymous union shall be 3507 // distinct from the names of any other entity in the 3508 // scope in which the anonymous union is declared. 3509 Invalid = true; 3510 } else { 3511 // C++ [class.union]p2: 3512 // For the purpose of name lookup, after the anonymous union 3513 // definition, the members of the anonymous union are 3514 // considered to have been defined in the scope in which the 3515 // anonymous union is declared. 3516 unsigned OldChainingSize = Chaining.size(); 3517 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3518 for (auto *PI : IF->chain()) 3519 Chaining.push_back(PI); 3520 else 3521 Chaining.push_back(VD); 3522 3523 assert(Chaining.size() >= 2); 3524 NamedDecl **NamedChain = 3525 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3526 for (unsigned i = 0; i < Chaining.size(); i++) 3527 NamedChain[i] = Chaining[i]; 3528 3529 IndirectFieldDecl* IndirectField = 3530 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3531 VD->getIdentifier(), VD->getType(), 3532 NamedChain, Chaining.size()); 3533 3534 IndirectField->setAccess(AS); 3535 IndirectField->setImplicit(); 3536 SemaRef.PushOnScopeChains(IndirectField, S); 3537 3538 // That includes picking up the appropriate access specifier. 3539 if (AS != AS_none) IndirectField->setAccess(AS); 3540 3541 Chaining.resize(OldChainingSize); 3542 } 3543 } 3544 } 3545 3546 return Invalid; 3547 } 3548 3549 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3550 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3551 /// illegal input values are mapped to SC_None. 3552 static StorageClass 3553 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3554 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3555 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3556 "Parser allowed 'typedef' as storage class VarDecl."); 3557 switch (StorageClassSpec) { 3558 case DeclSpec::SCS_unspecified: return SC_None; 3559 case DeclSpec::SCS_extern: 3560 if (DS.isExternInLinkageSpec()) 3561 return SC_None; 3562 return SC_Extern; 3563 case DeclSpec::SCS_static: return SC_Static; 3564 case DeclSpec::SCS_auto: return SC_Auto; 3565 case DeclSpec::SCS_register: return SC_Register; 3566 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3567 // Illegal SCSs map to None: error reporting is up to the caller. 3568 case DeclSpec::SCS_mutable: // Fall through. 3569 case DeclSpec::SCS_typedef: return SC_None; 3570 } 3571 llvm_unreachable("unknown storage class specifier"); 3572 } 3573 3574 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3575 assert(Record->hasInClassInitializer()); 3576 3577 for (const auto *I : Record->decls()) { 3578 const auto *FD = dyn_cast<FieldDecl>(I); 3579 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3580 FD = IFD->getAnonField(); 3581 if (FD && FD->hasInClassInitializer()) 3582 return FD->getLocation(); 3583 } 3584 3585 llvm_unreachable("couldn't find in-class initializer"); 3586 } 3587 3588 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3589 SourceLocation DefaultInitLoc) { 3590 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3591 return; 3592 3593 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3594 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3595 } 3596 3597 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3598 CXXRecordDecl *AnonUnion) { 3599 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3600 return; 3601 3602 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3603 } 3604 3605 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3606 /// anonymous structure or union. Anonymous unions are a C++ feature 3607 /// (C++ [class.union]) and a C11 feature; anonymous structures 3608 /// are a C11 feature and GNU C++ extension. 3609 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3610 AccessSpecifier AS, 3611 RecordDecl *Record, 3612 const PrintingPolicy &Policy) { 3613 DeclContext *Owner = Record->getDeclContext(); 3614 3615 // Diagnose whether this anonymous struct/union is an extension. 3616 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3617 Diag(Record->getLocation(), diag::ext_anonymous_union); 3618 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3619 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3620 else if (!Record->isUnion() && !getLangOpts().C11) 3621 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3622 3623 // C and C++ require different kinds of checks for anonymous 3624 // structs/unions. 3625 bool Invalid = false; 3626 if (getLangOpts().CPlusPlus) { 3627 const char *PrevSpec = nullptr; 3628 unsigned DiagID; 3629 if (Record->isUnion()) { 3630 // C++ [class.union]p6: 3631 // Anonymous unions declared in a named namespace or in the 3632 // global namespace shall be declared static. 3633 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3634 (isa<TranslationUnitDecl>(Owner) || 3635 (isa<NamespaceDecl>(Owner) && 3636 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3637 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3638 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3639 3640 // Recover by adding 'static'. 3641 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3642 PrevSpec, DiagID, Policy); 3643 } 3644 // C++ [class.union]p6: 3645 // A storage class is not allowed in a declaration of an 3646 // anonymous union in a class scope. 3647 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3648 isa<RecordDecl>(Owner)) { 3649 Diag(DS.getStorageClassSpecLoc(), 3650 diag::err_anonymous_union_with_storage_spec) 3651 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3652 3653 // Recover by removing the storage specifier. 3654 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3655 SourceLocation(), 3656 PrevSpec, DiagID, Context.getPrintingPolicy()); 3657 } 3658 } 3659 3660 // Ignore const/volatile/restrict qualifiers. 3661 if (DS.getTypeQualifiers()) { 3662 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3663 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3664 << Record->isUnion() << "const" 3665 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3666 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3667 Diag(DS.getVolatileSpecLoc(), 3668 diag::ext_anonymous_struct_union_qualified) 3669 << Record->isUnion() << "volatile" 3670 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3671 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3672 Diag(DS.getRestrictSpecLoc(), 3673 diag::ext_anonymous_struct_union_qualified) 3674 << Record->isUnion() << "restrict" 3675 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3676 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3677 Diag(DS.getAtomicSpecLoc(), 3678 diag::ext_anonymous_struct_union_qualified) 3679 << Record->isUnion() << "_Atomic" 3680 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3681 3682 DS.ClearTypeQualifiers(); 3683 } 3684 3685 // C++ [class.union]p2: 3686 // The member-specification of an anonymous union shall only 3687 // define non-static data members. [Note: nested types and 3688 // functions cannot be declared within an anonymous union. ] 3689 for (auto *Mem : Record->decls()) { 3690 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3691 // C++ [class.union]p3: 3692 // An anonymous union shall not have private or protected 3693 // members (clause 11). 3694 assert(FD->getAccess() != AS_none); 3695 if (FD->getAccess() != AS_public) { 3696 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3697 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3698 Invalid = true; 3699 } 3700 3701 // C++ [class.union]p1 3702 // An object of a class with a non-trivial constructor, a non-trivial 3703 // copy constructor, a non-trivial destructor, or a non-trivial copy 3704 // assignment operator cannot be a member of a union, nor can an 3705 // array of such objects. 3706 if (CheckNontrivialField(FD)) 3707 Invalid = true; 3708 } else if (Mem->isImplicit()) { 3709 // Any implicit members are fine. 3710 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3711 // This is a type that showed up in an 3712 // elaborated-type-specifier inside the anonymous struct or 3713 // union, but which actually declares a type outside of the 3714 // anonymous struct or union. It's okay. 3715 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3716 if (!MemRecord->isAnonymousStructOrUnion() && 3717 MemRecord->getDeclName()) { 3718 // Visual C++ allows type definition in anonymous struct or union. 3719 if (getLangOpts().MicrosoftExt) 3720 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3721 << (int)Record->isUnion(); 3722 else { 3723 // This is a nested type declaration. 3724 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3725 << (int)Record->isUnion(); 3726 Invalid = true; 3727 } 3728 } else { 3729 // This is an anonymous type definition within another anonymous type. 3730 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3731 // not part of standard C++. 3732 Diag(MemRecord->getLocation(), 3733 diag::ext_anonymous_record_with_anonymous_type) 3734 << (int)Record->isUnion(); 3735 } 3736 } else if (isa<AccessSpecDecl>(Mem)) { 3737 // Any access specifier is fine. 3738 } else { 3739 // We have something that isn't a non-static data 3740 // member. Complain about it. 3741 unsigned DK = diag::err_anonymous_record_bad_member; 3742 if (isa<TypeDecl>(Mem)) 3743 DK = diag::err_anonymous_record_with_type; 3744 else if (isa<FunctionDecl>(Mem)) 3745 DK = diag::err_anonymous_record_with_function; 3746 else if (isa<VarDecl>(Mem)) 3747 DK = diag::err_anonymous_record_with_static; 3748 3749 // Visual C++ allows type definition in anonymous struct or union. 3750 if (getLangOpts().MicrosoftExt && 3751 DK == diag::err_anonymous_record_with_type) 3752 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3753 << (int)Record->isUnion(); 3754 else { 3755 Diag(Mem->getLocation(), DK) 3756 << (int)Record->isUnion(); 3757 Invalid = true; 3758 } 3759 } 3760 } 3761 3762 // C++11 [class.union]p8 (DR1460): 3763 // At most one variant member of a union may have a 3764 // brace-or-equal-initializer. 3765 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3766 Owner->isRecord()) 3767 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3768 cast<CXXRecordDecl>(Record)); 3769 } 3770 3771 if (!Record->isUnion() && !Owner->isRecord()) { 3772 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3773 << (int)getLangOpts().CPlusPlus; 3774 Invalid = true; 3775 } 3776 3777 // Mock up a declarator. 3778 Declarator Dc(DS, Declarator::MemberContext); 3779 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3780 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3781 3782 // Create a declaration for this anonymous struct/union. 3783 NamedDecl *Anon = nullptr; 3784 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3785 Anon = FieldDecl::Create(Context, OwningClass, 3786 DS.getLocStart(), 3787 Record->getLocation(), 3788 /*IdentifierInfo=*/nullptr, 3789 Context.getTypeDeclType(Record), 3790 TInfo, 3791 /*BitWidth=*/nullptr, /*Mutable=*/false, 3792 /*InitStyle=*/ICIS_NoInit); 3793 Anon->setAccess(AS); 3794 if (getLangOpts().CPlusPlus) 3795 FieldCollector->Add(cast<FieldDecl>(Anon)); 3796 } else { 3797 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 3798 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 3799 if (SCSpec == DeclSpec::SCS_mutable) { 3800 // mutable can only appear on non-static class members, so it's always 3801 // an error here 3802 Diag(Record->getLocation(), diag::err_mutable_nonmember); 3803 Invalid = true; 3804 SC = SC_None; 3805 } 3806 3807 Anon = VarDecl::Create(Context, Owner, 3808 DS.getLocStart(), 3809 Record->getLocation(), /*IdentifierInfo=*/nullptr, 3810 Context.getTypeDeclType(Record), 3811 TInfo, SC); 3812 3813 // Default-initialize the implicit variable. This initialization will be 3814 // trivial in almost all cases, except if a union member has an in-class 3815 // initializer: 3816 // union { int n = 0; }; 3817 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 3818 } 3819 Anon->setImplicit(); 3820 3821 // Mark this as an anonymous struct/union type. 3822 Record->setAnonymousStructOrUnion(true); 3823 3824 // Add the anonymous struct/union object to the current 3825 // context. We'll be referencing this object when we refer to one of 3826 // its members. 3827 Owner->addDecl(Anon); 3828 3829 // Inject the members of the anonymous struct/union into the owning 3830 // context and into the identifier resolver chain for name lookup 3831 // purposes. 3832 SmallVector<NamedDecl*, 2> Chain; 3833 Chain.push_back(Anon); 3834 3835 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 3836 Chain, false)) 3837 Invalid = true; 3838 3839 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 3840 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 3841 Decl *ManglingContextDecl; 3842 if (MangleNumberingContext *MCtx = 3843 getCurrentMangleNumberContext(NewVD->getDeclContext(), 3844 ManglingContextDecl)) { 3845 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 3846 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 3847 } 3848 } 3849 } 3850 3851 if (Invalid) 3852 Anon->setInvalidDecl(); 3853 3854 return Anon; 3855 } 3856 3857 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 3858 /// Microsoft C anonymous structure. 3859 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 3860 /// Example: 3861 /// 3862 /// struct A { int a; }; 3863 /// struct B { struct A; int b; }; 3864 /// 3865 /// void foo() { 3866 /// B var; 3867 /// var.a = 3; 3868 /// } 3869 /// 3870 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 3871 RecordDecl *Record) { 3872 3873 // If there is no Record, get the record via the typedef. 3874 if (!Record) 3875 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 3876 3877 // Mock up a declarator. 3878 Declarator Dc(DS, Declarator::TypeNameContext); 3879 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3880 assert(TInfo && "couldn't build declarator info for anonymous struct"); 3881 3882 // Create a declaration for this anonymous struct. 3883 NamedDecl *Anon = FieldDecl::Create(Context, 3884 cast<RecordDecl>(CurContext), 3885 DS.getLocStart(), 3886 DS.getLocStart(), 3887 /*IdentifierInfo=*/nullptr, 3888 Context.getTypeDeclType(Record), 3889 TInfo, 3890 /*BitWidth=*/nullptr, /*Mutable=*/false, 3891 /*InitStyle=*/ICIS_NoInit); 3892 Anon->setImplicit(); 3893 3894 // Add the anonymous struct object to the current context. 3895 CurContext->addDecl(Anon); 3896 3897 // Inject the members of the anonymous struct into the current 3898 // context and into the identifier resolver chain for name lookup 3899 // purposes. 3900 SmallVector<NamedDecl*, 2> Chain; 3901 Chain.push_back(Anon); 3902 3903 RecordDecl *RecordDef = Record->getDefinition(); 3904 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 3905 RecordDef, AS_none, 3906 Chain, true)) 3907 Anon->setInvalidDecl(); 3908 3909 return Anon; 3910 } 3911 3912 /// GetNameForDeclarator - Determine the full declaration name for the 3913 /// given Declarator. 3914 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 3915 return GetNameFromUnqualifiedId(D.getName()); 3916 } 3917 3918 /// \brief Retrieves the declaration name from a parsed unqualified-id. 3919 DeclarationNameInfo 3920 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 3921 DeclarationNameInfo NameInfo; 3922 NameInfo.setLoc(Name.StartLocation); 3923 3924 switch (Name.getKind()) { 3925 3926 case UnqualifiedId::IK_ImplicitSelfParam: 3927 case UnqualifiedId::IK_Identifier: 3928 NameInfo.setName(Name.Identifier); 3929 NameInfo.setLoc(Name.StartLocation); 3930 return NameInfo; 3931 3932 case UnqualifiedId::IK_OperatorFunctionId: 3933 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 3934 Name.OperatorFunctionId.Operator)); 3935 NameInfo.setLoc(Name.StartLocation); 3936 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 3937 = Name.OperatorFunctionId.SymbolLocations[0]; 3938 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 3939 = Name.EndLocation.getRawEncoding(); 3940 return NameInfo; 3941 3942 case UnqualifiedId::IK_LiteralOperatorId: 3943 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 3944 Name.Identifier)); 3945 NameInfo.setLoc(Name.StartLocation); 3946 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 3947 return NameInfo; 3948 3949 case UnqualifiedId::IK_ConversionFunctionId: { 3950 TypeSourceInfo *TInfo; 3951 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 3952 if (Ty.isNull()) 3953 return DeclarationNameInfo(); 3954 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 3955 Context.getCanonicalType(Ty))); 3956 NameInfo.setLoc(Name.StartLocation); 3957 NameInfo.setNamedTypeInfo(TInfo); 3958 return NameInfo; 3959 } 3960 3961 case UnqualifiedId::IK_ConstructorName: { 3962 TypeSourceInfo *TInfo; 3963 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 3964 if (Ty.isNull()) 3965 return DeclarationNameInfo(); 3966 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3967 Context.getCanonicalType(Ty))); 3968 NameInfo.setLoc(Name.StartLocation); 3969 NameInfo.setNamedTypeInfo(TInfo); 3970 return NameInfo; 3971 } 3972 3973 case UnqualifiedId::IK_ConstructorTemplateId: { 3974 // In well-formed code, we can only have a constructor 3975 // template-id that refers to the current context, so go there 3976 // to find the actual type being constructed. 3977 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 3978 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 3979 return DeclarationNameInfo(); 3980 3981 // Determine the type of the class being constructed. 3982 QualType CurClassType = Context.getTypeDeclType(CurClass); 3983 3984 // FIXME: Check two things: that the template-id names the same type as 3985 // CurClassType, and that the template-id does not occur when the name 3986 // was qualified. 3987 3988 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 3989 Context.getCanonicalType(CurClassType))); 3990 NameInfo.setLoc(Name.StartLocation); 3991 // FIXME: should we retrieve TypeSourceInfo? 3992 NameInfo.setNamedTypeInfo(nullptr); 3993 return NameInfo; 3994 } 3995 3996 case UnqualifiedId::IK_DestructorName: { 3997 TypeSourceInfo *TInfo; 3998 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 3999 if (Ty.isNull()) 4000 return DeclarationNameInfo(); 4001 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4002 Context.getCanonicalType(Ty))); 4003 NameInfo.setLoc(Name.StartLocation); 4004 NameInfo.setNamedTypeInfo(TInfo); 4005 return NameInfo; 4006 } 4007 4008 case UnqualifiedId::IK_TemplateId: { 4009 TemplateName TName = Name.TemplateId->Template.get(); 4010 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4011 return Context.getNameForTemplate(TName, TNameLoc); 4012 } 4013 4014 } // switch (Name.getKind()) 4015 4016 llvm_unreachable("Unknown name kind"); 4017 } 4018 4019 static QualType getCoreType(QualType Ty) { 4020 do { 4021 if (Ty->isPointerType() || Ty->isReferenceType()) 4022 Ty = Ty->getPointeeType(); 4023 else if (Ty->isArrayType()) 4024 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4025 else 4026 return Ty.withoutLocalFastQualifiers(); 4027 } while (true); 4028 } 4029 4030 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4031 /// and Definition have "nearly" matching parameters. This heuristic is 4032 /// used to improve diagnostics in the case where an out-of-line function 4033 /// definition doesn't match any declaration within the class or namespace. 4034 /// Also sets Params to the list of indices to the parameters that differ 4035 /// between the declaration and the definition. If hasSimilarParameters 4036 /// returns true and Params is empty, then all of the parameters match. 4037 static bool hasSimilarParameters(ASTContext &Context, 4038 FunctionDecl *Declaration, 4039 FunctionDecl *Definition, 4040 SmallVectorImpl<unsigned> &Params) { 4041 Params.clear(); 4042 if (Declaration->param_size() != Definition->param_size()) 4043 return false; 4044 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4045 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4046 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4047 4048 // The parameter types are identical 4049 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4050 continue; 4051 4052 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4053 QualType DefParamBaseTy = getCoreType(DefParamTy); 4054 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4055 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4056 4057 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4058 (DeclTyName && DeclTyName == DefTyName)) 4059 Params.push_back(Idx); 4060 else // The two parameters aren't even close 4061 return false; 4062 } 4063 4064 return true; 4065 } 4066 4067 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4068 /// declarator needs to be rebuilt in the current instantiation. 4069 /// Any bits of declarator which appear before the name are valid for 4070 /// consideration here. That's specifically the type in the decl spec 4071 /// and the base type in any member-pointer chunks. 4072 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4073 DeclarationName Name) { 4074 // The types we specifically need to rebuild are: 4075 // - typenames, typeofs, and decltypes 4076 // - types which will become injected class names 4077 // Of course, we also need to rebuild any type referencing such a 4078 // type. It's safest to just say "dependent", but we call out a 4079 // few cases here. 4080 4081 DeclSpec &DS = D.getMutableDeclSpec(); 4082 switch (DS.getTypeSpecType()) { 4083 case DeclSpec::TST_typename: 4084 case DeclSpec::TST_typeofType: 4085 case DeclSpec::TST_underlyingType: 4086 case DeclSpec::TST_atomic: { 4087 // Grab the type from the parser. 4088 TypeSourceInfo *TSI = nullptr; 4089 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4090 if (T.isNull() || !T->isDependentType()) break; 4091 4092 // Make sure there's a type source info. This isn't really much 4093 // of a waste; most dependent types should have type source info 4094 // attached already. 4095 if (!TSI) 4096 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4097 4098 // Rebuild the type in the current instantiation. 4099 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4100 if (!TSI) return true; 4101 4102 // Store the new type back in the decl spec. 4103 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4104 DS.UpdateTypeRep(LocType); 4105 break; 4106 } 4107 4108 case DeclSpec::TST_decltype: 4109 case DeclSpec::TST_typeofExpr: { 4110 Expr *E = DS.getRepAsExpr(); 4111 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4112 if (Result.isInvalid()) return true; 4113 DS.UpdateExprRep(Result.get()); 4114 break; 4115 } 4116 4117 default: 4118 // Nothing to do for these decl specs. 4119 break; 4120 } 4121 4122 // It doesn't matter what order we do this in. 4123 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4124 DeclaratorChunk &Chunk = D.getTypeObject(I); 4125 4126 // The only type information in the declarator which can come 4127 // before the declaration name is the base type of a member 4128 // pointer. 4129 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4130 continue; 4131 4132 // Rebuild the scope specifier in-place. 4133 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4134 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4135 return true; 4136 } 4137 4138 return false; 4139 } 4140 4141 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4142 D.setFunctionDefinitionKind(FDK_Declaration); 4143 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4144 4145 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4146 Dcl && Dcl->getDeclContext()->isFileContext()) 4147 Dcl->setTopLevelDeclInObjCContainer(); 4148 4149 return Dcl; 4150 } 4151 4152 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4153 /// If T is the name of a class, then each of the following shall have a 4154 /// name different from T: 4155 /// - every static data member of class T; 4156 /// - every member function of class T 4157 /// - every member of class T that is itself a type; 4158 /// \returns true if the declaration name violates these rules. 4159 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4160 DeclarationNameInfo NameInfo) { 4161 DeclarationName Name = NameInfo.getName(); 4162 4163 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4164 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4165 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4166 return true; 4167 } 4168 4169 return false; 4170 } 4171 4172 /// \brief Diagnose a declaration whose declarator-id has the given 4173 /// nested-name-specifier. 4174 /// 4175 /// \param SS The nested-name-specifier of the declarator-id. 4176 /// 4177 /// \param DC The declaration context to which the nested-name-specifier 4178 /// resolves. 4179 /// 4180 /// \param Name The name of the entity being declared. 4181 /// 4182 /// \param Loc The location of the name of the entity being declared. 4183 /// 4184 /// \returns true if we cannot safely recover from this error, false otherwise. 4185 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4186 DeclarationName Name, 4187 SourceLocation Loc) { 4188 DeclContext *Cur = CurContext; 4189 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4190 Cur = Cur->getParent(); 4191 4192 // If the user provided a superfluous scope specifier that refers back to the 4193 // class in which the entity is already declared, diagnose and ignore it. 4194 // 4195 // class X { 4196 // void X::f(); 4197 // }; 4198 // 4199 // Note, it was once ill-formed to give redundant qualification in all 4200 // contexts, but that rule was removed by DR482. 4201 if (Cur->Equals(DC)) { 4202 if (Cur->isRecord()) { 4203 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4204 : diag::err_member_extra_qualification) 4205 << Name << FixItHint::CreateRemoval(SS.getRange()); 4206 SS.clear(); 4207 } else { 4208 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4209 } 4210 return false; 4211 } 4212 4213 // Check whether the qualifying scope encloses the scope of the original 4214 // declaration. 4215 if (!Cur->Encloses(DC)) { 4216 if (Cur->isRecord()) 4217 Diag(Loc, diag::err_member_qualification) 4218 << Name << SS.getRange(); 4219 else if (isa<TranslationUnitDecl>(DC)) 4220 Diag(Loc, diag::err_invalid_declarator_global_scope) 4221 << Name << SS.getRange(); 4222 else if (isa<FunctionDecl>(Cur)) 4223 Diag(Loc, diag::err_invalid_declarator_in_function) 4224 << Name << SS.getRange(); 4225 else if (isa<BlockDecl>(Cur)) 4226 Diag(Loc, diag::err_invalid_declarator_in_block) 4227 << Name << SS.getRange(); 4228 else 4229 Diag(Loc, diag::err_invalid_declarator_scope) 4230 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4231 4232 return true; 4233 } 4234 4235 if (Cur->isRecord()) { 4236 // Cannot qualify members within a class. 4237 Diag(Loc, diag::err_member_qualification) 4238 << Name << SS.getRange(); 4239 SS.clear(); 4240 4241 // C++ constructors and destructors with incorrect scopes can break 4242 // our AST invariants by having the wrong underlying types. If 4243 // that's the case, then drop this declaration entirely. 4244 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4245 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4246 !Context.hasSameType(Name.getCXXNameType(), 4247 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4248 return true; 4249 4250 return false; 4251 } 4252 4253 // C++11 [dcl.meaning]p1: 4254 // [...] "The nested-name-specifier of the qualified declarator-id shall 4255 // not begin with a decltype-specifer" 4256 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4257 while (SpecLoc.getPrefix()) 4258 SpecLoc = SpecLoc.getPrefix(); 4259 if (dyn_cast_or_null<DecltypeType>( 4260 SpecLoc.getNestedNameSpecifier()->getAsType())) 4261 Diag(Loc, diag::err_decltype_in_declarator) 4262 << SpecLoc.getTypeLoc().getSourceRange(); 4263 4264 return false; 4265 } 4266 4267 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4268 MultiTemplateParamsArg TemplateParamLists) { 4269 // TODO: consider using NameInfo for diagnostic. 4270 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4271 DeclarationName Name = NameInfo.getName(); 4272 4273 // All of these full declarators require an identifier. If it doesn't have 4274 // one, the ParsedFreeStandingDeclSpec action should be used. 4275 if (!Name) { 4276 if (!D.isInvalidType()) // Reject this if we think it is valid. 4277 Diag(D.getDeclSpec().getLocStart(), 4278 diag::err_declarator_need_ident) 4279 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4280 return nullptr; 4281 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4282 return nullptr; 4283 4284 // The scope passed in may not be a decl scope. Zip up the scope tree until 4285 // we find one that is. 4286 while ((S->getFlags() & Scope::DeclScope) == 0 || 4287 (S->getFlags() & Scope::TemplateParamScope) != 0) 4288 S = S->getParent(); 4289 4290 DeclContext *DC = CurContext; 4291 if (D.getCXXScopeSpec().isInvalid()) 4292 D.setInvalidType(); 4293 else if (D.getCXXScopeSpec().isSet()) { 4294 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4295 UPPC_DeclarationQualifier)) 4296 return nullptr; 4297 4298 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4299 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4300 if (!DC || isa<EnumDecl>(DC)) { 4301 // If we could not compute the declaration context, it's because the 4302 // declaration context is dependent but does not refer to a class, 4303 // class template, or class template partial specialization. Complain 4304 // and return early, to avoid the coming semantic disaster. 4305 Diag(D.getIdentifierLoc(), 4306 diag::err_template_qualified_declarator_no_match) 4307 << D.getCXXScopeSpec().getScopeRep() 4308 << D.getCXXScopeSpec().getRange(); 4309 return nullptr; 4310 } 4311 bool IsDependentContext = DC->isDependentContext(); 4312 4313 if (!IsDependentContext && 4314 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4315 return nullptr; 4316 4317 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4318 Diag(D.getIdentifierLoc(), 4319 diag::err_member_def_undefined_record) 4320 << Name << DC << D.getCXXScopeSpec().getRange(); 4321 D.setInvalidType(); 4322 } else if (!D.getDeclSpec().isFriendSpecified()) { 4323 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4324 Name, D.getIdentifierLoc())) { 4325 if (DC->isRecord()) 4326 return nullptr; 4327 4328 D.setInvalidType(); 4329 } 4330 } 4331 4332 // Check whether we need to rebuild the type of the given 4333 // declaration in the current instantiation. 4334 if (EnteringContext && IsDependentContext && 4335 TemplateParamLists.size() != 0) { 4336 ContextRAII SavedContext(*this, DC); 4337 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4338 D.setInvalidType(); 4339 } 4340 } 4341 4342 if (DiagnoseClassNameShadow(DC, NameInfo)) 4343 // If this is a typedef, we'll end up spewing multiple diagnostics. 4344 // Just return early; it's safer. 4345 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4346 return nullptr; 4347 4348 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4349 QualType R = TInfo->getType(); 4350 4351 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4352 UPPC_DeclarationType)) 4353 D.setInvalidType(); 4354 4355 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4356 ForRedeclaration); 4357 4358 // See if this is a redefinition of a variable in the same scope. 4359 if (!D.getCXXScopeSpec().isSet()) { 4360 bool IsLinkageLookup = false; 4361 bool CreateBuiltins = false; 4362 4363 // If the declaration we're planning to build will be a function 4364 // or object with linkage, then look for another declaration with 4365 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4366 // 4367 // If the declaration we're planning to build will be declared with 4368 // external linkage in the translation unit, create any builtin with 4369 // the same name. 4370 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4371 /* Do nothing*/; 4372 else if (CurContext->isFunctionOrMethod() && 4373 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4374 R->isFunctionType())) { 4375 IsLinkageLookup = true; 4376 CreateBuiltins = 4377 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4378 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4379 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4380 CreateBuiltins = true; 4381 4382 if (IsLinkageLookup) 4383 Previous.clear(LookupRedeclarationWithLinkage); 4384 4385 LookupName(Previous, S, CreateBuiltins); 4386 } else { // Something like "int foo::x;" 4387 LookupQualifiedName(Previous, DC); 4388 4389 // C++ [dcl.meaning]p1: 4390 // When the declarator-id is qualified, the declaration shall refer to a 4391 // previously declared member of the class or namespace to which the 4392 // qualifier refers (or, in the case of a namespace, of an element of the 4393 // inline namespace set of that namespace (7.3.1)) or to a specialization 4394 // thereof; [...] 4395 // 4396 // Note that we already checked the context above, and that we do not have 4397 // enough information to make sure that Previous contains the declaration 4398 // we want to match. For example, given: 4399 // 4400 // class X { 4401 // void f(); 4402 // void f(float); 4403 // }; 4404 // 4405 // void X::f(int) { } // ill-formed 4406 // 4407 // In this case, Previous will point to the overload set 4408 // containing the two f's declared in X, but neither of them 4409 // matches. 4410 4411 // C++ [dcl.meaning]p1: 4412 // [...] the member shall not merely have been introduced by a 4413 // using-declaration in the scope of the class or namespace nominated by 4414 // the nested-name-specifier of the declarator-id. 4415 RemoveUsingDecls(Previous); 4416 } 4417 4418 if (Previous.isSingleResult() && 4419 Previous.getFoundDecl()->isTemplateParameter()) { 4420 // Maybe we will complain about the shadowed template parameter. 4421 if (!D.isInvalidType()) 4422 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4423 Previous.getFoundDecl()); 4424 4425 // Just pretend that we didn't see the previous declaration. 4426 Previous.clear(); 4427 } 4428 4429 // In C++, the previous declaration we find might be a tag type 4430 // (class or enum). In this case, the new declaration will hide the 4431 // tag type. Note that this does does not apply if we're declaring a 4432 // typedef (C++ [dcl.typedef]p4). 4433 if (Previous.isSingleTagDecl() && 4434 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4435 Previous.clear(); 4436 4437 // Check that there are no default arguments other than in the parameters 4438 // of a function declaration (C++ only). 4439 if (getLangOpts().CPlusPlus) 4440 CheckExtraCXXDefaultArguments(D); 4441 4442 NamedDecl *New; 4443 4444 bool AddToScope = true; 4445 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4446 if (TemplateParamLists.size()) { 4447 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4448 return nullptr; 4449 } 4450 4451 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4452 } else if (R->isFunctionType()) { 4453 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4454 TemplateParamLists, 4455 AddToScope); 4456 } else { 4457 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4458 AddToScope); 4459 } 4460 4461 if (!New) 4462 return nullptr; 4463 4464 // If this has an identifier and is not an invalid redeclaration or 4465 // function template specialization, add it to the scope stack. 4466 if (New->getDeclName() && AddToScope && 4467 !(D.isRedeclaration() && New->isInvalidDecl())) { 4468 // Only make a locally-scoped extern declaration visible if it is the first 4469 // declaration of this entity. Qualified lookup for such an entity should 4470 // only find this declaration if there is no visible declaration of it. 4471 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4472 PushOnScopeChains(New, S, AddToContext); 4473 if (!AddToContext) 4474 CurContext->addHiddenDecl(New); 4475 } 4476 4477 return New; 4478 } 4479 4480 /// Helper method to turn variable array types into constant array 4481 /// types in certain situations which would otherwise be errors (for 4482 /// GCC compatibility). 4483 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4484 ASTContext &Context, 4485 bool &SizeIsNegative, 4486 llvm::APSInt &Oversized) { 4487 // This method tries to turn a variable array into a constant 4488 // array even when the size isn't an ICE. This is necessary 4489 // for compatibility with code that depends on gcc's buggy 4490 // constant expression folding, like struct {char x[(int)(char*)2];} 4491 SizeIsNegative = false; 4492 Oversized = 0; 4493 4494 if (T->isDependentType()) 4495 return QualType(); 4496 4497 QualifierCollector Qs; 4498 const Type *Ty = Qs.strip(T); 4499 4500 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4501 QualType Pointee = PTy->getPointeeType(); 4502 QualType FixedType = 4503 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4504 Oversized); 4505 if (FixedType.isNull()) return FixedType; 4506 FixedType = Context.getPointerType(FixedType); 4507 return Qs.apply(Context, FixedType); 4508 } 4509 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4510 QualType Inner = PTy->getInnerType(); 4511 QualType FixedType = 4512 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4513 Oversized); 4514 if (FixedType.isNull()) return FixedType; 4515 FixedType = Context.getParenType(FixedType); 4516 return Qs.apply(Context, FixedType); 4517 } 4518 4519 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4520 if (!VLATy) 4521 return QualType(); 4522 // FIXME: We should probably handle this case 4523 if (VLATy->getElementType()->isVariablyModifiedType()) 4524 return QualType(); 4525 4526 llvm::APSInt Res; 4527 if (!VLATy->getSizeExpr() || 4528 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4529 return QualType(); 4530 4531 // Check whether the array size is negative. 4532 if (Res.isSigned() && Res.isNegative()) { 4533 SizeIsNegative = true; 4534 return QualType(); 4535 } 4536 4537 // Check whether the array is too large to be addressed. 4538 unsigned ActiveSizeBits 4539 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4540 Res); 4541 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4542 Oversized = Res; 4543 return QualType(); 4544 } 4545 4546 return Context.getConstantArrayType(VLATy->getElementType(), 4547 Res, ArrayType::Normal, 0); 4548 } 4549 4550 static void 4551 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4552 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4553 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4554 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4555 DstPTL.getPointeeLoc()); 4556 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4557 return; 4558 } 4559 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4560 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4561 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4562 DstPTL.getInnerLoc()); 4563 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4564 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4565 return; 4566 } 4567 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4568 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4569 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4570 TypeLoc DstElemTL = DstATL.getElementLoc(); 4571 DstElemTL.initializeFullCopy(SrcElemTL); 4572 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4573 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4574 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4575 } 4576 4577 /// Helper method to turn variable array types into constant array 4578 /// types in certain situations which would otherwise be errors (for 4579 /// GCC compatibility). 4580 static TypeSourceInfo* 4581 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4582 ASTContext &Context, 4583 bool &SizeIsNegative, 4584 llvm::APSInt &Oversized) { 4585 QualType FixedTy 4586 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4587 SizeIsNegative, Oversized); 4588 if (FixedTy.isNull()) 4589 return nullptr; 4590 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4591 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4592 FixedTInfo->getTypeLoc()); 4593 return FixedTInfo; 4594 } 4595 4596 /// \brief Register the given locally-scoped extern "C" declaration so 4597 /// that it can be found later for redeclarations. We include any extern "C" 4598 /// declaration that is not visible in the translation unit here, not just 4599 /// function-scope declarations. 4600 void 4601 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4602 if (!getLangOpts().CPlusPlus && 4603 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4604 // Don't need to track declarations in the TU in C. 4605 return; 4606 4607 // Note that we have a locally-scoped external with this name. 4608 // FIXME: There can be multiple such declarations if they are functions marked 4609 // __attribute__((overloadable)) declared in function scope in C. 4610 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4611 } 4612 4613 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4614 if (ExternalSource) { 4615 // Load locally-scoped external decls from the external source. 4616 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4617 SmallVector<NamedDecl *, 4> Decls; 4618 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4619 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4620 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4621 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4622 if (Pos == LocallyScopedExternCDecls.end()) 4623 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4624 } 4625 } 4626 4627 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4628 return D ? D->getMostRecentDecl() : nullptr; 4629 } 4630 4631 /// \brief Diagnose function specifiers on a declaration of an identifier that 4632 /// does not identify a function. 4633 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4634 // FIXME: We should probably indicate the identifier in question to avoid 4635 // confusion for constructs like "inline int a(), b;" 4636 if (DS.isInlineSpecified()) 4637 Diag(DS.getInlineSpecLoc(), 4638 diag::err_inline_non_function); 4639 4640 if (DS.isVirtualSpecified()) 4641 Diag(DS.getVirtualSpecLoc(), 4642 diag::err_virtual_non_function); 4643 4644 if (DS.isExplicitSpecified()) 4645 Diag(DS.getExplicitSpecLoc(), 4646 diag::err_explicit_non_function); 4647 4648 if (DS.isNoreturnSpecified()) 4649 Diag(DS.getNoreturnSpecLoc(), 4650 diag::err_noreturn_non_function); 4651 } 4652 4653 NamedDecl* 4654 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4655 TypeSourceInfo *TInfo, LookupResult &Previous) { 4656 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4657 if (D.getCXXScopeSpec().isSet()) { 4658 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4659 << D.getCXXScopeSpec().getRange(); 4660 D.setInvalidType(); 4661 // Pretend we didn't see the scope specifier. 4662 DC = CurContext; 4663 Previous.clear(); 4664 } 4665 4666 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4667 4668 if (D.getDeclSpec().isConstexprSpecified()) 4669 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4670 << 1; 4671 4672 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4673 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4674 << D.getName().getSourceRange(); 4675 return nullptr; 4676 } 4677 4678 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4679 if (!NewTD) return nullptr; 4680 4681 // Handle attributes prior to checking for duplicates in MergeVarDecl 4682 ProcessDeclAttributes(S, NewTD, D); 4683 4684 CheckTypedefForVariablyModifiedType(S, NewTD); 4685 4686 bool Redeclaration = D.isRedeclaration(); 4687 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4688 D.setRedeclaration(Redeclaration); 4689 return ND; 4690 } 4691 4692 void 4693 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4694 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4695 // then it shall have block scope. 4696 // Note that variably modified types must be fixed before merging the decl so 4697 // that redeclarations will match. 4698 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4699 QualType T = TInfo->getType(); 4700 if (T->isVariablyModifiedType()) { 4701 getCurFunction()->setHasBranchProtectedScope(); 4702 4703 if (S->getFnParent() == nullptr) { 4704 bool SizeIsNegative; 4705 llvm::APSInt Oversized; 4706 TypeSourceInfo *FixedTInfo = 4707 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4708 SizeIsNegative, 4709 Oversized); 4710 if (FixedTInfo) { 4711 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4712 NewTD->setTypeSourceInfo(FixedTInfo); 4713 } else { 4714 if (SizeIsNegative) 4715 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4716 else if (T->isVariableArrayType()) 4717 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4718 else if (Oversized.getBoolValue()) 4719 Diag(NewTD->getLocation(), diag::err_array_too_large) 4720 << Oversized.toString(10); 4721 else 4722 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4723 NewTD->setInvalidDecl(); 4724 } 4725 } 4726 } 4727 } 4728 4729 4730 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4731 /// declares a typedef-name, either using the 'typedef' type specifier or via 4732 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4733 NamedDecl* 4734 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4735 LookupResult &Previous, bool &Redeclaration) { 4736 // Merge the decl with the existing one if appropriate. If the decl is 4737 // in an outer scope, it isn't the same thing. 4738 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4739 /*AllowInlineNamespace*/false); 4740 filterNonConflictingPreviousDecls(Context, NewTD, Previous); 4741 if (!Previous.empty()) { 4742 Redeclaration = true; 4743 MergeTypedefNameDecl(NewTD, Previous); 4744 } 4745 4746 // If this is the C FILE type, notify the AST context. 4747 if (IdentifierInfo *II = NewTD->getIdentifier()) 4748 if (!NewTD->isInvalidDecl() && 4749 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4750 if (II->isStr("FILE")) 4751 Context.setFILEDecl(NewTD); 4752 else if (II->isStr("jmp_buf")) 4753 Context.setjmp_bufDecl(NewTD); 4754 else if (II->isStr("sigjmp_buf")) 4755 Context.setsigjmp_bufDecl(NewTD); 4756 else if (II->isStr("ucontext_t")) 4757 Context.setucontext_tDecl(NewTD); 4758 } 4759 4760 return NewTD; 4761 } 4762 4763 /// \brief Determines whether the given declaration is an out-of-scope 4764 /// previous declaration. 4765 /// 4766 /// This routine should be invoked when name lookup has found a 4767 /// previous declaration (PrevDecl) that is not in the scope where a 4768 /// new declaration by the same name is being introduced. If the new 4769 /// declaration occurs in a local scope, previous declarations with 4770 /// linkage may still be considered previous declarations (C99 4771 /// 6.2.2p4-5, C++ [basic.link]p6). 4772 /// 4773 /// \param PrevDecl the previous declaration found by name 4774 /// lookup 4775 /// 4776 /// \param DC the context in which the new declaration is being 4777 /// declared. 4778 /// 4779 /// \returns true if PrevDecl is an out-of-scope previous declaration 4780 /// for a new delcaration with the same name. 4781 static bool 4782 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4783 ASTContext &Context) { 4784 if (!PrevDecl) 4785 return false; 4786 4787 if (!PrevDecl->hasLinkage()) 4788 return false; 4789 4790 if (Context.getLangOpts().CPlusPlus) { 4791 // C++ [basic.link]p6: 4792 // If there is a visible declaration of an entity with linkage 4793 // having the same name and type, ignoring entities declared 4794 // outside the innermost enclosing namespace scope, the block 4795 // scope declaration declares that same entity and receives the 4796 // linkage of the previous declaration. 4797 DeclContext *OuterContext = DC->getRedeclContext(); 4798 if (!OuterContext->isFunctionOrMethod()) 4799 // This rule only applies to block-scope declarations. 4800 return false; 4801 4802 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 4803 if (PrevOuterContext->isRecord()) 4804 // We found a member function: ignore it. 4805 return false; 4806 4807 // Find the innermost enclosing namespace for the new and 4808 // previous declarations. 4809 OuterContext = OuterContext->getEnclosingNamespaceContext(); 4810 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 4811 4812 // The previous declaration is in a different namespace, so it 4813 // isn't the same function. 4814 if (!OuterContext->Equals(PrevOuterContext)) 4815 return false; 4816 } 4817 4818 return true; 4819 } 4820 4821 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 4822 CXXScopeSpec &SS = D.getCXXScopeSpec(); 4823 if (!SS.isSet()) return; 4824 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 4825 } 4826 4827 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 4828 QualType type = decl->getType(); 4829 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4830 if (lifetime == Qualifiers::OCL_Autoreleasing) { 4831 // Various kinds of declaration aren't allowed to be __autoreleasing. 4832 unsigned kind = -1U; 4833 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4834 if (var->hasAttr<BlocksAttr>()) 4835 kind = 0; // __block 4836 else if (!var->hasLocalStorage()) 4837 kind = 1; // global 4838 } else if (isa<ObjCIvarDecl>(decl)) { 4839 kind = 3; // ivar 4840 } else if (isa<FieldDecl>(decl)) { 4841 kind = 2; // field 4842 } 4843 4844 if (kind != -1U) { 4845 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 4846 << kind; 4847 } 4848 } else if (lifetime == Qualifiers::OCL_None) { 4849 // Try to infer lifetime. 4850 if (!type->isObjCLifetimeType()) 4851 return false; 4852 4853 lifetime = type->getObjCARCImplicitLifetime(); 4854 type = Context.getLifetimeQualifiedType(type, lifetime); 4855 decl->setType(type); 4856 } 4857 4858 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 4859 // Thread-local variables cannot have lifetime. 4860 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 4861 var->getTLSKind()) { 4862 Diag(var->getLocation(), diag::err_arc_thread_ownership) 4863 << var->getType(); 4864 return true; 4865 } 4866 } 4867 4868 return false; 4869 } 4870 4871 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 4872 // Ensure that an auto decl is deduced otherwise the checks below might cache 4873 // the wrong linkage. 4874 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 4875 4876 // 'weak' only applies to declarations with external linkage. 4877 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 4878 if (!ND.isExternallyVisible()) { 4879 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 4880 ND.dropAttr<WeakAttr>(); 4881 } 4882 } 4883 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 4884 if (ND.isExternallyVisible()) { 4885 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 4886 ND.dropAttr<WeakRefAttr>(); 4887 } 4888 } 4889 4890 // 'selectany' only applies to externally visible varable declarations. 4891 // It does not apply to functions. 4892 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 4893 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 4894 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 4895 ND.dropAttr<SelectAnyAttr>(); 4896 } 4897 } 4898 4899 // dll attributes require external linkage. 4900 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 4901 if (!ND.isExternallyVisible()) { 4902 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4903 << &ND << Attr; 4904 ND.setInvalidDecl(); 4905 } 4906 } 4907 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 4908 if (!ND.isExternallyVisible()) { 4909 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 4910 << &ND << Attr; 4911 ND.setInvalidDecl(); 4912 } 4913 } 4914 } 4915 4916 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 4917 NamedDecl *NewDecl, 4918 bool IsSpecialization) { 4919 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 4920 OldDecl = OldTD->getTemplatedDecl(); 4921 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 4922 NewDecl = NewTD->getTemplatedDecl(); 4923 4924 if (!OldDecl || !NewDecl) 4925 return; 4926 4927 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 4928 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 4929 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 4930 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 4931 4932 // dllimport and dllexport are inheritable attributes so we have to exclude 4933 // inherited attribute instances. 4934 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 4935 (NewExportAttr && !NewExportAttr->isInherited()); 4936 4937 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 4938 // the only exception being explicit specializations. 4939 // Implicitly generated declarations are also excluded for now because there 4940 // is no other way to switch these to use dllimport or dllexport. 4941 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 4942 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 4943 S.Diag(NewDecl->getLocation(), diag::err_attribute_dll_redeclaration) 4944 << NewDecl 4945 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 4946 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4947 NewDecl->setInvalidDecl(); 4948 return; 4949 } 4950 4951 // A redeclaration is not allowed to drop a dllimport attribute, the only 4952 // exception being inline function definitions. 4953 // NB: MSVC converts such a declaration to dllexport. 4954 bool IsInline = false, IsStaticDataMember = false; 4955 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 4956 // Ignore static data because out-of-line definitions are diagnosed 4957 // separately. 4958 IsStaticDataMember = VD->isStaticDataMember(); 4959 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) 4960 IsInline = FD->isInlined(); 4961 4962 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember) { 4963 S.Diag(NewDecl->getLocation(), 4964 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4965 << NewDecl << OldImportAttr; 4966 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 4967 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 4968 OldDecl->dropAttr<DLLImportAttr>(); 4969 NewDecl->dropAttr<DLLImportAttr>(); 4970 } 4971 } 4972 4973 /// Given that we are within the definition of the given function, 4974 /// will that definition behave like C99's 'inline', where the 4975 /// definition is discarded except for optimization purposes? 4976 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 4977 // Try to avoid calling GetGVALinkageForFunction. 4978 4979 // All cases of this require the 'inline' keyword. 4980 if (!FD->isInlined()) return false; 4981 4982 // This is only possible in C++ with the gnu_inline attribute. 4983 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 4984 return false; 4985 4986 // Okay, go ahead and call the relatively-more-expensive function. 4987 4988 #ifndef NDEBUG 4989 // AST quite reasonably asserts that it's working on a function 4990 // definition. We don't really have a way to tell it that we're 4991 // currently defining the function, so just lie to it in +Asserts 4992 // builds. This is an awful hack. 4993 FD->setLazyBody(1); 4994 #endif 4995 4996 bool isC99Inline = 4997 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 4998 4999 #ifndef NDEBUG 5000 FD->setLazyBody(0); 5001 #endif 5002 5003 return isC99Inline; 5004 } 5005 5006 /// Determine whether a variable is extern "C" prior to attaching 5007 /// an initializer. We can't just call isExternC() here, because that 5008 /// will also compute and cache whether the declaration is externally 5009 /// visible, which might change when we attach the initializer. 5010 /// 5011 /// This can only be used if the declaration is known to not be a 5012 /// redeclaration of an internal linkage declaration. 5013 /// 5014 /// For instance: 5015 /// 5016 /// auto x = []{}; 5017 /// 5018 /// Attaching the initializer here makes this declaration not externally 5019 /// visible, because its type has internal linkage. 5020 /// 5021 /// FIXME: This is a hack. 5022 template<typename T> 5023 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5024 if (S.getLangOpts().CPlusPlus) { 5025 // In C++, the overloadable attribute negates the effects of extern "C". 5026 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5027 return false; 5028 } 5029 return D->isExternC(); 5030 } 5031 5032 static bool shouldConsiderLinkage(const VarDecl *VD) { 5033 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5034 if (DC->isFunctionOrMethod()) 5035 return VD->hasExternalStorage(); 5036 if (DC->isFileContext()) 5037 return true; 5038 if (DC->isRecord()) 5039 return false; 5040 llvm_unreachable("Unexpected context"); 5041 } 5042 5043 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5044 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5045 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5046 return true; 5047 if (DC->isRecord()) 5048 return false; 5049 llvm_unreachable("Unexpected context"); 5050 } 5051 5052 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5053 AttributeList::Kind Kind) { 5054 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5055 if (L->getKind() == Kind) 5056 return true; 5057 return false; 5058 } 5059 5060 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5061 AttributeList::Kind Kind) { 5062 // Check decl attributes on the DeclSpec. 5063 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5064 return true; 5065 5066 // Walk the declarator structure, checking decl attributes that were in a type 5067 // position to the decl itself. 5068 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5069 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5070 return true; 5071 } 5072 5073 // Finally, check attributes on the decl itself. 5074 return hasParsedAttr(S, PD.getAttributes(), Kind); 5075 } 5076 5077 /// Adjust the \c DeclContext for a function or variable that might be a 5078 /// function-local external declaration. 5079 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5080 if (!DC->isFunctionOrMethod()) 5081 return false; 5082 5083 // If this is a local extern function or variable declared within a function 5084 // template, don't add it into the enclosing namespace scope until it is 5085 // instantiated; it might have a dependent type right now. 5086 if (DC->isDependentContext()) 5087 return true; 5088 5089 // C++11 [basic.link]p7: 5090 // When a block scope declaration of an entity with linkage is not found to 5091 // refer to some other declaration, then that entity is a member of the 5092 // innermost enclosing namespace. 5093 // 5094 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5095 // semantically-enclosing namespace, not a lexically-enclosing one. 5096 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5097 DC = DC->getParent(); 5098 return true; 5099 } 5100 5101 NamedDecl * 5102 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5103 TypeSourceInfo *TInfo, LookupResult &Previous, 5104 MultiTemplateParamsArg TemplateParamLists, 5105 bool &AddToScope) { 5106 QualType R = TInfo->getType(); 5107 DeclarationName Name = GetNameForDeclarator(D).getName(); 5108 5109 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5110 VarDecl::StorageClass SC = 5111 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5112 5113 // dllimport globals without explicit storage class are treated as extern. We 5114 // have to change the storage class this early to get the right DeclContext. 5115 if (SC == SC_None && !DC->isRecord() && 5116 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5117 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5118 SC = SC_Extern; 5119 5120 DeclContext *OriginalDC = DC; 5121 bool IsLocalExternDecl = SC == SC_Extern && 5122 adjustContextForLocalExternDecl(DC); 5123 5124 if (getLangOpts().OpenCL) { 5125 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5126 QualType NR = R; 5127 while (NR->isPointerType()) { 5128 if (NR->isFunctionPointerType()) { 5129 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5130 D.setInvalidType(); 5131 break; 5132 } 5133 NR = NR->getPointeeType(); 5134 } 5135 5136 if (!getOpenCLOptions().cl_khr_fp16) { 5137 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5138 // half array type (unless the cl_khr_fp16 extension is enabled). 5139 if (Context.getBaseElementType(R)->isHalfType()) { 5140 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5141 D.setInvalidType(); 5142 } 5143 } 5144 } 5145 5146 if (SCSpec == DeclSpec::SCS_mutable) { 5147 // mutable can only appear on non-static class members, so it's always 5148 // an error here 5149 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5150 D.setInvalidType(); 5151 SC = SC_None; 5152 } 5153 5154 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5155 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5156 D.getDeclSpec().getStorageClassSpecLoc())) { 5157 // In C++11, the 'register' storage class specifier is deprecated. 5158 // Suppress the warning in system macros, it's used in macros in some 5159 // popular C system headers, such as in glibc's htonl() macro. 5160 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5161 diag::warn_deprecated_register) 5162 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5163 } 5164 5165 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5166 if (!II) { 5167 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5168 << Name; 5169 return nullptr; 5170 } 5171 5172 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5173 5174 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5175 // C99 6.9p2: The storage-class specifiers auto and register shall not 5176 // appear in the declaration specifiers in an external declaration. 5177 // Global Register+Asm is a GNU extension we support. 5178 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5179 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5180 D.setInvalidType(); 5181 } 5182 } 5183 5184 if (getLangOpts().OpenCL) { 5185 // Set up the special work-group-local storage class for variables in the 5186 // OpenCL __local address space. 5187 if (R.getAddressSpace() == LangAS::opencl_local) { 5188 SC = SC_OpenCLWorkGroupLocal; 5189 } 5190 5191 // OpenCL v1.2 s6.9.b p4: 5192 // The sampler type cannot be used with the __local and __global address 5193 // space qualifiers. 5194 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5195 R.getAddressSpace() == LangAS::opencl_global)) { 5196 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5197 } 5198 5199 // OpenCL 1.2 spec, p6.9 r: 5200 // The event type cannot be used to declare a program scope variable. 5201 // The event type cannot be used with the __local, __constant and __global 5202 // address space qualifiers. 5203 if (R->isEventT()) { 5204 if (S->getParent() == nullptr) { 5205 Diag(D.getLocStart(), diag::err_event_t_global_var); 5206 D.setInvalidType(); 5207 } 5208 5209 if (R.getAddressSpace()) { 5210 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5211 D.setInvalidType(); 5212 } 5213 } 5214 } 5215 5216 bool IsExplicitSpecialization = false; 5217 bool IsVariableTemplateSpecialization = false; 5218 bool IsPartialSpecialization = false; 5219 bool IsVariableTemplate = false; 5220 VarDecl *NewVD = nullptr; 5221 VarTemplateDecl *NewTemplate = nullptr; 5222 TemplateParameterList *TemplateParams = nullptr; 5223 if (!getLangOpts().CPlusPlus) { 5224 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5225 D.getIdentifierLoc(), II, 5226 R, TInfo, SC); 5227 5228 if (D.isInvalidType()) 5229 NewVD->setInvalidDecl(); 5230 } else { 5231 bool Invalid = false; 5232 5233 if (DC->isRecord() && !CurContext->isRecord()) { 5234 // This is an out-of-line definition of a static data member. 5235 switch (SC) { 5236 case SC_None: 5237 break; 5238 case SC_Static: 5239 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5240 diag::err_static_out_of_line) 5241 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5242 break; 5243 case SC_Auto: 5244 case SC_Register: 5245 case SC_Extern: 5246 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5247 // to names of variables declared in a block or to function parameters. 5248 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5249 // of class members 5250 5251 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5252 diag::err_storage_class_for_static_member) 5253 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5254 break; 5255 case SC_PrivateExtern: 5256 llvm_unreachable("C storage class in c++!"); 5257 case SC_OpenCLWorkGroupLocal: 5258 llvm_unreachable("OpenCL storage class in c++!"); 5259 } 5260 } 5261 5262 if (SC == SC_Static && CurContext->isRecord()) { 5263 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5264 if (RD->isLocalClass()) 5265 Diag(D.getIdentifierLoc(), 5266 diag::err_static_data_member_not_allowed_in_local_class) 5267 << Name << RD->getDeclName(); 5268 5269 // C++98 [class.union]p1: If a union contains a static data member, 5270 // the program is ill-formed. C++11 drops this restriction. 5271 if (RD->isUnion()) 5272 Diag(D.getIdentifierLoc(), 5273 getLangOpts().CPlusPlus11 5274 ? diag::warn_cxx98_compat_static_data_member_in_union 5275 : diag::ext_static_data_member_in_union) << Name; 5276 // We conservatively disallow static data members in anonymous structs. 5277 else if (!RD->getDeclName()) 5278 Diag(D.getIdentifierLoc(), 5279 diag::err_static_data_member_not_allowed_in_anon_struct) 5280 << Name << RD->isUnion(); 5281 } 5282 } 5283 5284 // Match up the template parameter lists with the scope specifier, then 5285 // determine whether we have a template or a template specialization. 5286 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5287 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5288 D.getCXXScopeSpec(), 5289 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5290 ? D.getName().TemplateId 5291 : nullptr, 5292 TemplateParamLists, 5293 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5294 5295 if (TemplateParams) { 5296 if (!TemplateParams->size() && 5297 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5298 // There is an extraneous 'template<>' for this variable. Complain 5299 // about it, but allow the declaration of the variable. 5300 Diag(TemplateParams->getTemplateLoc(), 5301 diag::err_template_variable_noparams) 5302 << II 5303 << SourceRange(TemplateParams->getTemplateLoc(), 5304 TemplateParams->getRAngleLoc()); 5305 TemplateParams = nullptr; 5306 } else { 5307 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5308 // This is an explicit specialization or a partial specialization. 5309 // FIXME: Check that we can declare a specialization here. 5310 IsVariableTemplateSpecialization = true; 5311 IsPartialSpecialization = TemplateParams->size() > 0; 5312 } else { // if (TemplateParams->size() > 0) 5313 // This is a template declaration. 5314 IsVariableTemplate = true; 5315 5316 // Check that we can declare a template here. 5317 if (CheckTemplateDeclScope(S, TemplateParams)) 5318 return nullptr; 5319 5320 // Only C++1y supports variable templates (N3651). 5321 Diag(D.getIdentifierLoc(), 5322 getLangOpts().CPlusPlus1y 5323 ? diag::warn_cxx11_compat_variable_template 5324 : diag::ext_variable_template); 5325 } 5326 } 5327 } else { 5328 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5329 "should have a 'template<>' for this decl"); 5330 } 5331 5332 if (IsVariableTemplateSpecialization) { 5333 SourceLocation TemplateKWLoc = 5334 TemplateParamLists.size() > 0 5335 ? TemplateParamLists[0]->getTemplateLoc() 5336 : SourceLocation(); 5337 DeclResult Res = ActOnVarTemplateSpecialization( 5338 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5339 IsPartialSpecialization); 5340 if (Res.isInvalid()) 5341 return nullptr; 5342 NewVD = cast<VarDecl>(Res.get()); 5343 AddToScope = false; 5344 } else 5345 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5346 D.getIdentifierLoc(), II, R, TInfo, SC); 5347 5348 // If this is supposed to be a variable template, create it as such. 5349 if (IsVariableTemplate) { 5350 NewTemplate = 5351 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5352 TemplateParams, NewVD); 5353 NewVD->setDescribedVarTemplate(NewTemplate); 5354 } 5355 5356 // If this decl has an auto type in need of deduction, make a note of the 5357 // Decl so we can diagnose uses of it in its own initializer. 5358 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5359 ParsingInitForAutoVars.insert(NewVD); 5360 5361 if (D.isInvalidType() || Invalid) { 5362 NewVD->setInvalidDecl(); 5363 if (NewTemplate) 5364 NewTemplate->setInvalidDecl(); 5365 } 5366 5367 SetNestedNameSpecifier(NewVD, D); 5368 5369 // If we have any template parameter lists that don't directly belong to 5370 // the variable (matching the scope specifier), store them. 5371 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5372 if (TemplateParamLists.size() > VDTemplateParamLists) 5373 NewVD->setTemplateParameterListsInfo( 5374 Context, TemplateParamLists.size() - VDTemplateParamLists, 5375 TemplateParamLists.data()); 5376 5377 if (D.getDeclSpec().isConstexprSpecified()) 5378 NewVD->setConstexpr(true); 5379 } 5380 5381 // Set the lexical context. If the declarator has a C++ scope specifier, the 5382 // lexical context will be different from the semantic context. 5383 NewVD->setLexicalDeclContext(CurContext); 5384 if (NewTemplate) 5385 NewTemplate->setLexicalDeclContext(CurContext); 5386 5387 if (IsLocalExternDecl) 5388 NewVD->setLocalExternDecl(); 5389 5390 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5391 if (NewVD->hasLocalStorage()) { 5392 // C++11 [dcl.stc]p4: 5393 // When thread_local is applied to a variable of block scope the 5394 // storage-class-specifier static is implied if it does not appear 5395 // explicitly. 5396 // Core issue: 'static' is not implied if the variable is declared 5397 // 'extern'. 5398 if (SCSpec == DeclSpec::SCS_unspecified && 5399 TSCS == DeclSpec::TSCS_thread_local && 5400 DC->isFunctionOrMethod()) 5401 NewVD->setTSCSpec(TSCS); 5402 else 5403 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5404 diag::err_thread_non_global) 5405 << DeclSpec::getSpecifierName(TSCS); 5406 } else if (!Context.getTargetInfo().isTLSSupported()) 5407 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5408 diag::err_thread_unsupported); 5409 else 5410 NewVD->setTSCSpec(TSCS); 5411 } 5412 5413 // C99 6.7.4p3 5414 // An inline definition of a function with external linkage shall 5415 // not contain a definition of a modifiable object with static or 5416 // thread storage duration... 5417 // We only apply this when the function is required to be defined 5418 // elsewhere, i.e. when the function is not 'extern inline'. Note 5419 // that a local variable with thread storage duration still has to 5420 // be marked 'static'. Also note that it's possible to get these 5421 // semantics in C++ using __attribute__((gnu_inline)). 5422 if (SC == SC_Static && S->getFnParent() != nullptr && 5423 !NewVD->getType().isConstQualified()) { 5424 FunctionDecl *CurFD = getCurFunctionDecl(); 5425 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5426 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5427 diag::warn_static_local_in_extern_inline); 5428 MaybeSuggestAddingStaticToDecl(CurFD); 5429 } 5430 } 5431 5432 if (D.getDeclSpec().isModulePrivateSpecified()) { 5433 if (IsVariableTemplateSpecialization) 5434 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5435 << (IsPartialSpecialization ? 1 : 0) 5436 << FixItHint::CreateRemoval( 5437 D.getDeclSpec().getModulePrivateSpecLoc()); 5438 else if (IsExplicitSpecialization) 5439 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5440 << 2 5441 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5442 else if (NewVD->hasLocalStorage()) 5443 Diag(NewVD->getLocation(), diag::err_module_private_local) 5444 << 0 << NewVD->getDeclName() 5445 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5446 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5447 else { 5448 NewVD->setModulePrivate(); 5449 if (NewTemplate) 5450 NewTemplate->setModulePrivate(); 5451 } 5452 } 5453 5454 // Handle attributes prior to checking for duplicates in MergeVarDecl 5455 ProcessDeclAttributes(S, NewVD, D); 5456 5457 if (getLangOpts().CUDA) { 5458 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5459 // storage [duration]." 5460 if (SC == SC_None && S->getFnParent() != nullptr && 5461 (NewVD->hasAttr<CUDASharedAttr>() || 5462 NewVD->hasAttr<CUDAConstantAttr>())) { 5463 NewVD->setStorageClass(SC_Static); 5464 } 5465 } 5466 5467 // Ensure that dllimport globals without explicit storage class are treated as 5468 // extern. The storage class is set above using parsed attributes. Now we can 5469 // check the VarDecl itself. 5470 assert(!NewVD->hasAttr<DLLImportAttr>() || 5471 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5472 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5473 5474 // In auto-retain/release, infer strong retension for variables of 5475 // retainable type. 5476 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5477 NewVD->setInvalidDecl(); 5478 5479 // Handle GNU asm-label extension (encoded as an attribute). 5480 if (Expr *E = (Expr*)D.getAsmLabel()) { 5481 // The parser guarantees this is a string. 5482 StringLiteral *SE = cast<StringLiteral>(E); 5483 StringRef Label = SE->getString(); 5484 if (S->getFnParent() != nullptr) { 5485 switch (SC) { 5486 case SC_None: 5487 case SC_Auto: 5488 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5489 break; 5490 case SC_Register: 5491 // Local Named register 5492 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5493 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5494 break; 5495 case SC_Static: 5496 case SC_Extern: 5497 case SC_PrivateExtern: 5498 case SC_OpenCLWorkGroupLocal: 5499 break; 5500 } 5501 } else if (SC == SC_Register) { 5502 // Global Named register 5503 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5504 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5505 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5506 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5507 NewVD->setInvalidDecl(true); 5508 } 5509 } 5510 5511 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5512 Context, Label, 0)); 5513 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5514 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5515 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5516 if (I != ExtnameUndeclaredIdentifiers.end()) { 5517 NewVD->addAttr(I->second); 5518 ExtnameUndeclaredIdentifiers.erase(I); 5519 } 5520 } 5521 5522 // Diagnose shadowed variables before filtering for scope. 5523 if (D.getCXXScopeSpec().isEmpty()) 5524 CheckShadow(S, NewVD, Previous); 5525 5526 // Don't consider existing declarations that are in a different 5527 // scope and are out-of-semantic-context declarations (if the new 5528 // declaration has linkage). 5529 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5530 D.getCXXScopeSpec().isNotEmpty() || 5531 IsExplicitSpecialization || 5532 IsVariableTemplateSpecialization); 5533 5534 // Check whether the previous declaration is in the same block scope. This 5535 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5536 if (getLangOpts().CPlusPlus && 5537 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5538 NewVD->setPreviousDeclInSameBlockScope( 5539 Previous.isSingleResult() && !Previous.isShadowed() && 5540 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5541 5542 if (!getLangOpts().CPlusPlus) { 5543 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5544 } else { 5545 // If this is an explicit specialization of a static data member, check it. 5546 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5547 CheckMemberSpecialization(NewVD, Previous)) 5548 NewVD->setInvalidDecl(); 5549 5550 // Merge the decl with the existing one if appropriate. 5551 if (!Previous.empty()) { 5552 if (Previous.isSingleResult() && 5553 isa<FieldDecl>(Previous.getFoundDecl()) && 5554 D.getCXXScopeSpec().isSet()) { 5555 // The user tried to define a non-static data member 5556 // out-of-line (C++ [dcl.meaning]p1). 5557 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5558 << D.getCXXScopeSpec().getRange(); 5559 Previous.clear(); 5560 NewVD->setInvalidDecl(); 5561 } 5562 } else if (D.getCXXScopeSpec().isSet()) { 5563 // No previous declaration in the qualifying scope. 5564 Diag(D.getIdentifierLoc(), diag::err_no_member) 5565 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5566 << D.getCXXScopeSpec().getRange(); 5567 NewVD->setInvalidDecl(); 5568 } 5569 5570 if (!IsVariableTemplateSpecialization) 5571 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5572 5573 if (NewTemplate) { 5574 VarTemplateDecl *PrevVarTemplate = 5575 NewVD->getPreviousDecl() 5576 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5577 : nullptr; 5578 5579 // Check the template parameter list of this declaration, possibly 5580 // merging in the template parameter list from the previous variable 5581 // template declaration. 5582 if (CheckTemplateParameterList( 5583 TemplateParams, 5584 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5585 : nullptr, 5586 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5587 DC->isDependentContext()) 5588 ? TPC_ClassTemplateMember 5589 : TPC_VarTemplate)) 5590 NewVD->setInvalidDecl(); 5591 5592 // If we are providing an explicit specialization of a static variable 5593 // template, make a note of that. 5594 if (PrevVarTemplate && 5595 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5596 PrevVarTemplate->setMemberSpecialization(); 5597 } 5598 } 5599 5600 ProcessPragmaWeak(S, NewVD); 5601 5602 // If this is the first declaration of an extern C variable, update 5603 // the map of such variables. 5604 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5605 isIncompleteDeclExternC(*this, NewVD)) 5606 RegisterLocallyScopedExternCDecl(NewVD, S); 5607 5608 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5609 Decl *ManglingContextDecl; 5610 if (MangleNumberingContext *MCtx = 5611 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5612 ManglingContextDecl)) { 5613 Context.setManglingNumber( 5614 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5615 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5616 } 5617 } 5618 5619 if (D.isRedeclaration() && !Previous.empty()) { 5620 checkDLLAttributeRedeclaration( 5621 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5622 IsExplicitSpecialization); 5623 } 5624 5625 if (NewTemplate) { 5626 if (NewVD->isInvalidDecl()) 5627 NewTemplate->setInvalidDecl(); 5628 ActOnDocumentableDecl(NewTemplate); 5629 return NewTemplate; 5630 } 5631 5632 return NewVD; 5633 } 5634 5635 /// \brief Diagnose variable or built-in function shadowing. Implements 5636 /// -Wshadow. 5637 /// 5638 /// This method is called whenever a VarDecl is added to a "useful" 5639 /// scope. 5640 /// 5641 /// \param S the scope in which the shadowing name is being declared 5642 /// \param R the lookup of the name 5643 /// 5644 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5645 // Return if warning is ignored. 5646 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 5647 DiagnosticsEngine::Ignored) 5648 return; 5649 5650 // Don't diagnose declarations at file scope. 5651 if (D->hasGlobalStorage()) 5652 return; 5653 5654 DeclContext *NewDC = D->getDeclContext(); 5655 5656 // Only diagnose if we're shadowing an unambiguous field or variable. 5657 if (R.getResultKind() != LookupResult::Found) 5658 return; 5659 5660 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5661 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5662 return; 5663 5664 // Fields are not shadowed by variables in C++ static methods. 5665 if (isa<FieldDecl>(ShadowedDecl)) 5666 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5667 if (MD->isStatic()) 5668 return; 5669 5670 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5671 if (shadowedVar->isExternC()) { 5672 // For shadowing external vars, make sure that we point to the global 5673 // declaration, not a locally scoped extern declaration. 5674 for (auto I : shadowedVar->redecls()) 5675 if (I->isFileVarDecl()) { 5676 ShadowedDecl = I; 5677 break; 5678 } 5679 } 5680 5681 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5682 5683 // Only warn about certain kinds of shadowing for class members. 5684 if (NewDC && NewDC->isRecord()) { 5685 // In particular, don't warn about shadowing non-class members. 5686 if (!OldDC->isRecord()) 5687 return; 5688 5689 // TODO: should we warn about static data members shadowing 5690 // static data members from base classes? 5691 5692 // TODO: don't diagnose for inaccessible shadowed members. 5693 // This is hard to do perfectly because we might friend the 5694 // shadowing context, but that's just a false negative. 5695 } 5696 5697 // Determine what kind of declaration we're shadowing. 5698 unsigned Kind; 5699 if (isa<RecordDecl>(OldDC)) { 5700 if (isa<FieldDecl>(ShadowedDecl)) 5701 Kind = 3; // field 5702 else 5703 Kind = 2; // static data member 5704 } else if (OldDC->isFileContext()) 5705 Kind = 1; // global 5706 else 5707 Kind = 0; // local 5708 5709 DeclarationName Name = R.getLookupName(); 5710 5711 // Emit warning and note. 5712 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5713 return; 5714 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5715 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5716 } 5717 5718 /// \brief Check -Wshadow without the advantage of a previous lookup. 5719 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5720 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 5721 DiagnosticsEngine::Ignored) 5722 return; 5723 5724 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5725 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5726 LookupName(R, S); 5727 CheckShadow(S, D, R); 5728 } 5729 5730 /// Check for conflict between this global or extern "C" declaration and 5731 /// previous global or extern "C" declarations. This is only used in C++. 5732 template<typename T> 5733 static bool checkGlobalOrExternCConflict( 5734 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5735 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5736 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5737 5738 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5739 // The common case: this global doesn't conflict with any extern "C" 5740 // declaration. 5741 return false; 5742 } 5743 5744 if (Prev) { 5745 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5746 // Both the old and new declarations have C language linkage. This is a 5747 // redeclaration. 5748 Previous.clear(); 5749 Previous.addDecl(Prev); 5750 return true; 5751 } 5752 5753 // This is a global, non-extern "C" declaration, and there is a previous 5754 // non-global extern "C" declaration. Diagnose if this is a variable 5755 // declaration. 5756 if (!isa<VarDecl>(ND)) 5757 return false; 5758 } else { 5759 // The declaration is extern "C". Check for any declaration in the 5760 // translation unit which might conflict. 5761 if (IsGlobal) { 5762 // We have already performed the lookup into the translation unit. 5763 IsGlobal = false; 5764 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5765 I != E; ++I) { 5766 if (isa<VarDecl>(*I)) { 5767 Prev = *I; 5768 break; 5769 } 5770 } 5771 } else { 5772 DeclContext::lookup_result R = 5773 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 5774 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 5775 I != E; ++I) { 5776 if (isa<VarDecl>(*I)) { 5777 Prev = *I; 5778 break; 5779 } 5780 // FIXME: If we have any other entity with this name in global scope, 5781 // the declaration is ill-formed, but that is a defect: it breaks the 5782 // 'stat' hack, for instance. Only variables can have mangled name 5783 // clashes with extern "C" declarations, so only they deserve a 5784 // diagnostic. 5785 } 5786 } 5787 5788 if (!Prev) 5789 return false; 5790 } 5791 5792 // Use the first declaration's location to ensure we point at something which 5793 // is lexically inside an extern "C" linkage-spec. 5794 assert(Prev && "should have found a previous declaration to diagnose"); 5795 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 5796 Prev = FD->getFirstDecl(); 5797 else 5798 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 5799 5800 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 5801 << IsGlobal << ND; 5802 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 5803 << IsGlobal; 5804 return false; 5805 } 5806 5807 /// Apply special rules for handling extern "C" declarations. Returns \c true 5808 /// if we have found that this is a redeclaration of some prior entity. 5809 /// 5810 /// Per C++ [dcl.link]p6: 5811 /// Two declarations [for a function or variable] with C language linkage 5812 /// with the same name that appear in different scopes refer to the same 5813 /// [entity]. An entity with C language linkage shall not be declared with 5814 /// the same name as an entity in global scope. 5815 template<typename T> 5816 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 5817 LookupResult &Previous) { 5818 if (!S.getLangOpts().CPlusPlus) { 5819 // In C, when declaring a global variable, look for a corresponding 'extern' 5820 // variable declared in function scope. We don't need this in C++, because 5821 // we find local extern decls in the surrounding file-scope DeclContext. 5822 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5823 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 5824 Previous.clear(); 5825 Previous.addDecl(Prev); 5826 return true; 5827 } 5828 } 5829 return false; 5830 } 5831 5832 // A declaration in the translation unit can conflict with an extern "C" 5833 // declaration. 5834 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 5835 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 5836 5837 // An extern "C" declaration can conflict with a declaration in the 5838 // translation unit or can be a redeclaration of an extern "C" declaration 5839 // in another scope. 5840 if (isIncompleteDeclExternC(S,ND)) 5841 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 5842 5843 // Neither global nor extern "C": nothing to do. 5844 return false; 5845 } 5846 5847 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 5848 // If the decl is already known invalid, don't check it. 5849 if (NewVD->isInvalidDecl()) 5850 return; 5851 5852 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 5853 QualType T = TInfo->getType(); 5854 5855 // Defer checking an 'auto' type until its initializer is attached. 5856 if (T->isUndeducedType()) 5857 return; 5858 5859 if (NewVD->hasAttrs()) 5860 CheckAlignasUnderalignment(NewVD); 5861 5862 if (T->isObjCObjectType()) { 5863 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 5864 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 5865 T = Context.getObjCObjectPointerType(T); 5866 NewVD->setType(T); 5867 } 5868 5869 // Emit an error if an address space was applied to decl with local storage. 5870 // This includes arrays of objects with address space qualifiers, but not 5871 // automatic variables that point to other address spaces. 5872 // ISO/IEC TR 18037 S5.1.2 5873 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 5874 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 5875 NewVD->setInvalidDecl(); 5876 return; 5877 } 5878 5879 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 5880 // __constant address space. 5881 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 5882 && T.getAddressSpace() != LangAS::opencl_constant 5883 && !T->isSamplerT()){ 5884 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 5885 NewVD->setInvalidDecl(); 5886 return; 5887 } 5888 5889 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 5890 // scope. 5891 if ((getLangOpts().OpenCLVersion >= 120) 5892 && NewVD->isStaticLocal()) { 5893 Diag(NewVD->getLocation(), diag::err_static_function_scope); 5894 NewVD->setInvalidDecl(); 5895 return; 5896 } 5897 5898 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 5899 && !NewVD->hasAttr<BlocksAttr>()) { 5900 if (getLangOpts().getGC() != LangOptions::NonGC) 5901 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 5902 else { 5903 assert(!getLangOpts().ObjCAutoRefCount); 5904 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 5905 } 5906 } 5907 5908 bool isVM = T->isVariablyModifiedType(); 5909 if (isVM || NewVD->hasAttr<CleanupAttr>() || 5910 NewVD->hasAttr<BlocksAttr>()) 5911 getCurFunction()->setHasBranchProtectedScope(); 5912 5913 if ((isVM && NewVD->hasLinkage()) || 5914 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 5915 bool SizeIsNegative; 5916 llvm::APSInt Oversized; 5917 TypeSourceInfo *FixedTInfo = 5918 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5919 SizeIsNegative, Oversized); 5920 if (!FixedTInfo && T->isVariableArrayType()) { 5921 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 5922 // FIXME: This won't give the correct result for 5923 // int a[10][n]; 5924 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 5925 5926 if (NewVD->isFileVarDecl()) 5927 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 5928 << SizeRange; 5929 else if (NewVD->isStaticLocal()) 5930 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 5931 << SizeRange; 5932 else 5933 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 5934 << SizeRange; 5935 NewVD->setInvalidDecl(); 5936 return; 5937 } 5938 5939 if (!FixedTInfo) { 5940 if (NewVD->isFileVarDecl()) 5941 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 5942 else 5943 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 5944 NewVD->setInvalidDecl(); 5945 return; 5946 } 5947 5948 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 5949 NewVD->setType(FixedTInfo->getType()); 5950 NewVD->setTypeSourceInfo(FixedTInfo); 5951 } 5952 5953 if (T->isVoidType()) { 5954 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 5955 // of objects and functions. 5956 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 5957 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 5958 << T; 5959 NewVD->setInvalidDecl(); 5960 return; 5961 } 5962 } 5963 5964 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 5965 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 5966 NewVD->setInvalidDecl(); 5967 return; 5968 } 5969 5970 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 5971 Diag(NewVD->getLocation(), diag::err_block_on_vm); 5972 NewVD->setInvalidDecl(); 5973 return; 5974 } 5975 5976 if (NewVD->isConstexpr() && !T->isDependentType() && 5977 RequireLiteralType(NewVD->getLocation(), T, 5978 diag::err_constexpr_var_non_literal)) { 5979 NewVD->setInvalidDecl(); 5980 return; 5981 } 5982 } 5983 5984 /// \brief Perform semantic checking on a newly-created variable 5985 /// declaration. 5986 /// 5987 /// This routine performs all of the type-checking required for a 5988 /// variable declaration once it has been built. It is used both to 5989 /// check variables after they have been parsed and their declarators 5990 /// have been translated into a declaration, and to check variables 5991 /// that have been instantiated from a template. 5992 /// 5993 /// Sets NewVD->isInvalidDecl() if an error was encountered. 5994 /// 5995 /// Returns true if the variable declaration is a redeclaration. 5996 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 5997 CheckVariableDeclarationType(NewVD); 5998 5999 // If the decl is already known invalid, don't check it. 6000 if (NewVD->isInvalidDecl()) 6001 return false; 6002 6003 // If we did not find anything by this name, look for a non-visible 6004 // extern "C" declaration with the same name. 6005 if (Previous.empty() && 6006 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6007 Previous.setShadowed(); 6008 6009 // Filter out any non-conflicting previous declarations. 6010 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6011 6012 if (!Previous.empty()) { 6013 MergeVarDecl(NewVD, Previous); 6014 return true; 6015 } 6016 return false; 6017 } 6018 6019 /// \brief Data used with FindOverriddenMethod 6020 struct FindOverriddenMethodData { 6021 Sema *S; 6022 CXXMethodDecl *Method; 6023 }; 6024 6025 /// \brief Member lookup function that determines whether a given C++ 6026 /// method overrides a method in a base class, to be used with 6027 /// CXXRecordDecl::lookupInBases(). 6028 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6029 CXXBasePath &Path, 6030 void *UserData) { 6031 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6032 6033 FindOverriddenMethodData *Data 6034 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6035 6036 DeclarationName Name = Data->Method->getDeclName(); 6037 6038 // FIXME: Do we care about other names here too? 6039 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6040 // We really want to find the base class destructor here. 6041 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6042 CanQualType CT = Data->S->Context.getCanonicalType(T); 6043 6044 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6045 } 6046 6047 for (Path.Decls = BaseRecord->lookup(Name); 6048 !Path.Decls.empty(); 6049 Path.Decls = Path.Decls.slice(1)) { 6050 NamedDecl *D = Path.Decls.front(); 6051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6052 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6053 return true; 6054 } 6055 } 6056 6057 return false; 6058 } 6059 6060 namespace { 6061 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6062 } 6063 /// \brief Report an error regarding overriding, along with any relevant 6064 /// overriden methods. 6065 /// 6066 /// \param DiagID the primary error to report. 6067 /// \param MD the overriding method. 6068 /// \param OEK which overrides to include as notes. 6069 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6070 OverrideErrorKind OEK = OEK_All) { 6071 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6072 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6073 E = MD->end_overridden_methods(); 6074 I != E; ++I) { 6075 // This check (& the OEK parameter) could be replaced by a predicate, but 6076 // without lambdas that would be overkill. This is still nicer than writing 6077 // out the diag loop 3 times. 6078 if ((OEK == OEK_All) || 6079 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6080 (OEK == OEK_Deleted && (*I)->isDeleted())) 6081 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6082 } 6083 } 6084 6085 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6086 /// and if so, check that it's a valid override and remember it. 6087 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6088 // Look for virtual methods in base classes that this method might override. 6089 CXXBasePaths Paths; 6090 FindOverriddenMethodData Data; 6091 Data.Method = MD; 6092 Data.S = this; 6093 bool hasDeletedOverridenMethods = false; 6094 bool hasNonDeletedOverridenMethods = false; 6095 bool AddedAny = false; 6096 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6097 for (auto *I : Paths.found_decls()) { 6098 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6099 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6100 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6101 !CheckOverridingFunctionAttributes(MD, OldMD) && 6102 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6103 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6104 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6105 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6106 AddedAny = true; 6107 } 6108 } 6109 } 6110 } 6111 6112 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6113 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6114 } 6115 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6116 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6117 } 6118 6119 return AddedAny; 6120 } 6121 6122 namespace { 6123 // Struct for holding all of the extra arguments needed by 6124 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6125 struct ActOnFDArgs { 6126 Scope *S; 6127 Declarator &D; 6128 MultiTemplateParamsArg TemplateParamLists; 6129 bool AddToScope; 6130 }; 6131 } 6132 6133 namespace { 6134 6135 // Callback to only accept typo corrections that have a non-zero edit distance. 6136 // Also only accept corrections that have the same parent decl. 6137 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6138 public: 6139 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6140 CXXRecordDecl *Parent) 6141 : Context(Context), OriginalFD(TypoFD), 6142 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6143 6144 bool ValidateCandidate(const TypoCorrection &candidate) override { 6145 if (candidate.getEditDistance() == 0) 6146 return false; 6147 6148 SmallVector<unsigned, 1> MismatchedParams; 6149 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6150 CDeclEnd = candidate.end(); 6151 CDecl != CDeclEnd; ++CDecl) { 6152 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6153 6154 if (FD && !FD->hasBody() && 6155 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6156 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6157 CXXRecordDecl *Parent = MD->getParent(); 6158 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6159 return true; 6160 } else if (!ExpectedParent) { 6161 return true; 6162 } 6163 } 6164 } 6165 6166 return false; 6167 } 6168 6169 private: 6170 ASTContext &Context; 6171 FunctionDecl *OriginalFD; 6172 CXXRecordDecl *ExpectedParent; 6173 }; 6174 6175 } 6176 6177 /// \brief Generate diagnostics for an invalid function redeclaration. 6178 /// 6179 /// This routine handles generating the diagnostic messages for an invalid 6180 /// function redeclaration, including finding possible similar declarations 6181 /// or performing typo correction if there are no previous declarations with 6182 /// the same name. 6183 /// 6184 /// Returns a NamedDecl iff typo correction was performed and substituting in 6185 /// the new declaration name does not cause new errors. 6186 static NamedDecl *DiagnoseInvalidRedeclaration( 6187 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6188 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6189 DeclarationName Name = NewFD->getDeclName(); 6190 DeclContext *NewDC = NewFD->getDeclContext(); 6191 SmallVector<unsigned, 1> MismatchedParams; 6192 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6193 TypoCorrection Correction; 6194 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6195 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6196 : diag::err_member_decl_does_not_match; 6197 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6198 IsLocalFriend ? Sema::LookupLocalFriendName 6199 : Sema::LookupOrdinaryName, 6200 Sema::ForRedeclaration); 6201 6202 NewFD->setInvalidDecl(); 6203 if (IsLocalFriend) 6204 SemaRef.LookupName(Prev, S); 6205 else 6206 SemaRef.LookupQualifiedName(Prev, NewDC); 6207 assert(!Prev.isAmbiguous() && 6208 "Cannot have an ambiguity in previous-declaration lookup"); 6209 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6210 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6211 MD ? MD->getParent() : nullptr); 6212 if (!Prev.empty()) { 6213 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6214 Func != FuncEnd; ++Func) { 6215 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6216 if (FD && 6217 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6218 // Add 1 to the index so that 0 can mean the mismatch didn't 6219 // involve a parameter 6220 unsigned ParamNum = 6221 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6222 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6223 } 6224 } 6225 // If the qualified name lookup yielded nothing, try typo correction 6226 } else if ((Correction = SemaRef.CorrectTypo( 6227 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6228 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6229 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6230 // Set up everything for the call to ActOnFunctionDeclarator 6231 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6232 ExtraArgs.D.getIdentifierLoc()); 6233 Previous.clear(); 6234 Previous.setLookupName(Correction.getCorrection()); 6235 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6236 CDeclEnd = Correction.end(); 6237 CDecl != CDeclEnd; ++CDecl) { 6238 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6239 if (FD && !FD->hasBody() && 6240 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6241 Previous.addDecl(FD); 6242 } 6243 } 6244 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6245 6246 NamedDecl *Result; 6247 // Retry building the function declaration with the new previous 6248 // declarations, and with errors suppressed. 6249 { 6250 // Trap errors. 6251 Sema::SFINAETrap Trap(SemaRef); 6252 6253 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6254 // pieces need to verify the typo-corrected C++ declaration and hopefully 6255 // eliminate the need for the parameter pack ExtraArgs. 6256 Result = SemaRef.ActOnFunctionDeclarator( 6257 ExtraArgs.S, ExtraArgs.D, 6258 Correction.getCorrectionDecl()->getDeclContext(), 6259 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6260 ExtraArgs.AddToScope); 6261 6262 if (Trap.hasErrorOccurred()) 6263 Result = nullptr; 6264 } 6265 6266 if (Result) { 6267 // Determine which correction we picked. 6268 Decl *Canonical = Result->getCanonicalDecl(); 6269 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6270 I != E; ++I) 6271 if ((*I)->getCanonicalDecl() == Canonical) 6272 Correction.setCorrectionDecl(*I); 6273 6274 SemaRef.diagnoseTypo( 6275 Correction, 6276 SemaRef.PDiag(IsLocalFriend 6277 ? diag::err_no_matching_local_friend_suggest 6278 : diag::err_member_decl_does_not_match_suggest) 6279 << Name << NewDC << IsDefinition); 6280 return Result; 6281 } 6282 6283 // Pretend the typo correction never occurred 6284 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6285 ExtraArgs.D.getIdentifierLoc()); 6286 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6287 Previous.clear(); 6288 Previous.setLookupName(Name); 6289 } 6290 6291 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6292 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6293 6294 bool NewFDisConst = false; 6295 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6296 NewFDisConst = NewMD->isConst(); 6297 6298 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6299 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6300 NearMatch != NearMatchEnd; ++NearMatch) { 6301 FunctionDecl *FD = NearMatch->first; 6302 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6303 bool FDisConst = MD && MD->isConst(); 6304 bool IsMember = MD || !IsLocalFriend; 6305 6306 // FIXME: These notes are poorly worded for the local friend case. 6307 if (unsigned Idx = NearMatch->second) { 6308 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6309 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6310 if (Loc.isInvalid()) Loc = FD->getLocation(); 6311 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6312 : diag::note_local_decl_close_param_match) 6313 << Idx << FDParam->getType() 6314 << NewFD->getParamDecl(Idx - 1)->getType(); 6315 } else if (FDisConst != NewFDisConst) { 6316 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6317 << NewFDisConst << FD->getSourceRange().getEnd(); 6318 } else 6319 SemaRef.Diag(FD->getLocation(), 6320 IsMember ? diag::note_member_def_close_match 6321 : diag::note_local_decl_close_match); 6322 } 6323 return nullptr; 6324 } 6325 6326 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6327 Declarator &D) { 6328 switch (D.getDeclSpec().getStorageClassSpec()) { 6329 default: llvm_unreachable("Unknown storage class!"); 6330 case DeclSpec::SCS_auto: 6331 case DeclSpec::SCS_register: 6332 case DeclSpec::SCS_mutable: 6333 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6334 diag::err_typecheck_sclass_func); 6335 D.setInvalidType(); 6336 break; 6337 case DeclSpec::SCS_unspecified: break; 6338 case DeclSpec::SCS_extern: 6339 if (D.getDeclSpec().isExternInLinkageSpec()) 6340 return SC_None; 6341 return SC_Extern; 6342 case DeclSpec::SCS_static: { 6343 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6344 // C99 6.7.1p5: 6345 // The declaration of an identifier for a function that has 6346 // block scope shall have no explicit storage-class specifier 6347 // other than extern 6348 // See also (C++ [dcl.stc]p4). 6349 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6350 diag::err_static_block_func); 6351 break; 6352 } else 6353 return SC_Static; 6354 } 6355 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6356 } 6357 6358 // No explicit storage class has already been returned 6359 return SC_None; 6360 } 6361 6362 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6363 DeclContext *DC, QualType &R, 6364 TypeSourceInfo *TInfo, 6365 FunctionDecl::StorageClass SC, 6366 bool &IsVirtualOkay) { 6367 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6368 DeclarationName Name = NameInfo.getName(); 6369 6370 FunctionDecl *NewFD = nullptr; 6371 bool isInline = D.getDeclSpec().isInlineSpecified(); 6372 6373 if (!SemaRef.getLangOpts().CPlusPlus) { 6374 // Determine whether the function was written with a 6375 // prototype. This true when: 6376 // - there is a prototype in the declarator, or 6377 // - the type R of the function is some kind of typedef or other reference 6378 // to a type name (which eventually refers to a function type). 6379 bool HasPrototype = 6380 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6381 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6382 6383 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6384 D.getLocStart(), NameInfo, R, 6385 TInfo, SC, isInline, 6386 HasPrototype, false); 6387 if (D.isInvalidType()) 6388 NewFD->setInvalidDecl(); 6389 6390 // Set the lexical context. 6391 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6392 6393 return NewFD; 6394 } 6395 6396 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6397 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6398 6399 // Check that the return type is not an abstract class type. 6400 // For record types, this is done by the AbstractClassUsageDiagnoser once 6401 // the class has been completely parsed. 6402 if (!DC->isRecord() && 6403 SemaRef.RequireNonAbstractType( 6404 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6405 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6406 D.setInvalidType(); 6407 6408 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6409 // This is a C++ constructor declaration. 6410 assert(DC->isRecord() && 6411 "Constructors can only be declared in a member context"); 6412 6413 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6414 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6415 D.getLocStart(), NameInfo, 6416 R, TInfo, isExplicit, isInline, 6417 /*isImplicitlyDeclared=*/false, 6418 isConstexpr); 6419 6420 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6421 // This is a C++ destructor declaration. 6422 if (DC->isRecord()) { 6423 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6424 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6425 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6426 SemaRef.Context, Record, 6427 D.getLocStart(), 6428 NameInfo, R, TInfo, isInline, 6429 /*isImplicitlyDeclared=*/false); 6430 6431 // If the class is complete, then we now create the implicit exception 6432 // specification. If the class is incomplete or dependent, we can't do 6433 // it yet. 6434 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6435 Record->getDefinition() && !Record->isBeingDefined() && 6436 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6437 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6438 } 6439 6440 IsVirtualOkay = true; 6441 return NewDD; 6442 6443 } else { 6444 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6445 D.setInvalidType(); 6446 6447 // Create a FunctionDecl to satisfy the function definition parsing 6448 // code path. 6449 return FunctionDecl::Create(SemaRef.Context, DC, 6450 D.getLocStart(), 6451 D.getIdentifierLoc(), Name, R, TInfo, 6452 SC, isInline, 6453 /*hasPrototype=*/true, isConstexpr); 6454 } 6455 6456 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6457 if (!DC->isRecord()) { 6458 SemaRef.Diag(D.getIdentifierLoc(), 6459 diag::err_conv_function_not_member); 6460 return nullptr; 6461 } 6462 6463 SemaRef.CheckConversionDeclarator(D, R, SC); 6464 IsVirtualOkay = true; 6465 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6466 D.getLocStart(), NameInfo, 6467 R, TInfo, isInline, isExplicit, 6468 isConstexpr, SourceLocation()); 6469 6470 } else if (DC->isRecord()) { 6471 // If the name of the function is the same as the name of the record, 6472 // then this must be an invalid constructor that has a return type. 6473 // (The parser checks for a return type and makes the declarator a 6474 // constructor if it has no return type). 6475 if (Name.getAsIdentifierInfo() && 6476 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6477 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6478 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6479 << SourceRange(D.getIdentifierLoc()); 6480 return nullptr; 6481 } 6482 6483 // This is a C++ method declaration. 6484 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6485 cast<CXXRecordDecl>(DC), 6486 D.getLocStart(), NameInfo, R, 6487 TInfo, SC, isInline, 6488 isConstexpr, SourceLocation()); 6489 IsVirtualOkay = !Ret->isStatic(); 6490 return Ret; 6491 } else { 6492 // Determine whether the function was written with a 6493 // prototype. This true when: 6494 // - we're in C++ (where every function has a prototype), 6495 return FunctionDecl::Create(SemaRef.Context, DC, 6496 D.getLocStart(), 6497 NameInfo, R, TInfo, SC, isInline, 6498 true/*HasPrototype*/, isConstexpr); 6499 } 6500 } 6501 6502 enum OpenCLParamType { 6503 ValidKernelParam, 6504 PtrPtrKernelParam, 6505 PtrKernelParam, 6506 PrivatePtrKernelParam, 6507 InvalidKernelParam, 6508 RecordKernelParam 6509 }; 6510 6511 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6512 if (PT->isPointerType()) { 6513 QualType PointeeType = PT->getPointeeType(); 6514 if (PointeeType->isPointerType()) 6515 return PtrPtrKernelParam; 6516 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6517 : PtrKernelParam; 6518 } 6519 6520 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6521 // be used as builtin types. 6522 6523 if (PT->isImageType()) 6524 return PtrKernelParam; 6525 6526 if (PT->isBooleanType()) 6527 return InvalidKernelParam; 6528 6529 if (PT->isEventT()) 6530 return InvalidKernelParam; 6531 6532 if (PT->isHalfType()) 6533 return InvalidKernelParam; 6534 6535 if (PT->isRecordType()) 6536 return RecordKernelParam; 6537 6538 return ValidKernelParam; 6539 } 6540 6541 static void checkIsValidOpenCLKernelParameter( 6542 Sema &S, 6543 Declarator &D, 6544 ParmVarDecl *Param, 6545 llvm::SmallPtrSet<const Type *, 16> &ValidTypes) { 6546 QualType PT = Param->getType(); 6547 6548 // Cache the valid types we encounter to avoid rechecking structs that are 6549 // used again 6550 if (ValidTypes.count(PT.getTypePtr())) 6551 return; 6552 6553 switch (getOpenCLKernelParameterType(PT)) { 6554 case PtrPtrKernelParam: 6555 // OpenCL v1.2 s6.9.a: 6556 // A kernel function argument cannot be declared as a 6557 // pointer to a pointer type. 6558 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6559 D.setInvalidType(); 6560 return; 6561 6562 case PrivatePtrKernelParam: 6563 // OpenCL v1.2 s6.9.a: 6564 // A kernel function argument cannot be declared as a 6565 // pointer to the private address space. 6566 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6567 D.setInvalidType(); 6568 return; 6569 6570 // OpenCL v1.2 s6.9.k: 6571 // Arguments to kernel functions in a program cannot be declared with the 6572 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6573 // uintptr_t or a struct and/or union that contain fields declared to be 6574 // one of these built-in scalar types. 6575 6576 case InvalidKernelParam: 6577 // OpenCL v1.2 s6.8 n: 6578 // A kernel function argument cannot be declared 6579 // of event_t type. 6580 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6581 D.setInvalidType(); 6582 return; 6583 6584 case PtrKernelParam: 6585 case ValidKernelParam: 6586 ValidTypes.insert(PT.getTypePtr()); 6587 return; 6588 6589 case RecordKernelParam: 6590 break; 6591 } 6592 6593 // Track nested structs we will inspect 6594 SmallVector<const Decl *, 4> VisitStack; 6595 6596 // Track where we are in the nested structs. Items will migrate from 6597 // VisitStack to HistoryStack as we do the DFS for bad field. 6598 SmallVector<const FieldDecl *, 4> HistoryStack; 6599 HistoryStack.push_back(nullptr); 6600 6601 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6602 VisitStack.push_back(PD); 6603 6604 assert(VisitStack.back() && "First decl null?"); 6605 6606 do { 6607 const Decl *Next = VisitStack.pop_back_val(); 6608 if (!Next) { 6609 assert(!HistoryStack.empty()); 6610 // Found a marker, we have gone up a level 6611 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6612 ValidTypes.insert(Hist->getType().getTypePtr()); 6613 6614 continue; 6615 } 6616 6617 // Adds everything except the original parameter declaration (which is not a 6618 // field itself) to the history stack. 6619 const RecordDecl *RD; 6620 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6621 HistoryStack.push_back(Field); 6622 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6623 } else { 6624 RD = cast<RecordDecl>(Next); 6625 } 6626 6627 // Add a null marker so we know when we've gone back up a level 6628 VisitStack.push_back(nullptr); 6629 6630 for (const auto *FD : RD->fields()) { 6631 QualType QT = FD->getType(); 6632 6633 if (ValidTypes.count(QT.getTypePtr())) 6634 continue; 6635 6636 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6637 if (ParamType == ValidKernelParam) 6638 continue; 6639 6640 if (ParamType == RecordKernelParam) { 6641 VisitStack.push_back(FD); 6642 continue; 6643 } 6644 6645 // OpenCL v1.2 s6.9.p: 6646 // Arguments to kernel functions that are declared to be a struct or union 6647 // do not allow OpenCL objects to be passed as elements of the struct or 6648 // union. 6649 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6650 ParamType == PrivatePtrKernelParam) { 6651 S.Diag(Param->getLocation(), 6652 diag::err_record_with_pointers_kernel_param) 6653 << PT->isUnionType() 6654 << PT; 6655 } else { 6656 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6657 } 6658 6659 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6660 << PD->getDeclName(); 6661 6662 // We have an error, now let's go back up through history and show where 6663 // the offending field came from 6664 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6665 E = HistoryStack.end(); I != E; ++I) { 6666 const FieldDecl *OuterField = *I; 6667 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6668 << OuterField->getType(); 6669 } 6670 6671 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6672 << QT->isPointerType() 6673 << QT; 6674 D.setInvalidType(); 6675 return; 6676 } 6677 } while (!VisitStack.empty()); 6678 } 6679 6680 NamedDecl* 6681 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6682 TypeSourceInfo *TInfo, LookupResult &Previous, 6683 MultiTemplateParamsArg TemplateParamLists, 6684 bool &AddToScope) { 6685 QualType R = TInfo->getType(); 6686 6687 assert(R.getTypePtr()->isFunctionType()); 6688 6689 // TODO: consider using NameInfo for diagnostic. 6690 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6691 DeclarationName Name = NameInfo.getName(); 6692 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6693 6694 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6695 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6696 diag::err_invalid_thread) 6697 << DeclSpec::getSpecifierName(TSCS); 6698 6699 if (D.isFirstDeclarationOfMember()) 6700 adjustMemberFunctionCC(R, D.isStaticMember()); 6701 6702 bool isFriend = false; 6703 FunctionTemplateDecl *FunctionTemplate = nullptr; 6704 bool isExplicitSpecialization = false; 6705 bool isFunctionTemplateSpecialization = false; 6706 6707 bool isDependentClassScopeExplicitSpecialization = false; 6708 bool HasExplicitTemplateArgs = false; 6709 TemplateArgumentListInfo TemplateArgs; 6710 6711 bool isVirtualOkay = false; 6712 6713 DeclContext *OriginalDC = DC; 6714 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6715 6716 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6717 isVirtualOkay); 6718 if (!NewFD) return nullptr; 6719 6720 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6721 NewFD->setTopLevelDeclInObjCContainer(); 6722 6723 // Set the lexical context. If this is a function-scope declaration, or has a 6724 // C++ scope specifier, or is the object of a friend declaration, the lexical 6725 // context will be different from the semantic context. 6726 NewFD->setLexicalDeclContext(CurContext); 6727 6728 if (IsLocalExternDecl) 6729 NewFD->setLocalExternDecl(); 6730 6731 if (getLangOpts().CPlusPlus) { 6732 bool isInline = D.getDeclSpec().isInlineSpecified(); 6733 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6734 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6735 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6736 isFriend = D.getDeclSpec().isFriendSpecified(); 6737 if (isFriend && !isInline && D.isFunctionDefinition()) { 6738 // C++ [class.friend]p5 6739 // A function can be defined in a friend declaration of a 6740 // class . . . . Such a function is implicitly inline. 6741 NewFD->setImplicitlyInline(); 6742 } 6743 6744 // If this is a method defined in an __interface, and is not a constructor 6745 // or an overloaded operator, then set the pure flag (isVirtual will already 6746 // return true). 6747 if (const CXXRecordDecl *Parent = 6748 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6749 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6750 NewFD->setPure(true); 6751 } 6752 6753 SetNestedNameSpecifier(NewFD, D); 6754 isExplicitSpecialization = false; 6755 isFunctionTemplateSpecialization = false; 6756 if (D.isInvalidType()) 6757 NewFD->setInvalidDecl(); 6758 6759 // Match up the template parameter lists with the scope specifier, then 6760 // determine whether we have a template or a template specialization. 6761 bool Invalid = false; 6762 if (TemplateParameterList *TemplateParams = 6763 MatchTemplateParametersToScopeSpecifier( 6764 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6765 D.getCXXScopeSpec(), 6766 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6767 ? D.getName().TemplateId 6768 : nullptr, 6769 TemplateParamLists, isFriend, isExplicitSpecialization, 6770 Invalid)) { 6771 if (TemplateParams->size() > 0) { 6772 // This is a function template 6773 6774 // Check that we can declare a template here. 6775 if (CheckTemplateDeclScope(S, TemplateParams)) 6776 return nullptr; 6777 6778 // A destructor cannot be a template. 6779 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6780 Diag(NewFD->getLocation(), diag::err_destructor_template); 6781 return nullptr; 6782 } 6783 6784 // If we're adding a template to a dependent context, we may need to 6785 // rebuilding some of the types used within the template parameter list, 6786 // now that we know what the current instantiation is. 6787 if (DC->isDependentContext()) { 6788 ContextRAII SavedContext(*this, DC); 6789 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 6790 Invalid = true; 6791 } 6792 6793 6794 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 6795 NewFD->getLocation(), 6796 Name, TemplateParams, 6797 NewFD); 6798 FunctionTemplate->setLexicalDeclContext(CurContext); 6799 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 6800 6801 // For source fidelity, store the other template param lists. 6802 if (TemplateParamLists.size() > 1) { 6803 NewFD->setTemplateParameterListsInfo(Context, 6804 TemplateParamLists.size() - 1, 6805 TemplateParamLists.data()); 6806 } 6807 } else { 6808 // This is a function template specialization. 6809 isFunctionTemplateSpecialization = true; 6810 // For source fidelity, store all the template param lists. 6811 if (TemplateParamLists.size() > 0) 6812 NewFD->setTemplateParameterListsInfo(Context, 6813 TemplateParamLists.size(), 6814 TemplateParamLists.data()); 6815 6816 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 6817 if (isFriend) { 6818 // We want to remove the "template<>", found here. 6819 SourceRange RemoveRange = TemplateParams->getSourceRange(); 6820 6821 // If we remove the template<> and the name is not a 6822 // template-id, we're actually silently creating a problem: 6823 // the friend declaration will refer to an untemplated decl, 6824 // and clearly the user wants a template specialization. So 6825 // we need to insert '<>' after the name. 6826 SourceLocation InsertLoc; 6827 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6828 InsertLoc = D.getName().getSourceRange().getEnd(); 6829 InsertLoc = getLocForEndOfToken(InsertLoc); 6830 } 6831 6832 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 6833 << Name << RemoveRange 6834 << FixItHint::CreateRemoval(RemoveRange) 6835 << FixItHint::CreateInsertion(InsertLoc, "<>"); 6836 } 6837 } 6838 } 6839 else { 6840 // All template param lists were matched against the scope specifier: 6841 // this is NOT (an explicit specialization of) a template. 6842 if (TemplateParamLists.size() > 0) 6843 // For source fidelity, store all the template param lists. 6844 NewFD->setTemplateParameterListsInfo(Context, 6845 TemplateParamLists.size(), 6846 TemplateParamLists.data()); 6847 } 6848 6849 if (Invalid) { 6850 NewFD->setInvalidDecl(); 6851 if (FunctionTemplate) 6852 FunctionTemplate->setInvalidDecl(); 6853 } 6854 6855 // C++ [dcl.fct.spec]p5: 6856 // The virtual specifier shall only be used in declarations of 6857 // nonstatic class member functions that appear within a 6858 // member-specification of a class declaration; see 10.3. 6859 // 6860 if (isVirtual && !NewFD->isInvalidDecl()) { 6861 if (!isVirtualOkay) { 6862 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6863 diag::err_virtual_non_function); 6864 } else if (!CurContext->isRecord()) { 6865 // 'virtual' was specified outside of the class. 6866 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6867 diag::err_virtual_out_of_class) 6868 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6869 } else if (NewFD->getDescribedFunctionTemplate()) { 6870 // C++ [temp.mem]p3: 6871 // A member function template shall not be virtual. 6872 Diag(D.getDeclSpec().getVirtualSpecLoc(), 6873 diag::err_virtual_member_function_template) 6874 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 6875 } else { 6876 // Okay: Add virtual to the method. 6877 NewFD->setVirtualAsWritten(true); 6878 } 6879 6880 if (getLangOpts().CPlusPlus1y && 6881 NewFD->getReturnType()->isUndeducedType()) 6882 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 6883 } 6884 6885 if (getLangOpts().CPlusPlus1y && 6886 (NewFD->isDependentContext() || 6887 (isFriend && CurContext->isDependentContext())) && 6888 NewFD->getReturnType()->isUndeducedType()) { 6889 // If the function template is referenced directly (for instance, as a 6890 // member of the current instantiation), pretend it has a dependent type. 6891 // This is not really justified by the standard, but is the only sane 6892 // thing to do. 6893 // FIXME: For a friend function, we have not marked the function as being 6894 // a friend yet, so 'isDependentContext' on the FD doesn't work. 6895 const FunctionProtoType *FPT = 6896 NewFD->getType()->castAs<FunctionProtoType>(); 6897 QualType Result = 6898 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 6899 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 6900 FPT->getExtProtoInfo())); 6901 } 6902 6903 // C++ [dcl.fct.spec]p3: 6904 // The inline specifier shall not appear on a block scope function 6905 // declaration. 6906 if (isInline && !NewFD->isInvalidDecl()) { 6907 if (CurContext->isFunctionOrMethod()) { 6908 // 'inline' is not allowed on block scope function declaration. 6909 Diag(D.getDeclSpec().getInlineSpecLoc(), 6910 diag::err_inline_declaration_block_scope) << Name 6911 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6912 } 6913 } 6914 6915 // C++ [dcl.fct.spec]p6: 6916 // The explicit specifier shall be used only in the declaration of a 6917 // constructor or conversion function within its class definition; 6918 // see 12.3.1 and 12.3.2. 6919 if (isExplicit && !NewFD->isInvalidDecl()) { 6920 if (!CurContext->isRecord()) { 6921 // 'explicit' was specified outside of the class. 6922 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6923 diag::err_explicit_out_of_class) 6924 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6925 } else if (!isa<CXXConstructorDecl>(NewFD) && 6926 !isa<CXXConversionDecl>(NewFD)) { 6927 // 'explicit' was specified on a function that wasn't a constructor 6928 // or conversion function. 6929 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6930 diag::err_explicit_non_ctor_or_conv_function) 6931 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 6932 } 6933 } 6934 6935 if (isConstexpr) { 6936 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 6937 // are implicitly inline. 6938 NewFD->setImplicitlyInline(); 6939 6940 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 6941 // be either constructors or to return a literal type. Therefore, 6942 // destructors cannot be declared constexpr. 6943 if (isa<CXXDestructorDecl>(NewFD)) 6944 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 6945 } 6946 6947 // If __module_private__ was specified, mark the function accordingly. 6948 if (D.getDeclSpec().isModulePrivateSpecified()) { 6949 if (isFunctionTemplateSpecialization) { 6950 SourceLocation ModulePrivateLoc 6951 = D.getDeclSpec().getModulePrivateSpecLoc(); 6952 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 6953 << 0 6954 << FixItHint::CreateRemoval(ModulePrivateLoc); 6955 } else { 6956 NewFD->setModulePrivate(); 6957 if (FunctionTemplate) 6958 FunctionTemplate->setModulePrivate(); 6959 } 6960 } 6961 6962 if (isFriend) { 6963 if (FunctionTemplate) { 6964 FunctionTemplate->setObjectOfFriendDecl(); 6965 FunctionTemplate->setAccess(AS_public); 6966 } 6967 NewFD->setObjectOfFriendDecl(); 6968 NewFD->setAccess(AS_public); 6969 } 6970 6971 // If a function is defined as defaulted or deleted, mark it as such now. 6972 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 6973 // definition kind to FDK_Definition. 6974 switch (D.getFunctionDefinitionKind()) { 6975 case FDK_Declaration: 6976 case FDK_Definition: 6977 break; 6978 6979 case FDK_Defaulted: 6980 NewFD->setDefaulted(); 6981 break; 6982 6983 case FDK_Deleted: 6984 NewFD->setDeletedAsWritten(); 6985 break; 6986 } 6987 6988 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 6989 D.isFunctionDefinition()) { 6990 // C++ [class.mfct]p2: 6991 // A member function may be defined (8.4) in its class definition, in 6992 // which case it is an inline member function (7.1.2) 6993 NewFD->setImplicitlyInline(); 6994 } 6995 6996 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 6997 !CurContext->isRecord()) { 6998 // C++ [class.static]p1: 6999 // A data or function member of a class may be declared static 7000 // in a class definition, in which case it is a static member of 7001 // the class. 7002 7003 // Complain about the 'static' specifier if it's on an out-of-line 7004 // member function definition. 7005 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7006 diag::err_static_out_of_line) 7007 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7008 } 7009 7010 // C++11 [except.spec]p15: 7011 // A deallocation function with no exception-specification is treated 7012 // as if it were specified with noexcept(true). 7013 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7014 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7015 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7016 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) { 7017 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7018 EPI.ExceptionSpecType = EST_BasicNoexcept; 7019 NewFD->setType(Context.getFunctionType(FPT->getReturnType(), 7020 FPT->getParamTypes(), EPI)); 7021 } 7022 } 7023 7024 // Filter out previous declarations that don't match the scope. 7025 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7026 D.getCXXScopeSpec().isNotEmpty() || 7027 isExplicitSpecialization || 7028 isFunctionTemplateSpecialization); 7029 7030 // Handle GNU asm-label extension (encoded as an attribute). 7031 if (Expr *E = (Expr*) D.getAsmLabel()) { 7032 // The parser guarantees this is a string. 7033 StringLiteral *SE = cast<StringLiteral>(E); 7034 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7035 SE->getString(), 0)); 7036 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7037 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7038 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7039 if (I != ExtnameUndeclaredIdentifiers.end()) { 7040 NewFD->addAttr(I->second); 7041 ExtnameUndeclaredIdentifiers.erase(I); 7042 } 7043 } 7044 7045 // Copy the parameter declarations from the declarator D to the function 7046 // declaration NewFD, if they are available. First scavenge them into Params. 7047 SmallVector<ParmVarDecl*, 16> Params; 7048 if (D.isFunctionDeclarator()) { 7049 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7050 7051 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7052 // function that takes no arguments, not a function that takes a 7053 // single void argument. 7054 // We let through "const void" here because Sema::GetTypeForDeclarator 7055 // already checks for that case. 7056 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7057 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7058 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7059 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7060 Param->setDeclContext(NewFD); 7061 Params.push_back(Param); 7062 7063 if (Param->isInvalidDecl()) 7064 NewFD->setInvalidDecl(); 7065 } 7066 } 7067 7068 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7069 // When we're declaring a function with a typedef, typeof, etc as in the 7070 // following example, we'll need to synthesize (unnamed) 7071 // parameters for use in the declaration. 7072 // 7073 // @code 7074 // typedef void fn(int); 7075 // fn f; 7076 // @endcode 7077 7078 // Synthesize a parameter for each argument type. 7079 for (const auto &AI : FT->param_types()) { 7080 ParmVarDecl *Param = 7081 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7082 Param->setScopeInfo(0, Params.size()); 7083 Params.push_back(Param); 7084 } 7085 } else { 7086 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7087 "Should not need args for typedef of non-prototype fn"); 7088 } 7089 7090 // Finally, we know we have the right number of parameters, install them. 7091 NewFD->setParams(Params); 7092 7093 // Find all anonymous symbols defined during the declaration of this function 7094 // and add to NewFD. This lets us track decls such 'enum Y' in: 7095 // 7096 // void f(enum Y {AA} x) {} 7097 // 7098 // which would otherwise incorrectly end up in the translation unit scope. 7099 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7100 DeclsInPrototypeScope.clear(); 7101 7102 if (D.getDeclSpec().isNoreturnSpecified()) 7103 NewFD->addAttr( 7104 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7105 Context, 0)); 7106 7107 // Functions returning a variably modified type violate C99 6.7.5.2p2 7108 // because all functions have linkage. 7109 if (!NewFD->isInvalidDecl() && 7110 NewFD->getReturnType()->isVariablyModifiedType()) { 7111 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7112 NewFD->setInvalidDecl(); 7113 } 7114 7115 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7116 !NewFD->hasAttr<SectionAttr>()) { 7117 NewFD->addAttr( 7118 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7119 CodeSegStack.CurrentValue->getString(), 7120 CodeSegStack.CurrentPragmaLocation)); 7121 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7122 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7123 NewFD->dropAttr<SectionAttr>(); 7124 } 7125 7126 // Handle attributes. 7127 ProcessDeclAttributes(S, NewFD, D); 7128 7129 QualType RetType = NewFD->getReturnType(); 7130 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7131 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7132 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7133 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7134 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7135 // Attach WarnUnusedResult to functions returning types with that attribute. 7136 // Don't apply the attribute to that type's own non-static member functions 7137 // (to avoid warning on things like assignment operators) 7138 if (!MD || MD->getParent() != Ret) 7139 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7140 } 7141 7142 if (getLangOpts().OpenCL) { 7143 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7144 // type declaration will generate a compilation error. 7145 unsigned AddressSpace = RetType.getAddressSpace(); 7146 if (AddressSpace == LangAS::opencl_local || 7147 AddressSpace == LangAS::opencl_global || 7148 AddressSpace == LangAS::opencl_constant) { 7149 Diag(NewFD->getLocation(), 7150 diag::err_opencl_return_value_with_address_space); 7151 NewFD->setInvalidDecl(); 7152 } 7153 } 7154 7155 if (!getLangOpts().CPlusPlus) { 7156 // Perform semantic checking on the function declaration. 7157 bool isExplicitSpecialization=false; 7158 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7159 CheckMain(NewFD, D.getDeclSpec()); 7160 7161 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7162 CheckMSVCRTEntryPoint(NewFD); 7163 7164 if (!NewFD->isInvalidDecl()) 7165 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7166 isExplicitSpecialization)); 7167 else if (!Previous.empty()) 7168 // Make graceful recovery from an invalid redeclaration. 7169 D.setRedeclaration(true); 7170 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7171 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7172 "previous declaration set still overloaded"); 7173 } else { 7174 // C++11 [replacement.functions]p3: 7175 // The program's definitions shall not be specified as inline. 7176 // 7177 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7178 // 7179 // Suppress the diagnostic if the function is __attribute__((used)), since 7180 // that forces an external definition to be emitted. 7181 if (D.getDeclSpec().isInlineSpecified() && 7182 NewFD->isReplaceableGlobalAllocationFunction() && 7183 !NewFD->hasAttr<UsedAttr>()) 7184 Diag(D.getDeclSpec().getInlineSpecLoc(), 7185 diag::ext_operator_new_delete_declared_inline) 7186 << NewFD->getDeclName(); 7187 7188 // If the declarator is a template-id, translate the parser's template 7189 // argument list into our AST format. 7190 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7191 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7192 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7193 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7194 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7195 TemplateId->NumArgs); 7196 translateTemplateArguments(TemplateArgsPtr, 7197 TemplateArgs); 7198 7199 HasExplicitTemplateArgs = true; 7200 7201 if (NewFD->isInvalidDecl()) { 7202 HasExplicitTemplateArgs = false; 7203 } else if (FunctionTemplate) { 7204 // Function template with explicit template arguments. 7205 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7206 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7207 7208 HasExplicitTemplateArgs = false; 7209 } else { 7210 assert((isFunctionTemplateSpecialization || 7211 D.getDeclSpec().isFriendSpecified()) && 7212 "should have a 'template<>' for this decl"); 7213 // "friend void foo<>(int);" is an implicit specialization decl. 7214 isFunctionTemplateSpecialization = true; 7215 } 7216 } else if (isFriend && isFunctionTemplateSpecialization) { 7217 // This combination is only possible in a recovery case; the user 7218 // wrote something like: 7219 // template <> friend void foo(int); 7220 // which we're recovering from as if the user had written: 7221 // friend void foo<>(int); 7222 // Go ahead and fake up a template id. 7223 HasExplicitTemplateArgs = true; 7224 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7225 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7226 } 7227 7228 // If it's a friend (and only if it's a friend), it's possible 7229 // that either the specialized function type or the specialized 7230 // template is dependent, and therefore matching will fail. In 7231 // this case, don't check the specialization yet. 7232 bool InstantiationDependent = false; 7233 if (isFunctionTemplateSpecialization && isFriend && 7234 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7235 TemplateSpecializationType::anyDependentTemplateArguments( 7236 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7237 InstantiationDependent))) { 7238 assert(HasExplicitTemplateArgs && 7239 "friend function specialization without template args"); 7240 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7241 Previous)) 7242 NewFD->setInvalidDecl(); 7243 } else if (isFunctionTemplateSpecialization) { 7244 if (CurContext->isDependentContext() && CurContext->isRecord() 7245 && !isFriend) { 7246 isDependentClassScopeExplicitSpecialization = true; 7247 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7248 diag::ext_function_specialization_in_class : 7249 diag::err_function_specialization_in_class) 7250 << NewFD->getDeclName(); 7251 } else if (CheckFunctionTemplateSpecialization(NewFD, 7252 (HasExplicitTemplateArgs ? &TemplateArgs 7253 : nullptr), 7254 Previous)) 7255 NewFD->setInvalidDecl(); 7256 7257 // C++ [dcl.stc]p1: 7258 // A storage-class-specifier shall not be specified in an explicit 7259 // specialization (14.7.3) 7260 FunctionTemplateSpecializationInfo *Info = 7261 NewFD->getTemplateSpecializationInfo(); 7262 if (Info && SC != SC_None) { 7263 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7264 Diag(NewFD->getLocation(), 7265 diag::err_explicit_specialization_inconsistent_storage_class) 7266 << SC 7267 << FixItHint::CreateRemoval( 7268 D.getDeclSpec().getStorageClassSpecLoc()); 7269 7270 else 7271 Diag(NewFD->getLocation(), 7272 diag::ext_explicit_specialization_storage_class) 7273 << FixItHint::CreateRemoval( 7274 D.getDeclSpec().getStorageClassSpecLoc()); 7275 } 7276 7277 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7278 if (CheckMemberSpecialization(NewFD, Previous)) 7279 NewFD->setInvalidDecl(); 7280 } 7281 7282 // Perform semantic checking on the function declaration. 7283 if (!isDependentClassScopeExplicitSpecialization) { 7284 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7285 CheckMain(NewFD, D.getDeclSpec()); 7286 7287 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7288 CheckMSVCRTEntryPoint(NewFD); 7289 7290 if (!NewFD->isInvalidDecl()) 7291 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7292 isExplicitSpecialization)); 7293 } 7294 7295 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7296 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7297 "previous declaration set still overloaded"); 7298 7299 NamedDecl *PrincipalDecl = (FunctionTemplate 7300 ? cast<NamedDecl>(FunctionTemplate) 7301 : NewFD); 7302 7303 if (isFriend && D.isRedeclaration()) { 7304 AccessSpecifier Access = AS_public; 7305 if (!NewFD->isInvalidDecl()) 7306 Access = NewFD->getPreviousDecl()->getAccess(); 7307 7308 NewFD->setAccess(Access); 7309 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7310 } 7311 7312 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7313 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7314 PrincipalDecl->setNonMemberOperator(); 7315 7316 // If we have a function template, check the template parameter 7317 // list. This will check and merge default template arguments. 7318 if (FunctionTemplate) { 7319 FunctionTemplateDecl *PrevTemplate = 7320 FunctionTemplate->getPreviousDecl(); 7321 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7322 PrevTemplate ? PrevTemplate->getTemplateParameters() 7323 : nullptr, 7324 D.getDeclSpec().isFriendSpecified() 7325 ? (D.isFunctionDefinition() 7326 ? TPC_FriendFunctionTemplateDefinition 7327 : TPC_FriendFunctionTemplate) 7328 : (D.getCXXScopeSpec().isSet() && 7329 DC && DC->isRecord() && 7330 DC->isDependentContext()) 7331 ? TPC_ClassTemplateMember 7332 : TPC_FunctionTemplate); 7333 } 7334 7335 if (NewFD->isInvalidDecl()) { 7336 // Ignore all the rest of this. 7337 } else if (!D.isRedeclaration()) { 7338 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7339 AddToScope }; 7340 // Fake up an access specifier if it's supposed to be a class member. 7341 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7342 NewFD->setAccess(AS_public); 7343 7344 // Qualified decls generally require a previous declaration. 7345 if (D.getCXXScopeSpec().isSet()) { 7346 // ...with the major exception of templated-scope or 7347 // dependent-scope friend declarations. 7348 7349 // TODO: we currently also suppress this check in dependent 7350 // contexts because (1) the parameter depth will be off when 7351 // matching friend templates and (2) we might actually be 7352 // selecting a friend based on a dependent factor. But there 7353 // are situations where these conditions don't apply and we 7354 // can actually do this check immediately. 7355 if (isFriend && 7356 (TemplateParamLists.size() || 7357 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7358 CurContext->isDependentContext())) { 7359 // ignore these 7360 } else { 7361 // The user tried to provide an out-of-line definition for a 7362 // function that is a member of a class or namespace, but there 7363 // was no such member function declared (C++ [class.mfct]p2, 7364 // C++ [namespace.memdef]p2). For example: 7365 // 7366 // class X { 7367 // void f() const; 7368 // }; 7369 // 7370 // void X::f() { } // ill-formed 7371 // 7372 // Complain about this problem, and attempt to suggest close 7373 // matches (e.g., those that differ only in cv-qualifiers and 7374 // whether the parameter types are references). 7375 7376 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7377 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7378 AddToScope = ExtraArgs.AddToScope; 7379 return Result; 7380 } 7381 } 7382 7383 // Unqualified local friend declarations are required to resolve 7384 // to something. 7385 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7386 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7387 *this, Previous, NewFD, ExtraArgs, true, S)) { 7388 AddToScope = ExtraArgs.AddToScope; 7389 return Result; 7390 } 7391 } 7392 7393 } else if (!D.isFunctionDefinition() && 7394 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7395 !isFriend && !isFunctionTemplateSpecialization && 7396 !isExplicitSpecialization) { 7397 // An out-of-line member function declaration must also be a 7398 // definition (C++ [class.mfct]p2). 7399 // Note that this is not the case for explicit specializations of 7400 // function templates or member functions of class templates, per 7401 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7402 // extension for compatibility with old SWIG code which likes to 7403 // generate them. 7404 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7405 << D.getCXXScopeSpec().getRange(); 7406 } 7407 } 7408 7409 ProcessPragmaWeak(S, NewFD); 7410 checkAttributesAfterMerging(*this, *NewFD); 7411 7412 AddKnownFunctionAttributes(NewFD); 7413 7414 if (NewFD->hasAttr<OverloadableAttr>() && 7415 !NewFD->getType()->getAs<FunctionProtoType>()) { 7416 Diag(NewFD->getLocation(), 7417 diag::err_attribute_overloadable_no_prototype) 7418 << NewFD; 7419 7420 // Turn this into a variadic function with no parameters. 7421 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7422 FunctionProtoType::ExtProtoInfo EPI( 7423 Context.getDefaultCallingConvention(true, false)); 7424 EPI.Variadic = true; 7425 EPI.ExtInfo = FT->getExtInfo(); 7426 7427 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7428 NewFD->setType(R); 7429 } 7430 7431 // If there's a #pragma GCC visibility in scope, and this isn't a class 7432 // member, set the visibility of this function. 7433 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7434 AddPushedVisibilityAttribute(NewFD); 7435 7436 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7437 // marking the function. 7438 AddCFAuditedAttribute(NewFD); 7439 7440 // If this is a function definition, check if we have to apply optnone due to 7441 // a pragma. 7442 if(D.isFunctionDefinition()) 7443 AddRangeBasedOptnone(NewFD); 7444 7445 // If this is the first declaration of an extern C variable, update 7446 // the map of such variables. 7447 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7448 isIncompleteDeclExternC(*this, NewFD)) 7449 RegisterLocallyScopedExternCDecl(NewFD, S); 7450 7451 // Set this FunctionDecl's range up to the right paren. 7452 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7453 7454 if (D.isRedeclaration() && !Previous.empty()) { 7455 checkDLLAttributeRedeclaration( 7456 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7457 isExplicitSpecialization || isFunctionTemplateSpecialization); 7458 } 7459 7460 if (getLangOpts().CPlusPlus) { 7461 if (FunctionTemplate) { 7462 if (NewFD->isInvalidDecl()) 7463 FunctionTemplate->setInvalidDecl(); 7464 return FunctionTemplate; 7465 } 7466 } 7467 7468 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7469 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7470 if ((getLangOpts().OpenCLVersion >= 120) 7471 && (SC == SC_Static)) { 7472 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7473 D.setInvalidType(); 7474 } 7475 7476 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7477 if (!NewFD->getReturnType()->isVoidType()) { 7478 Diag(D.getIdentifierLoc(), 7479 diag::err_expected_kernel_void_return_type); 7480 D.setInvalidType(); 7481 } 7482 7483 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7484 for (auto Param : NewFD->params()) 7485 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7486 } 7487 7488 MarkUnusedFileScopedDecl(NewFD); 7489 7490 if (getLangOpts().CUDA) 7491 if (IdentifierInfo *II = NewFD->getIdentifier()) 7492 if (!NewFD->isInvalidDecl() && 7493 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7494 if (II->isStr("cudaConfigureCall")) { 7495 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7496 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7497 7498 Context.setcudaConfigureCallDecl(NewFD); 7499 } 7500 } 7501 7502 // Here we have an function template explicit specialization at class scope. 7503 // The actually specialization will be postponed to template instatiation 7504 // time via the ClassScopeFunctionSpecializationDecl node. 7505 if (isDependentClassScopeExplicitSpecialization) { 7506 ClassScopeFunctionSpecializationDecl *NewSpec = 7507 ClassScopeFunctionSpecializationDecl::Create( 7508 Context, CurContext, SourceLocation(), 7509 cast<CXXMethodDecl>(NewFD), 7510 HasExplicitTemplateArgs, TemplateArgs); 7511 CurContext->addDecl(NewSpec); 7512 AddToScope = false; 7513 } 7514 7515 return NewFD; 7516 } 7517 7518 /// \brief Perform semantic checking of a new function declaration. 7519 /// 7520 /// Performs semantic analysis of the new function declaration 7521 /// NewFD. This routine performs all semantic checking that does not 7522 /// require the actual declarator involved in the declaration, and is 7523 /// used both for the declaration of functions as they are parsed 7524 /// (called via ActOnDeclarator) and for the declaration of functions 7525 /// that have been instantiated via C++ template instantiation (called 7526 /// via InstantiateDecl). 7527 /// 7528 /// \param IsExplicitSpecialization whether this new function declaration is 7529 /// an explicit specialization of the previous declaration. 7530 /// 7531 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7532 /// 7533 /// \returns true if the function declaration is a redeclaration. 7534 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7535 LookupResult &Previous, 7536 bool IsExplicitSpecialization) { 7537 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7538 "Variably modified return types are not handled here"); 7539 7540 // Determine whether the type of this function should be merged with 7541 // a previous visible declaration. This never happens for functions in C++, 7542 // and always happens in C if the previous declaration was visible. 7543 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7544 !Previous.isShadowed(); 7545 7546 // Filter out any non-conflicting previous declarations. 7547 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7548 7549 bool Redeclaration = false; 7550 NamedDecl *OldDecl = nullptr; 7551 7552 // Merge or overload the declaration with an existing declaration of 7553 // the same name, if appropriate. 7554 if (!Previous.empty()) { 7555 // Determine whether NewFD is an overload of PrevDecl or 7556 // a declaration that requires merging. If it's an overload, 7557 // there's no more work to do here; we'll just add the new 7558 // function to the scope. 7559 if (!AllowOverloadingOfFunction(Previous, Context)) { 7560 NamedDecl *Candidate = Previous.getFoundDecl(); 7561 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7562 Redeclaration = true; 7563 OldDecl = Candidate; 7564 } 7565 } else { 7566 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7567 /*NewIsUsingDecl*/ false)) { 7568 case Ovl_Match: 7569 Redeclaration = true; 7570 break; 7571 7572 case Ovl_NonFunction: 7573 Redeclaration = true; 7574 break; 7575 7576 case Ovl_Overload: 7577 Redeclaration = false; 7578 break; 7579 } 7580 7581 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7582 // If a function name is overloadable in C, then every function 7583 // with that name must be marked "overloadable". 7584 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7585 << Redeclaration << NewFD; 7586 NamedDecl *OverloadedDecl = nullptr; 7587 if (Redeclaration) 7588 OverloadedDecl = OldDecl; 7589 else if (!Previous.empty()) 7590 OverloadedDecl = Previous.getRepresentativeDecl(); 7591 if (OverloadedDecl) 7592 Diag(OverloadedDecl->getLocation(), 7593 diag::note_attribute_overloadable_prev_overload); 7594 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7595 } 7596 } 7597 } 7598 7599 // Check for a previous extern "C" declaration with this name. 7600 if (!Redeclaration && 7601 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7602 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7603 if (!Previous.empty()) { 7604 // This is an extern "C" declaration with the same name as a previous 7605 // declaration, and thus redeclares that entity... 7606 Redeclaration = true; 7607 OldDecl = Previous.getFoundDecl(); 7608 MergeTypeWithPrevious = false; 7609 7610 // ... except in the presence of __attribute__((overloadable)). 7611 if (OldDecl->hasAttr<OverloadableAttr>()) { 7612 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7613 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7614 << Redeclaration << NewFD; 7615 Diag(Previous.getFoundDecl()->getLocation(), 7616 diag::note_attribute_overloadable_prev_overload); 7617 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7618 } 7619 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7620 Redeclaration = false; 7621 OldDecl = nullptr; 7622 } 7623 } 7624 } 7625 } 7626 7627 // C++11 [dcl.constexpr]p8: 7628 // A constexpr specifier for a non-static member function that is not 7629 // a constructor declares that member function to be const. 7630 // 7631 // This needs to be delayed until we know whether this is an out-of-line 7632 // definition of a static member function. 7633 // 7634 // This rule is not present in C++1y, so we produce a backwards 7635 // compatibility warning whenever it happens in C++11. 7636 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7637 if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() && 7638 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7639 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7640 CXXMethodDecl *OldMD = nullptr; 7641 if (OldDecl) 7642 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7643 if (!OldMD || !OldMD->isStatic()) { 7644 const FunctionProtoType *FPT = 7645 MD->getType()->castAs<FunctionProtoType>(); 7646 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7647 EPI.TypeQuals |= Qualifiers::Const; 7648 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7649 FPT->getParamTypes(), EPI)); 7650 7651 // Warn that we did this, if we're not performing template instantiation. 7652 // In that case, we'll have warned already when the template was defined. 7653 if (ActiveTemplateInstantiations.empty()) { 7654 SourceLocation AddConstLoc; 7655 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7656 .IgnoreParens().getAs<FunctionTypeLoc>()) 7657 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7658 7659 Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const) 7660 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7661 } 7662 } 7663 } 7664 7665 if (Redeclaration) { 7666 // NewFD and OldDecl represent declarations that need to be 7667 // merged. 7668 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7669 NewFD->setInvalidDecl(); 7670 return Redeclaration; 7671 } 7672 7673 Previous.clear(); 7674 Previous.addDecl(OldDecl); 7675 7676 if (FunctionTemplateDecl *OldTemplateDecl 7677 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7678 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7679 FunctionTemplateDecl *NewTemplateDecl 7680 = NewFD->getDescribedFunctionTemplate(); 7681 assert(NewTemplateDecl && "Template/non-template mismatch"); 7682 if (CXXMethodDecl *Method 7683 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7684 Method->setAccess(OldTemplateDecl->getAccess()); 7685 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7686 } 7687 7688 // If this is an explicit specialization of a member that is a function 7689 // template, mark it as a member specialization. 7690 if (IsExplicitSpecialization && 7691 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7692 NewTemplateDecl->setMemberSpecialization(); 7693 assert(OldTemplateDecl->isMemberSpecialization()); 7694 } 7695 7696 } else { 7697 // This needs to happen first so that 'inline' propagates. 7698 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7699 7700 if (isa<CXXMethodDecl>(NewFD)) { 7701 // A valid redeclaration of a C++ method must be out-of-line, 7702 // but (unfortunately) it's not necessarily a definition 7703 // because of templates, which means that the previous 7704 // declaration is not necessarily from the class definition. 7705 7706 // For just setting the access, that doesn't matter. 7707 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7708 NewFD->setAccess(oldMethod->getAccess()); 7709 7710 // Update the key-function state if necessary for this ABI. 7711 if (NewFD->isInlined() && 7712 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7713 // setNonKeyFunction needs to work with the original 7714 // declaration from the class definition, and isVirtual() is 7715 // just faster in that case, so map back to that now. 7716 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7717 if (oldMethod->isVirtual()) { 7718 Context.setNonKeyFunction(oldMethod); 7719 } 7720 } 7721 } 7722 } 7723 } 7724 7725 // Semantic checking for this function declaration (in isolation). 7726 if (getLangOpts().CPlusPlus) { 7727 // C++-specific checks. 7728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7729 CheckConstructor(Constructor); 7730 } else if (CXXDestructorDecl *Destructor = 7731 dyn_cast<CXXDestructorDecl>(NewFD)) { 7732 CXXRecordDecl *Record = Destructor->getParent(); 7733 QualType ClassType = Context.getTypeDeclType(Record); 7734 7735 // FIXME: Shouldn't we be able to perform this check even when the class 7736 // type is dependent? Both gcc and edg can handle that. 7737 if (!ClassType->isDependentType()) { 7738 DeclarationName Name 7739 = Context.DeclarationNames.getCXXDestructorName( 7740 Context.getCanonicalType(ClassType)); 7741 if (NewFD->getDeclName() != Name) { 7742 Diag(NewFD->getLocation(), diag::err_destructor_name); 7743 NewFD->setInvalidDecl(); 7744 return Redeclaration; 7745 } 7746 } 7747 } else if (CXXConversionDecl *Conversion 7748 = dyn_cast<CXXConversionDecl>(NewFD)) { 7749 ActOnConversionDeclarator(Conversion); 7750 } 7751 7752 // Find any virtual functions that this function overrides. 7753 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7754 if (!Method->isFunctionTemplateSpecialization() && 7755 !Method->getDescribedFunctionTemplate() && 7756 Method->isCanonicalDecl()) { 7757 if (AddOverriddenMethods(Method->getParent(), Method)) { 7758 // If the function was marked as "static", we have a problem. 7759 if (NewFD->getStorageClass() == SC_Static) { 7760 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 7761 } 7762 } 7763 } 7764 7765 if (Method->isStatic()) 7766 checkThisInStaticMemberFunctionType(Method); 7767 } 7768 7769 // Extra checking for C++ overloaded operators (C++ [over.oper]). 7770 if (NewFD->isOverloadedOperator() && 7771 CheckOverloadedOperatorDeclaration(NewFD)) { 7772 NewFD->setInvalidDecl(); 7773 return Redeclaration; 7774 } 7775 7776 // Extra checking for C++0x literal operators (C++0x [over.literal]). 7777 if (NewFD->getLiteralIdentifier() && 7778 CheckLiteralOperatorDeclaration(NewFD)) { 7779 NewFD->setInvalidDecl(); 7780 return Redeclaration; 7781 } 7782 7783 // In C++, check default arguments now that we have merged decls. Unless 7784 // the lexical context is the class, because in this case this is done 7785 // during delayed parsing anyway. 7786 if (!CurContext->isRecord()) 7787 CheckCXXDefaultArguments(NewFD); 7788 7789 // If this function declares a builtin function, check the type of this 7790 // declaration against the expected type for the builtin. 7791 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 7792 ASTContext::GetBuiltinTypeError Error; 7793 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 7794 QualType T = Context.GetBuiltinType(BuiltinID, Error); 7795 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 7796 // The type of this function differs from the type of the builtin, 7797 // so forget about the builtin entirely. 7798 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 7799 } 7800 } 7801 7802 // If this function is declared as being extern "C", then check to see if 7803 // the function returns a UDT (class, struct, or union type) that is not C 7804 // compatible, and if it does, warn the user. 7805 // But, issue any diagnostic on the first declaration only. 7806 if (NewFD->isExternC() && Previous.empty()) { 7807 QualType R = NewFD->getReturnType(); 7808 if (R->isIncompleteType() && !R->isVoidType()) 7809 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 7810 << NewFD << R; 7811 else if (!R.isPODType(Context) && !R->isVoidType() && 7812 !R->isObjCObjectPointerType()) 7813 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 7814 } 7815 } 7816 return Redeclaration; 7817 } 7818 7819 static SourceRange getResultSourceRange(const FunctionDecl *FD) { 7820 const TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 7821 if (!TSI) 7822 return SourceRange(); 7823 7824 TypeLoc TL = TSI->getTypeLoc(); 7825 FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>(); 7826 if (!FunctionTL) 7827 return SourceRange(); 7828 7829 TypeLoc ResultTL = FunctionTL.getReturnLoc(); 7830 if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>()) 7831 return ResultTL.getSourceRange(); 7832 7833 return SourceRange(); 7834 } 7835 7836 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 7837 // C++11 [basic.start.main]p3: 7838 // A program that [...] declares main to be inline, static or 7839 // constexpr is ill-formed. 7840 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 7841 // appear in a declaration of main. 7842 // static main is not an error under C99, but we should warn about it. 7843 // We accept _Noreturn main as an extension. 7844 if (FD->getStorageClass() == SC_Static) 7845 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 7846 ? diag::err_static_main : diag::warn_static_main) 7847 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 7848 if (FD->isInlineSpecified()) 7849 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 7850 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 7851 if (DS.isNoreturnSpecified()) { 7852 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 7853 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 7854 Diag(NoreturnLoc, diag::ext_noreturn_main); 7855 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 7856 << FixItHint::CreateRemoval(NoreturnRange); 7857 } 7858 if (FD->isConstexpr()) { 7859 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 7860 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 7861 FD->setConstexpr(false); 7862 } 7863 7864 if (getLangOpts().OpenCL) { 7865 Diag(FD->getLocation(), diag::err_opencl_no_main) 7866 << FD->hasAttr<OpenCLKernelAttr>(); 7867 FD->setInvalidDecl(); 7868 return; 7869 } 7870 7871 QualType T = FD->getType(); 7872 assert(T->isFunctionType() && "function decl is not of function type"); 7873 const FunctionType* FT = T->castAs<FunctionType>(); 7874 7875 // All the standards say that main() should should return 'int'. 7876 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) { 7877 // In C and C++, main magically returns 0 if you fall off the end; 7878 // set the flag which tells us that. 7879 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 7880 FD->setHasImplicitReturnZero(true); 7881 7882 // In C with GNU extensions we allow main() to have non-integer return 7883 // type, but we should warn about the extension, and we disable the 7884 // implicit-return-zero rule. 7885 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 7886 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 7887 7888 SourceRange ResultRange = getResultSourceRange(FD); 7889 if (ResultRange.isValid()) 7890 Diag(ResultRange.getBegin(), diag::note_main_change_return_type) 7891 << FixItHint::CreateReplacement(ResultRange, "int"); 7892 7893 // Otherwise, this is just a flat-out error. 7894 } else { 7895 SourceRange ResultRange = getResultSourceRange(FD); 7896 if (ResultRange.isValid()) 7897 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 7898 << FixItHint::CreateReplacement(ResultRange, "int"); 7899 else 7900 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 7901 7902 FD->setInvalidDecl(true); 7903 } 7904 7905 // Treat protoless main() as nullary. 7906 if (isa<FunctionNoProtoType>(FT)) return; 7907 7908 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 7909 unsigned nparams = FTP->getNumParams(); 7910 assert(FD->getNumParams() == nparams); 7911 7912 bool HasExtraParameters = (nparams > 3); 7913 7914 // Darwin passes an undocumented fourth argument of type char**. If 7915 // other platforms start sprouting these, the logic below will start 7916 // getting shifty. 7917 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 7918 HasExtraParameters = false; 7919 7920 if (HasExtraParameters) { 7921 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 7922 FD->setInvalidDecl(true); 7923 nparams = 3; 7924 } 7925 7926 // FIXME: a lot of the following diagnostics would be improved 7927 // if we had some location information about types. 7928 7929 QualType CharPP = 7930 Context.getPointerType(Context.getPointerType(Context.CharTy)); 7931 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 7932 7933 for (unsigned i = 0; i < nparams; ++i) { 7934 QualType AT = FTP->getParamType(i); 7935 7936 bool mismatch = true; 7937 7938 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 7939 mismatch = false; 7940 else if (Expected[i] == CharPP) { 7941 // As an extension, the following forms are okay: 7942 // char const ** 7943 // char const * const * 7944 // char * const * 7945 7946 QualifierCollector qs; 7947 const PointerType* PT; 7948 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 7949 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 7950 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 7951 Context.CharTy)) { 7952 qs.removeConst(); 7953 mismatch = !qs.empty(); 7954 } 7955 } 7956 7957 if (mismatch) { 7958 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 7959 // TODO: suggest replacing given type with expected type 7960 FD->setInvalidDecl(true); 7961 } 7962 } 7963 7964 if (nparams == 1 && !FD->isInvalidDecl()) { 7965 Diag(FD->getLocation(), diag::warn_main_one_arg); 7966 } 7967 7968 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7969 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7970 FD->setInvalidDecl(); 7971 } 7972 } 7973 7974 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 7975 QualType T = FD->getType(); 7976 assert(T->isFunctionType() && "function decl is not of function type"); 7977 const FunctionType *FT = T->castAs<FunctionType>(); 7978 7979 // Set an implicit return of 'zero' if the function can return some integral, 7980 // enumeration, pointer or nullptr type. 7981 if (FT->getReturnType()->isIntegralOrEnumerationType() || 7982 FT->getReturnType()->isAnyPointerType() || 7983 FT->getReturnType()->isNullPtrType()) 7984 // DllMain is exempt because a return value of zero means it failed. 7985 if (FD->getName() != "DllMain") 7986 FD->setHasImplicitReturnZero(true); 7987 7988 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 7989 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 7990 FD->setInvalidDecl(); 7991 } 7992 } 7993 7994 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 7995 // FIXME: Need strict checking. In C89, we need to check for 7996 // any assignment, increment, decrement, function-calls, or 7997 // commas outside of a sizeof. In C99, it's the same list, 7998 // except that the aforementioned are allowed in unevaluated 7999 // expressions. Everything else falls under the 8000 // "may accept other forms of constant expressions" exception. 8001 // (We never end up here for C++, so the constant expression 8002 // rules there don't matter.) 8003 const Expr *Culprit; 8004 if (Init->isConstantInitializer(Context, false, &Culprit)) 8005 return false; 8006 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8007 << Culprit->getSourceRange(); 8008 return true; 8009 } 8010 8011 namespace { 8012 // Visits an initialization expression to see if OrigDecl is evaluated in 8013 // its own initialization and throws a warning if it does. 8014 class SelfReferenceChecker 8015 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8016 Sema &S; 8017 Decl *OrigDecl; 8018 bool isRecordType; 8019 bool isPODType; 8020 bool isReferenceType; 8021 8022 public: 8023 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8024 8025 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8026 S(S), OrigDecl(OrigDecl) { 8027 isPODType = false; 8028 isRecordType = false; 8029 isReferenceType = false; 8030 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8031 isPODType = VD->getType().isPODType(S.Context); 8032 isRecordType = VD->getType()->isRecordType(); 8033 isReferenceType = VD->getType()->isReferenceType(); 8034 } 8035 } 8036 8037 // For most expressions, the cast is directly above the DeclRefExpr. 8038 // For conditional operators, the cast can be outside the conditional 8039 // operator if both expressions are DeclRefExpr's. 8040 void HandleValue(Expr *E) { 8041 if (isReferenceType) 8042 return; 8043 E = E->IgnoreParenImpCasts(); 8044 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8045 HandleDeclRefExpr(DRE); 8046 return; 8047 } 8048 8049 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8050 HandleValue(CO->getTrueExpr()); 8051 HandleValue(CO->getFalseExpr()); 8052 return; 8053 } 8054 8055 if (isa<MemberExpr>(E)) { 8056 Expr *Base = E->IgnoreParenImpCasts(); 8057 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8058 // Check for static member variables and don't warn on them. 8059 if (!isa<FieldDecl>(ME->getMemberDecl())) 8060 return; 8061 Base = ME->getBase()->IgnoreParenImpCasts(); 8062 } 8063 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8064 HandleDeclRefExpr(DRE); 8065 return; 8066 } 8067 } 8068 8069 // Reference types are handled here since all uses of references are 8070 // bad, not just r-value uses. 8071 void VisitDeclRefExpr(DeclRefExpr *E) { 8072 if (isReferenceType) 8073 HandleDeclRefExpr(E); 8074 } 8075 8076 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8077 if (E->getCastKind() == CK_LValueToRValue || 8078 (isRecordType && E->getCastKind() == CK_NoOp)) 8079 HandleValue(E->getSubExpr()); 8080 8081 Inherited::VisitImplicitCastExpr(E); 8082 } 8083 8084 void VisitMemberExpr(MemberExpr *E) { 8085 // Don't warn on arrays since they can be treated as pointers. 8086 if (E->getType()->canDecayToPointerType()) return; 8087 8088 // Warn when a non-static method call is followed by non-static member 8089 // field accesses, which is followed by a DeclRefExpr. 8090 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8091 bool Warn = (MD && !MD->isStatic()); 8092 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8093 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8094 if (!isa<FieldDecl>(ME->getMemberDecl())) 8095 Warn = false; 8096 Base = ME->getBase()->IgnoreParenImpCasts(); 8097 } 8098 8099 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8100 if (Warn) 8101 HandleDeclRefExpr(DRE); 8102 return; 8103 } 8104 8105 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8106 // Visit that expression. 8107 Visit(Base); 8108 } 8109 8110 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8111 if (E->getNumArgs() > 0) 8112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8113 HandleDeclRefExpr(DRE); 8114 8115 Inherited::VisitCXXOperatorCallExpr(E); 8116 } 8117 8118 void VisitUnaryOperator(UnaryOperator *E) { 8119 // For POD record types, addresses of its own members are well-defined. 8120 if (E->getOpcode() == UO_AddrOf && isRecordType && 8121 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8122 if (!isPODType) 8123 HandleValue(E->getSubExpr()); 8124 return; 8125 } 8126 Inherited::VisitUnaryOperator(E); 8127 } 8128 8129 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8130 8131 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8132 Decl* ReferenceDecl = DRE->getDecl(); 8133 if (OrigDecl != ReferenceDecl) return; 8134 unsigned diag; 8135 if (isReferenceType) { 8136 diag = diag::warn_uninit_self_reference_in_reference_init; 8137 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8138 diag = diag::warn_static_self_reference_in_init; 8139 } else { 8140 diag = diag::warn_uninit_self_reference_in_init; 8141 } 8142 8143 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8144 S.PDiag(diag) 8145 << DRE->getNameInfo().getName() 8146 << OrigDecl->getLocation() 8147 << DRE->getSourceRange()); 8148 } 8149 }; 8150 8151 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8152 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8153 bool DirectInit) { 8154 // Parameters arguments are occassionially constructed with itself, 8155 // for instance, in recursive functions. Skip them. 8156 if (isa<ParmVarDecl>(OrigDecl)) 8157 return; 8158 8159 E = E->IgnoreParens(); 8160 8161 // Skip checking T a = a where T is not a record or reference type. 8162 // Doing so is a way to silence uninitialized warnings. 8163 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8164 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8165 if (ICE->getCastKind() == CK_LValueToRValue) 8166 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8167 if (DRE->getDecl() == OrigDecl) 8168 return; 8169 8170 SelfReferenceChecker(S, OrigDecl).Visit(E); 8171 } 8172 } 8173 8174 /// AddInitializerToDecl - Adds the initializer Init to the 8175 /// declaration dcl. If DirectInit is true, this is C++ direct 8176 /// initialization rather than copy initialization. 8177 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8178 bool DirectInit, bool TypeMayContainAuto) { 8179 // If there is no declaration, there was an error parsing it. Just ignore 8180 // the initializer. 8181 if (!RealDecl || RealDecl->isInvalidDecl()) 8182 return; 8183 8184 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8185 // With declarators parsed the way they are, the parser cannot 8186 // distinguish between a normal initializer and a pure-specifier. 8187 // Thus this grotesque test. 8188 IntegerLiteral *IL; 8189 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8190 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8191 CheckPureMethod(Method, Init->getSourceRange()); 8192 else { 8193 Diag(Method->getLocation(), diag::err_member_function_initialization) 8194 << Method->getDeclName() << Init->getSourceRange(); 8195 Method->setInvalidDecl(); 8196 } 8197 return; 8198 } 8199 8200 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8201 if (!VDecl) { 8202 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8203 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8204 RealDecl->setInvalidDecl(); 8205 return; 8206 } 8207 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8208 8209 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8210 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8211 Expr *DeduceInit = Init; 8212 // Initializer could be a C++ direct-initializer. Deduction only works if it 8213 // contains exactly one expression. 8214 if (CXXDirectInit) { 8215 if (CXXDirectInit->getNumExprs() == 0) { 8216 // It isn't possible to write this directly, but it is possible to 8217 // end up in this situation with "auto x(some_pack...);" 8218 Diag(CXXDirectInit->getLocStart(), 8219 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8220 : diag::err_auto_var_init_no_expression) 8221 << VDecl->getDeclName() << VDecl->getType() 8222 << VDecl->getSourceRange(); 8223 RealDecl->setInvalidDecl(); 8224 return; 8225 } else if (CXXDirectInit->getNumExprs() > 1) { 8226 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8227 VDecl->isInitCapture() 8228 ? diag::err_init_capture_multiple_expressions 8229 : diag::err_auto_var_init_multiple_expressions) 8230 << VDecl->getDeclName() << VDecl->getType() 8231 << VDecl->getSourceRange(); 8232 RealDecl->setInvalidDecl(); 8233 return; 8234 } else { 8235 DeduceInit = CXXDirectInit->getExpr(0); 8236 if (isa<InitListExpr>(DeduceInit)) 8237 Diag(CXXDirectInit->getLocStart(), 8238 diag::err_auto_var_init_paren_braces) 8239 << VDecl->getDeclName() << VDecl->getType() 8240 << VDecl->getSourceRange(); 8241 } 8242 } 8243 8244 // Expressions default to 'id' when we're in a debugger. 8245 bool DefaultedToAuto = false; 8246 if (getLangOpts().DebuggerCastResultToId && 8247 Init->getType() == Context.UnknownAnyTy) { 8248 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8249 if (Result.isInvalid()) { 8250 VDecl->setInvalidDecl(); 8251 return; 8252 } 8253 Init = Result.get(); 8254 DefaultedToAuto = true; 8255 } 8256 8257 QualType DeducedType; 8258 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8259 DAR_Failed) 8260 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8261 if (DeducedType.isNull()) { 8262 RealDecl->setInvalidDecl(); 8263 return; 8264 } 8265 VDecl->setType(DeducedType); 8266 assert(VDecl->isLinkageValid()); 8267 8268 // In ARC, infer lifetime. 8269 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8270 VDecl->setInvalidDecl(); 8271 8272 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8273 // 'id' instead of a specific object type prevents most of our usual checks. 8274 // We only want to warn outside of template instantiations, though: 8275 // inside a template, the 'id' could have come from a parameter. 8276 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8277 DeducedType->isObjCIdType()) { 8278 SourceLocation Loc = 8279 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8280 Diag(Loc, diag::warn_auto_var_is_id) 8281 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8282 } 8283 8284 // If this is a redeclaration, check that the type we just deduced matches 8285 // the previously declared type. 8286 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8287 // We never need to merge the type, because we cannot form an incomplete 8288 // array of auto, nor deduce such a type. 8289 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8290 } 8291 8292 // Check the deduced type is valid for a variable declaration. 8293 CheckVariableDeclarationType(VDecl); 8294 if (VDecl->isInvalidDecl()) 8295 return; 8296 } 8297 8298 // dllimport cannot be used on variable definitions. 8299 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8300 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8301 VDecl->setInvalidDecl(); 8302 return; 8303 } 8304 8305 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8306 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8307 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8308 VDecl->setInvalidDecl(); 8309 return; 8310 } 8311 8312 if (!VDecl->getType()->isDependentType()) { 8313 // A definition must end up with a complete type, which means it must be 8314 // complete with the restriction that an array type might be completed by 8315 // the initializer; note that later code assumes this restriction. 8316 QualType BaseDeclType = VDecl->getType(); 8317 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8318 BaseDeclType = Array->getElementType(); 8319 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8320 diag::err_typecheck_decl_incomplete_type)) { 8321 RealDecl->setInvalidDecl(); 8322 return; 8323 } 8324 8325 // The variable can not have an abstract class type. 8326 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8327 diag::err_abstract_type_in_decl, 8328 AbstractVariableType)) 8329 VDecl->setInvalidDecl(); 8330 } 8331 8332 const VarDecl *Def; 8333 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8334 Diag(VDecl->getLocation(), diag::err_redefinition) 8335 << VDecl->getDeclName(); 8336 Diag(Def->getLocation(), diag::note_previous_definition); 8337 VDecl->setInvalidDecl(); 8338 return; 8339 } 8340 8341 const VarDecl *PrevInit = nullptr; 8342 if (getLangOpts().CPlusPlus) { 8343 // C++ [class.static.data]p4 8344 // If a static data member is of const integral or const 8345 // enumeration type, its declaration in the class definition can 8346 // specify a constant-initializer which shall be an integral 8347 // constant expression (5.19). In that case, the member can appear 8348 // in integral constant expressions. The member shall still be 8349 // defined in a namespace scope if it is used in the program and the 8350 // namespace scope definition shall not contain an initializer. 8351 // 8352 // We already performed a redefinition check above, but for static 8353 // data members we also need to check whether there was an in-class 8354 // declaration with an initializer. 8355 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8356 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8357 << VDecl->getDeclName(); 8358 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8359 return; 8360 } 8361 8362 if (VDecl->hasLocalStorage()) 8363 getCurFunction()->setHasBranchProtectedScope(); 8364 8365 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8366 VDecl->setInvalidDecl(); 8367 return; 8368 } 8369 } 8370 8371 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8372 // a kernel function cannot be initialized." 8373 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8374 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8375 VDecl->setInvalidDecl(); 8376 return; 8377 } 8378 8379 // Get the decls type and save a reference for later, since 8380 // CheckInitializerTypes may change it. 8381 QualType DclT = VDecl->getType(), SavT = DclT; 8382 8383 // Expressions default to 'id' when we're in a debugger 8384 // and we are assigning it to a variable of Objective-C pointer type. 8385 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8386 Init->getType() == Context.UnknownAnyTy) { 8387 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8388 if (Result.isInvalid()) { 8389 VDecl->setInvalidDecl(); 8390 return; 8391 } 8392 Init = Result.get(); 8393 } 8394 8395 // Perform the initialization. 8396 if (!VDecl->isInvalidDecl()) { 8397 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8398 InitializationKind Kind 8399 = DirectInit ? 8400 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8401 Init->getLocStart(), 8402 Init->getLocEnd()) 8403 : InitializationKind::CreateDirectList( 8404 VDecl->getLocation()) 8405 : InitializationKind::CreateCopy(VDecl->getLocation(), 8406 Init->getLocStart()); 8407 8408 MultiExprArg Args = Init; 8409 if (CXXDirectInit) 8410 Args = MultiExprArg(CXXDirectInit->getExprs(), 8411 CXXDirectInit->getNumExprs()); 8412 8413 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8414 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8415 if (Result.isInvalid()) { 8416 VDecl->setInvalidDecl(); 8417 return; 8418 } 8419 8420 Init = Result.getAs<Expr>(); 8421 } 8422 8423 // Check for self-references within variable initializers. 8424 // Variables declared within a function/method body (except for references) 8425 // are handled by a dataflow analysis. 8426 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8427 VDecl->getType()->isReferenceType()) { 8428 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8429 } 8430 8431 // If the type changed, it means we had an incomplete type that was 8432 // completed by the initializer. For example: 8433 // int ary[] = { 1, 3, 5 }; 8434 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8435 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8436 VDecl->setType(DclT); 8437 8438 if (!VDecl->isInvalidDecl()) { 8439 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8440 8441 if (VDecl->hasAttr<BlocksAttr>()) 8442 checkRetainCycles(VDecl, Init); 8443 8444 // It is safe to assign a weak reference into a strong variable. 8445 // Although this code can still have problems: 8446 // id x = self.weakProp; 8447 // id y = self.weakProp; 8448 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8449 // paths through the function. This should be revisited if 8450 // -Wrepeated-use-of-weak is made flow-sensitive. 8451 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) { 8452 DiagnosticsEngine::Level Level = 8453 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8454 Init->getLocStart()); 8455 if (Level != DiagnosticsEngine::Ignored) 8456 getCurFunction()->markSafeWeakUse(Init); 8457 } 8458 } 8459 8460 // The initialization is usually a full-expression. 8461 // 8462 // FIXME: If this is a braced initialization of an aggregate, it is not 8463 // an expression, and each individual field initializer is a separate 8464 // full-expression. For instance, in: 8465 // 8466 // struct Temp { ~Temp(); }; 8467 // struct S { S(Temp); }; 8468 // struct T { S a, b; } t = { Temp(), Temp() } 8469 // 8470 // we should destroy the first Temp before constructing the second. 8471 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8472 false, 8473 VDecl->isConstexpr()); 8474 if (Result.isInvalid()) { 8475 VDecl->setInvalidDecl(); 8476 return; 8477 } 8478 Init = Result.get(); 8479 8480 // Attach the initializer to the decl. 8481 VDecl->setInit(Init); 8482 8483 if (VDecl->isLocalVarDecl()) { 8484 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8485 // static storage duration shall be constant expressions or string literals. 8486 // C++ does not have this restriction. 8487 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8488 const Expr *Culprit; 8489 if (VDecl->getStorageClass() == SC_Static) 8490 CheckForConstantInitializer(Init, DclT); 8491 // C89 is stricter than C99 for non-static aggregate types. 8492 // C89 6.5.7p3: All the expressions [...] in an initializer list 8493 // for an object that has aggregate or union type shall be 8494 // constant expressions. 8495 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8496 isa<InitListExpr>(Init) && 8497 !Init->isConstantInitializer(Context, false, &Culprit)) 8498 Diag(Culprit->getExprLoc(), 8499 diag::ext_aggregate_init_not_constant) 8500 << Culprit->getSourceRange(); 8501 } 8502 } else if (VDecl->isStaticDataMember() && 8503 VDecl->getLexicalDeclContext()->isRecord()) { 8504 // This is an in-class initialization for a static data member, e.g., 8505 // 8506 // struct S { 8507 // static const int value = 17; 8508 // }; 8509 8510 // C++ [class.mem]p4: 8511 // A member-declarator can contain a constant-initializer only 8512 // if it declares a static member (9.4) of const integral or 8513 // const enumeration type, see 9.4.2. 8514 // 8515 // C++11 [class.static.data]p3: 8516 // If a non-volatile const static data member is of integral or 8517 // enumeration type, its declaration in the class definition can 8518 // specify a brace-or-equal-initializer in which every initalizer-clause 8519 // that is an assignment-expression is a constant expression. A static 8520 // data member of literal type can be declared in the class definition 8521 // with the constexpr specifier; if so, its declaration shall specify a 8522 // brace-or-equal-initializer in which every initializer-clause that is 8523 // an assignment-expression is a constant expression. 8524 8525 // Do nothing on dependent types. 8526 if (DclT->isDependentType()) { 8527 8528 // Allow any 'static constexpr' members, whether or not they are of literal 8529 // type. We separately check that every constexpr variable is of literal 8530 // type. 8531 } else if (VDecl->isConstexpr()) { 8532 8533 // Require constness. 8534 } else if (!DclT.isConstQualified()) { 8535 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8536 << Init->getSourceRange(); 8537 VDecl->setInvalidDecl(); 8538 8539 // We allow integer constant expressions in all cases. 8540 } else if (DclT->isIntegralOrEnumerationType()) { 8541 // Check whether the expression is a constant expression. 8542 SourceLocation Loc; 8543 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8544 // In C++11, a non-constexpr const static data member with an 8545 // in-class initializer cannot be volatile. 8546 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8547 else if (Init->isValueDependent()) 8548 ; // Nothing to check. 8549 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8550 ; // Ok, it's an ICE! 8551 else if (Init->isEvaluatable(Context)) { 8552 // If we can constant fold the initializer through heroics, accept it, 8553 // but report this as a use of an extension for -pedantic. 8554 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8555 << Init->getSourceRange(); 8556 } else { 8557 // Otherwise, this is some crazy unknown case. Report the issue at the 8558 // location provided by the isIntegerConstantExpr failed check. 8559 Diag(Loc, diag::err_in_class_initializer_non_constant) 8560 << Init->getSourceRange(); 8561 VDecl->setInvalidDecl(); 8562 } 8563 8564 // We allow foldable floating-point constants as an extension. 8565 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8566 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8567 // it anyway and provide a fixit to add the 'constexpr'. 8568 if (getLangOpts().CPlusPlus11) { 8569 Diag(VDecl->getLocation(), 8570 diag::ext_in_class_initializer_float_type_cxx11) 8571 << DclT << Init->getSourceRange(); 8572 Diag(VDecl->getLocStart(), 8573 diag::note_in_class_initializer_float_type_cxx11) 8574 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8575 } else { 8576 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8577 << DclT << Init->getSourceRange(); 8578 8579 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8580 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8581 << Init->getSourceRange(); 8582 VDecl->setInvalidDecl(); 8583 } 8584 } 8585 8586 // Suggest adding 'constexpr' in C++11 for literal types. 8587 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8588 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8589 << DclT << Init->getSourceRange() 8590 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8591 VDecl->setConstexpr(true); 8592 8593 } else { 8594 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8595 << DclT << Init->getSourceRange(); 8596 VDecl->setInvalidDecl(); 8597 } 8598 } else if (VDecl->isFileVarDecl()) { 8599 if (VDecl->getStorageClass() == SC_Extern && 8600 (!getLangOpts().CPlusPlus || 8601 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8602 VDecl->isExternC())) && 8603 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8604 Diag(VDecl->getLocation(), diag::warn_extern_init); 8605 8606 // C99 6.7.8p4. All file scoped initializers need to be constant. 8607 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8608 CheckForConstantInitializer(Init, DclT); 8609 } 8610 8611 // We will represent direct-initialization similarly to copy-initialization: 8612 // int x(1); -as-> int x = 1; 8613 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8614 // 8615 // Clients that want to distinguish between the two forms, can check for 8616 // direct initializer using VarDecl::getInitStyle(). 8617 // A major benefit is that clients that don't particularly care about which 8618 // exactly form was it (like the CodeGen) can handle both cases without 8619 // special case code. 8620 8621 // C++ 8.5p11: 8622 // The form of initialization (using parentheses or '=') is generally 8623 // insignificant, but does matter when the entity being initialized has a 8624 // class type. 8625 if (CXXDirectInit) { 8626 assert(DirectInit && "Call-style initializer must be direct init."); 8627 VDecl->setInitStyle(VarDecl::CallInit); 8628 } else if (DirectInit) { 8629 // This must be list-initialization. No other way is direct-initialization. 8630 VDecl->setInitStyle(VarDecl::ListInit); 8631 } 8632 8633 CheckCompleteVariableDeclaration(VDecl); 8634 } 8635 8636 /// ActOnInitializerError - Given that there was an error parsing an 8637 /// initializer for the given declaration, try to return to some form 8638 /// of sanity. 8639 void Sema::ActOnInitializerError(Decl *D) { 8640 // Our main concern here is re-establishing invariants like "a 8641 // variable's type is either dependent or complete". 8642 if (!D || D->isInvalidDecl()) return; 8643 8644 VarDecl *VD = dyn_cast<VarDecl>(D); 8645 if (!VD) return; 8646 8647 // Auto types are meaningless if we can't make sense of the initializer. 8648 if (ParsingInitForAutoVars.count(D)) { 8649 D->setInvalidDecl(); 8650 return; 8651 } 8652 8653 QualType Ty = VD->getType(); 8654 if (Ty->isDependentType()) return; 8655 8656 // Require a complete type. 8657 if (RequireCompleteType(VD->getLocation(), 8658 Context.getBaseElementType(Ty), 8659 diag::err_typecheck_decl_incomplete_type)) { 8660 VD->setInvalidDecl(); 8661 return; 8662 } 8663 8664 // Require a non-abstract type. 8665 if (RequireNonAbstractType(VD->getLocation(), Ty, 8666 diag::err_abstract_type_in_decl, 8667 AbstractVariableType)) { 8668 VD->setInvalidDecl(); 8669 return; 8670 } 8671 8672 // Don't bother complaining about constructors or destructors, 8673 // though. 8674 } 8675 8676 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 8677 bool TypeMayContainAuto) { 8678 // If there is no declaration, there was an error parsing it. Just ignore it. 8679 if (!RealDecl) 8680 return; 8681 8682 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 8683 QualType Type = Var->getType(); 8684 8685 // C++11 [dcl.spec.auto]p3 8686 if (TypeMayContainAuto && Type->getContainedAutoType()) { 8687 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 8688 << Var->getDeclName() << Type; 8689 Var->setInvalidDecl(); 8690 return; 8691 } 8692 8693 // C++11 [class.static.data]p3: A static data member can be declared with 8694 // the constexpr specifier; if so, its declaration shall specify 8695 // a brace-or-equal-initializer. 8696 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 8697 // the definition of a variable [...] or the declaration of a static data 8698 // member. 8699 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 8700 if (Var->isStaticDataMember()) 8701 Diag(Var->getLocation(), 8702 diag::err_constexpr_static_mem_var_requires_init) 8703 << Var->getDeclName(); 8704 else 8705 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 8706 Var->setInvalidDecl(); 8707 return; 8708 } 8709 8710 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 8711 // be initialized. 8712 if (!Var->isInvalidDecl() && 8713 Var->getType().getAddressSpace() == LangAS::opencl_constant && 8714 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 8715 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 8716 Var->setInvalidDecl(); 8717 return; 8718 } 8719 8720 switch (Var->isThisDeclarationADefinition()) { 8721 case VarDecl::Definition: 8722 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 8723 break; 8724 8725 // We have an out-of-line definition of a static data member 8726 // that has an in-class initializer, so we type-check this like 8727 // a declaration. 8728 // 8729 // Fall through 8730 8731 case VarDecl::DeclarationOnly: 8732 // It's only a declaration. 8733 8734 // Block scope. C99 6.7p7: If an identifier for an object is 8735 // declared with no linkage (C99 6.2.2p6), the type for the 8736 // object shall be complete. 8737 if (!Type->isDependentType() && Var->isLocalVarDecl() && 8738 !Var->hasLinkage() && !Var->isInvalidDecl() && 8739 RequireCompleteType(Var->getLocation(), Type, 8740 diag::err_typecheck_decl_incomplete_type)) 8741 Var->setInvalidDecl(); 8742 8743 // Make sure that the type is not abstract. 8744 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8745 RequireNonAbstractType(Var->getLocation(), Type, 8746 diag::err_abstract_type_in_decl, 8747 AbstractVariableType)) 8748 Var->setInvalidDecl(); 8749 if (!Type->isDependentType() && !Var->isInvalidDecl() && 8750 Var->getStorageClass() == SC_PrivateExtern) { 8751 Diag(Var->getLocation(), diag::warn_private_extern); 8752 Diag(Var->getLocation(), diag::note_private_extern); 8753 } 8754 8755 return; 8756 8757 case VarDecl::TentativeDefinition: 8758 // File scope. C99 6.9.2p2: A declaration of an identifier for an 8759 // object that has file scope without an initializer, and without a 8760 // storage-class specifier or with the storage-class specifier "static", 8761 // constitutes a tentative definition. Note: A tentative definition with 8762 // external linkage is valid (C99 6.2.2p5). 8763 if (!Var->isInvalidDecl()) { 8764 if (const IncompleteArrayType *ArrayT 8765 = Context.getAsIncompleteArrayType(Type)) { 8766 if (RequireCompleteType(Var->getLocation(), 8767 ArrayT->getElementType(), 8768 diag::err_illegal_decl_array_incomplete_type)) 8769 Var->setInvalidDecl(); 8770 } else if (Var->getStorageClass() == SC_Static) { 8771 // C99 6.9.2p3: If the declaration of an identifier for an object is 8772 // a tentative definition and has internal linkage (C99 6.2.2p3), the 8773 // declared type shall not be an incomplete type. 8774 // NOTE: code such as the following 8775 // static struct s; 8776 // struct s { int a; }; 8777 // is accepted by gcc. Hence here we issue a warning instead of 8778 // an error and we do not invalidate the static declaration. 8779 // NOTE: to avoid multiple warnings, only check the first declaration. 8780 if (Var->isFirstDecl()) 8781 RequireCompleteType(Var->getLocation(), Type, 8782 diag::ext_typecheck_decl_incomplete_type); 8783 } 8784 } 8785 8786 // Record the tentative definition; we're done. 8787 if (!Var->isInvalidDecl()) 8788 TentativeDefinitions.push_back(Var); 8789 return; 8790 } 8791 8792 // Provide a specific diagnostic for uninitialized variable 8793 // definitions with incomplete array type. 8794 if (Type->isIncompleteArrayType()) { 8795 Diag(Var->getLocation(), 8796 diag::err_typecheck_incomplete_array_needs_initializer); 8797 Var->setInvalidDecl(); 8798 return; 8799 } 8800 8801 // Provide a specific diagnostic for uninitialized variable 8802 // definitions with reference type. 8803 if (Type->isReferenceType()) { 8804 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 8805 << Var->getDeclName() 8806 << SourceRange(Var->getLocation(), Var->getLocation()); 8807 Var->setInvalidDecl(); 8808 return; 8809 } 8810 8811 // Do not attempt to type-check the default initializer for a 8812 // variable with dependent type. 8813 if (Type->isDependentType()) 8814 return; 8815 8816 if (Var->isInvalidDecl()) 8817 return; 8818 8819 if (RequireCompleteType(Var->getLocation(), 8820 Context.getBaseElementType(Type), 8821 diag::err_typecheck_decl_incomplete_type)) { 8822 Var->setInvalidDecl(); 8823 return; 8824 } 8825 8826 // The variable can not have an abstract class type. 8827 if (RequireNonAbstractType(Var->getLocation(), Type, 8828 diag::err_abstract_type_in_decl, 8829 AbstractVariableType)) { 8830 Var->setInvalidDecl(); 8831 return; 8832 } 8833 8834 // Check for jumps past the implicit initializer. C++0x 8835 // clarifies that this applies to a "variable with automatic 8836 // storage duration", not a "local variable". 8837 // C++11 [stmt.dcl]p3 8838 // A program that jumps from a point where a variable with automatic 8839 // storage duration is not in scope to a point where it is in scope is 8840 // ill-formed unless the variable has scalar type, class type with a 8841 // trivial default constructor and a trivial destructor, a cv-qualified 8842 // version of one of these types, or an array of one of the preceding 8843 // types and is declared without an initializer. 8844 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 8845 if (const RecordType *Record 8846 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 8847 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 8848 // Mark the function for further checking even if the looser rules of 8849 // C++11 do not require such checks, so that we can diagnose 8850 // incompatibilities with C++98. 8851 if (!CXXRecord->isPOD()) 8852 getCurFunction()->setHasBranchProtectedScope(); 8853 } 8854 } 8855 8856 // C++03 [dcl.init]p9: 8857 // If no initializer is specified for an object, and the 8858 // object is of (possibly cv-qualified) non-POD class type (or 8859 // array thereof), the object shall be default-initialized; if 8860 // the object is of const-qualified type, the underlying class 8861 // type shall have a user-declared default 8862 // constructor. Otherwise, if no initializer is specified for 8863 // a non- static object, the object and its subobjects, if 8864 // any, have an indeterminate initial value); if the object 8865 // or any of its subobjects are of const-qualified type, the 8866 // program is ill-formed. 8867 // C++0x [dcl.init]p11: 8868 // If no initializer is specified for an object, the object is 8869 // default-initialized; [...]. 8870 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 8871 InitializationKind Kind 8872 = InitializationKind::CreateDefault(Var->getLocation()); 8873 8874 InitializationSequence InitSeq(*this, Entity, Kind, None); 8875 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 8876 if (Init.isInvalid()) 8877 Var->setInvalidDecl(); 8878 else if (Init.get()) { 8879 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 8880 // This is important for template substitution. 8881 Var->setInitStyle(VarDecl::CallInit); 8882 } 8883 8884 CheckCompleteVariableDeclaration(Var); 8885 } 8886 } 8887 8888 void Sema::ActOnCXXForRangeDecl(Decl *D) { 8889 VarDecl *VD = dyn_cast<VarDecl>(D); 8890 if (!VD) { 8891 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 8892 D->setInvalidDecl(); 8893 return; 8894 } 8895 8896 VD->setCXXForRangeDecl(true); 8897 8898 // for-range-declaration cannot be given a storage class specifier. 8899 int Error = -1; 8900 switch (VD->getStorageClass()) { 8901 case SC_None: 8902 break; 8903 case SC_Extern: 8904 Error = 0; 8905 break; 8906 case SC_Static: 8907 Error = 1; 8908 break; 8909 case SC_PrivateExtern: 8910 Error = 2; 8911 break; 8912 case SC_Auto: 8913 Error = 3; 8914 break; 8915 case SC_Register: 8916 Error = 4; 8917 break; 8918 case SC_OpenCLWorkGroupLocal: 8919 llvm_unreachable("Unexpected storage class"); 8920 } 8921 if (VD->isConstexpr()) 8922 Error = 5; 8923 if (Error != -1) { 8924 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 8925 << VD->getDeclName() << Error; 8926 D->setInvalidDecl(); 8927 } 8928 } 8929 8930 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 8931 if (var->isInvalidDecl()) return; 8932 8933 // In ARC, don't allow jumps past the implicit initialization of a 8934 // local retaining variable. 8935 if (getLangOpts().ObjCAutoRefCount && 8936 var->hasLocalStorage()) { 8937 switch (var->getType().getObjCLifetime()) { 8938 case Qualifiers::OCL_None: 8939 case Qualifiers::OCL_ExplicitNone: 8940 case Qualifiers::OCL_Autoreleasing: 8941 break; 8942 8943 case Qualifiers::OCL_Weak: 8944 case Qualifiers::OCL_Strong: 8945 getCurFunction()->setHasBranchProtectedScope(); 8946 break; 8947 } 8948 } 8949 8950 // Warn about externally-visible variables being defined without a 8951 // prior declaration. We only want to do this for global 8952 // declarations, but we also specifically need to avoid doing it for 8953 // class members because the linkage of an anonymous class can 8954 // change if it's later given a typedef name. 8955 if (var->isThisDeclarationADefinition() && 8956 var->getDeclContext()->getRedeclContext()->isFileContext() && 8957 var->isExternallyVisible() && var->hasLinkage() && 8958 getDiagnostics().getDiagnosticLevel( 8959 diag::warn_missing_variable_declarations, 8960 var->getLocation())) { 8961 // Find a previous declaration that's not a definition. 8962 VarDecl *prev = var->getPreviousDecl(); 8963 while (prev && prev->isThisDeclarationADefinition()) 8964 prev = prev->getPreviousDecl(); 8965 8966 if (!prev) 8967 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 8968 } 8969 8970 if (var->getTLSKind() == VarDecl::TLS_Static) { 8971 const Expr *Culprit; 8972 if (var->getType().isDestructedType()) { 8973 // GNU C++98 edits for __thread, [basic.start.term]p3: 8974 // The type of an object with thread storage duration shall not 8975 // have a non-trivial destructor. 8976 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 8977 if (getLangOpts().CPlusPlus11) 8978 Diag(var->getLocation(), diag::note_use_thread_local); 8979 } else if (getLangOpts().CPlusPlus && var->hasInit() && 8980 !var->getInit()->isConstantInitializer( 8981 Context, var->getType()->isReferenceType(), &Culprit)) { 8982 // GNU C++98 edits for __thread, [basic.start.init]p4: 8983 // An object of thread storage duration shall not require dynamic 8984 // initialization. 8985 // FIXME: Need strict checking here. 8986 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 8987 << Culprit->getSourceRange(); 8988 if (getLangOpts().CPlusPlus11) 8989 Diag(var->getLocation(), diag::note_use_thread_local); 8990 } 8991 8992 } 8993 8994 if (var->isThisDeclarationADefinition() && 8995 ActiveTemplateInstantiations.empty()) { 8996 PragmaStack<StringLiteral *> *Stack = nullptr; 8997 int SectionFlags = PSF_Implicit | PSF_Read; 8998 if (var->getType().isConstQualified()) 8999 Stack = &ConstSegStack; 9000 else if (!var->getInit()) { 9001 Stack = &BSSSegStack; 9002 SectionFlags |= PSF_Write; 9003 } else { 9004 Stack = &DataSegStack; 9005 SectionFlags |= PSF_Write; 9006 } 9007 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 9008 var->addAttr( 9009 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 9010 Stack->CurrentValue->getString(), 9011 Stack->CurrentPragmaLocation)); 9012 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9013 if (UnifySection(SA->getName(), SectionFlags, var)) 9014 var->dropAttr<SectionAttr>(); 9015 } 9016 9017 // All the following checks are C++ only. 9018 if (!getLangOpts().CPlusPlus) return; 9019 9020 QualType type = var->getType(); 9021 if (type->isDependentType()) return; 9022 9023 // __block variables might require us to capture a copy-initializer. 9024 if (var->hasAttr<BlocksAttr>()) { 9025 // It's currently invalid to ever have a __block variable with an 9026 // array type; should we diagnose that here? 9027 9028 // Regardless, we don't want to ignore array nesting when 9029 // constructing this copy. 9030 if (type->isStructureOrClassType()) { 9031 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9032 SourceLocation poi = var->getLocation(); 9033 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9034 ExprResult result 9035 = PerformMoveOrCopyInitialization( 9036 InitializedEntity::InitializeBlock(poi, type, false), 9037 var, var->getType(), varRef, /*AllowNRVO=*/true); 9038 if (!result.isInvalid()) { 9039 result = MaybeCreateExprWithCleanups(result); 9040 Expr *init = result.getAs<Expr>(); 9041 Context.setBlockVarCopyInits(var, init); 9042 } 9043 } 9044 } 9045 9046 Expr *Init = var->getInit(); 9047 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 9048 QualType baseType = Context.getBaseElementType(type); 9049 9050 if (!var->getDeclContext()->isDependentContext() && 9051 Init && !Init->isValueDependent()) { 9052 if (IsGlobal && !var->isConstexpr() && 9053 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 9054 var->getLocation()) 9055 != DiagnosticsEngine::Ignored) { 9056 // Warn about globals which don't have a constant initializer. Don't 9057 // warn about globals with a non-trivial destructor because we already 9058 // warned about them. 9059 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9060 if (!(RD && !RD->hasTrivialDestructor()) && 9061 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9062 Diag(var->getLocation(), diag::warn_global_constructor) 9063 << Init->getSourceRange(); 9064 } 9065 9066 if (var->isConstexpr()) { 9067 SmallVector<PartialDiagnosticAt, 8> Notes; 9068 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9069 SourceLocation DiagLoc = var->getLocation(); 9070 // If the note doesn't add any useful information other than a source 9071 // location, fold it into the primary diagnostic. 9072 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9073 diag::note_invalid_subexpr_in_const_expr) { 9074 DiagLoc = Notes[0].first; 9075 Notes.clear(); 9076 } 9077 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9078 << var << Init->getSourceRange(); 9079 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9080 Diag(Notes[I].first, Notes[I].second); 9081 } 9082 } else if (var->isUsableInConstantExpressions(Context)) { 9083 // Check whether the initializer of a const variable of integral or 9084 // enumeration type is an ICE now, since we can't tell whether it was 9085 // initialized by a constant expression if we check later. 9086 var->checkInitIsICE(); 9087 } 9088 } 9089 9090 // Require the destructor. 9091 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9092 FinalizeVarWithDestructor(var, recordType); 9093 } 9094 9095 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9096 /// any semantic actions necessary after any initializer has been attached. 9097 void 9098 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9099 // Note that we are no longer parsing the initializer for this declaration. 9100 ParsingInitForAutoVars.erase(ThisDecl); 9101 9102 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9103 if (!VD) 9104 return; 9105 9106 checkAttributesAfterMerging(*this, *VD); 9107 9108 // Imported static data members cannot be defined out-of-line. 9109 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) { 9110 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9111 VD->isThisDeclarationADefinition()) { 9112 // We allow definitions of dllimport class template static data members 9113 // with a warning. 9114 CXXRecordDecl *Context = 9115 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9116 bool IsClassTemplateMember = 9117 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9118 Context->getDescribedClassTemplate(); 9119 9120 Diag(VD->getLocation(), 9121 IsClassTemplateMember 9122 ? diag::warn_attribute_dllimport_static_field_definition 9123 : diag::err_attribute_dllimport_static_field_definition); 9124 Diag(IA->getLocation(), diag::note_attribute); 9125 if (!IsClassTemplateMember) 9126 VD->setInvalidDecl(); 9127 } 9128 } 9129 9130 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9131 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9132 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9133 VD->dropAttr<UsedAttr>(); 9134 } 9135 } 9136 9137 if (!VD->isInvalidDecl() && 9138 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9139 if (const VarDecl *Def = VD->getDefinition()) { 9140 if (Def->hasAttr<AliasAttr>()) { 9141 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9142 << VD->getDeclName(); 9143 Diag(Def->getLocation(), diag::note_previous_definition); 9144 VD->setInvalidDecl(); 9145 } 9146 } 9147 } 9148 9149 const DeclContext *DC = VD->getDeclContext(); 9150 // If there's a #pragma GCC visibility in scope, and this isn't a class 9151 // member, set the visibility of this variable. 9152 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9153 AddPushedVisibilityAttribute(VD); 9154 9155 // FIXME: Warn on unused templates. 9156 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9157 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9158 MarkUnusedFileScopedDecl(VD); 9159 9160 // Now we have parsed the initializer and can update the table of magic 9161 // tag values. 9162 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9163 !VD->getType()->isIntegralOrEnumerationType()) 9164 return; 9165 9166 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9167 const Expr *MagicValueExpr = VD->getInit(); 9168 if (!MagicValueExpr) { 9169 continue; 9170 } 9171 llvm::APSInt MagicValueInt; 9172 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9173 Diag(I->getRange().getBegin(), 9174 diag::err_type_tag_for_datatype_not_ice) 9175 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9176 continue; 9177 } 9178 if (MagicValueInt.getActiveBits() > 64) { 9179 Diag(I->getRange().getBegin(), 9180 diag::err_type_tag_for_datatype_too_large) 9181 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9182 continue; 9183 } 9184 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9185 RegisterTypeTagForDatatype(I->getArgumentKind(), 9186 MagicValue, 9187 I->getMatchingCType(), 9188 I->getLayoutCompatible(), 9189 I->getMustBeNull()); 9190 } 9191 } 9192 9193 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9194 ArrayRef<Decl *> Group) { 9195 SmallVector<Decl*, 8> Decls; 9196 9197 if (DS.isTypeSpecOwned()) 9198 Decls.push_back(DS.getRepAsDecl()); 9199 9200 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9201 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9202 if (Decl *D = Group[i]) { 9203 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9204 if (!FirstDeclaratorInGroup) 9205 FirstDeclaratorInGroup = DD; 9206 Decls.push_back(D); 9207 } 9208 9209 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9210 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9211 HandleTagNumbering(*this, Tag, S); 9212 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9213 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9214 } 9215 } 9216 9217 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9218 } 9219 9220 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9221 /// group, performing any necessary semantic checking. 9222 Sema::DeclGroupPtrTy 9223 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group, 9224 bool TypeMayContainAuto) { 9225 // C++0x [dcl.spec.auto]p7: 9226 // If the type deduced for the template parameter U is not the same in each 9227 // deduction, the program is ill-formed. 9228 // FIXME: When initializer-list support is added, a distinction is needed 9229 // between the deduced type U and the deduced type which 'auto' stands for. 9230 // auto a = 0, b = { 1, 2, 3 }; 9231 // is legal because the deduced type U is 'int' in both cases. 9232 if (TypeMayContainAuto && Group.size() > 1) { 9233 QualType Deduced; 9234 CanQualType DeducedCanon; 9235 VarDecl *DeducedDecl = nullptr; 9236 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9237 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9238 AutoType *AT = D->getType()->getContainedAutoType(); 9239 // Don't reissue diagnostics when instantiating a template. 9240 if (AT && D->isInvalidDecl()) 9241 break; 9242 QualType U = AT ? AT->getDeducedType() : QualType(); 9243 if (!U.isNull()) { 9244 CanQualType UCanon = Context.getCanonicalType(U); 9245 if (Deduced.isNull()) { 9246 Deduced = U; 9247 DeducedCanon = UCanon; 9248 DeducedDecl = D; 9249 } else if (DeducedCanon != UCanon) { 9250 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9251 diag::err_auto_different_deductions) 9252 << (AT->isDecltypeAuto() ? 1 : 0) 9253 << Deduced << DeducedDecl->getDeclName() 9254 << U << D->getDeclName() 9255 << DeducedDecl->getInit()->getSourceRange() 9256 << D->getInit()->getSourceRange(); 9257 D->setInvalidDecl(); 9258 break; 9259 } 9260 } 9261 } 9262 } 9263 } 9264 9265 ActOnDocumentableDecls(Group); 9266 9267 return DeclGroupPtrTy::make( 9268 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9269 } 9270 9271 void Sema::ActOnDocumentableDecl(Decl *D) { 9272 ActOnDocumentableDecls(D); 9273 } 9274 9275 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9276 // Don't parse the comment if Doxygen diagnostics are ignored. 9277 if (Group.empty() || !Group[0]) 9278 return; 9279 9280 if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found, 9281 Group[0]->getLocation()) 9282 == DiagnosticsEngine::Ignored) 9283 return; 9284 9285 if (Group.size() >= 2) { 9286 // This is a decl group. Normally it will contain only declarations 9287 // produced from declarator list. But in case we have any definitions or 9288 // additional declaration references: 9289 // 'typedef struct S {} S;' 9290 // 'typedef struct S *S;' 9291 // 'struct S *pS;' 9292 // FinalizeDeclaratorGroup adds these as separate declarations. 9293 Decl *MaybeTagDecl = Group[0]; 9294 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9295 Group = Group.slice(1); 9296 } 9297 } 9298 9299 // See if there are any new comments that are not attached to a decl. 9300 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9301 if (!Comments.empty() && 9302 !Comments.back()->isAttached()) { 9303 // There is at least one comment that not attached to a decl. 9304 // Maybe it should be attached to one of these decls? 9305 // 9306 // Note that this way we pick up not only comments that precede the 9307 // declaration, but also comments that *follow* the declaration -- thanks to 9308 // the lookahead in the lexer: we've consumed the semicolon and looked 9309 // ahead through comments. 9310 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9311 Context.getCommentForDecl(Group[i], &PP); 9312 } 9313 } 9314 9315 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9316 /// to introduce parameters into function prototype scope. 9317 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9318 const DeclSpec &DS = D.getDeclSpec(); 9319 9320 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9321 9322 // C++03 [dcl.stc]p2 also permits 'auto'. 9323 VarDecl::StorageClass StorageClass = SC_None; 9324 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9325 StorageClass = SC_Register; 9326 } else if (getLangOpts().CPlusPlus && 9327 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9328 StorageClass = SC_Auto; 9329 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9330 Diag(DS.getStorageClassSpecLoc(), 9331 diag::err_invalid_storage_class_in_func_decl); 9332 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9333 } 9334 9335 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9336 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9337 << DeclSpec::getSpecifierName(TSCS); 9338 if (DS.isConstexprSpecified()) 9339 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9340 << 0; 9341 9342 DiagnoseFunctionSpecifiers(DS); 9343 9344 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9345 QualType parmDeclType = TInfo->getType(); 9346 9347 if (getLangOpts().CPlusPlus) { 9348 // Check that there are no default arguments inside the type of this 9349 // parameter. 9350 CheckExtraCXXDefaultArguments(D); 9351 9352 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9353 if (D.getCXXScopeSpec().isSet()) { 9354 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9355 << D.getCXXScopeSpec().getRange(); 9356 D.getCXXScopeSpec().clear(); 9357 } 9358 } 9359 9360 // Ensure we have a valid name 9361 IdentifierInfo *II = nullptr; 9362 if (D.hasName()) { 9363 II = D.getIdentifier(); 9364 if (!II) { 9365 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9366 << GetNameForDeclarator(D).getName(); 9367 D.setInvalidType(true); 9368 } 9369 } 9370 9371 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9372 if (II) { 9373 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9374 ForRedeclaration); 9375 LookupName(R, S); 9376 if (R.isSingleResult()) { 9377 NamedDecl *PrevDecl = R.getFoundDecl(); 9378 if (PrevDecl->isTemplateParameter()) { 9379 // Maybe we will complain about the shadowed template parameter. 9380 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9381 // Just pretend that we didn't see the previous declaration. 9382 PrevDecl = nullptr; 9383 } else if (S->isDeclScope(PrevDecl)) { 9384 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9385 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9386 9387 // Recover by removing the name 9388 II = nullptr; 9389 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9390 D.setInvalidType(true); 9391 } 9392 } 9393 } 9394 9395 // Temporarily put parameter variables in the translation unit, not 9396 // the enclosing context. This prevents them from accidentally 9397 // looking like class members in C++. 9398 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9399 D.getLocStart(), 9400 D.getIdentifierLoc(), II, 9401 parmDeclType, TInfo, 9402 StorageClass); 9403 9404 if (D.isInvalidType()) 9405 New->setInvalidDecl(); 9406 9407 assert(S->isFunctionPrototypeScope()); 9408 assert(S->getFunctionPrototypeDepth() >= 1); 9409 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9410 S->getNextFunctionPrototypeIndex()); 9411 9412 // Add the parameter declaration into this scope. 9413 S->AddDecl(New); 9414 if (II) 9415 IdResolver.AddDecl(New); 9416 9417 ProcessDeclAttributes(S, New, D); 9418 9419 if (D.getDeclSpec().isModulePrivateSpecified()) 9420 Diag(New->getLocation(), diag::err_module_private_local) 9421 << 1 << New->getDeclName() 9422 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9423 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9424 9425 if (New->hasAttr<BlocksAttr>()) { 9426 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9427 } 9428 return New; 9429 } 9430 9431 /// \brief Synthesizes a variable for a parameter arising from a 9432 /// typedef. 9433 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9434 SourceLocation Loc, 9435 QualType T) { 9436 /* FIXME: setting StartLoc == Loc. 9437 Would it be worth to modify callers so as to provide proper source 9438 location for the unnamed parameters, embedding the parameter's type? */ 9439 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9440 T, Context.getTrivialTypeSourceInfo(T, Loc), 9441 SC_None, nullptr); 9442 Param->setImplicit(); 9443 return Param; 9444 } 9445 9446 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9447 ParmVarDecl * const *ParamEnd) { 9448 // Don't diagnose unused-parameter errors in template instantiations; we 9449 // will already have done so in the template itself. 9450 if (!ActiveTemplateInstantiations.empty()) 9451 return; 9452 9453 for (; Param != ParamEnd; ++Param) { 9454 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9455 !(*Param)->hasAttr<UnusedAttr>()) { 9456 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9457 << (*Param)->getDeclName(); 9458 } 9459 } 9460 } 9461 9462 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9463 ParmVarDecl * const *ParamEnd, 9464 QualType ReturnTy, 9465 NamedDecl *D) { 9466 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9467 return; 9468 9469 // Warn if the return value is pass-by-value and larger than the specified 9470 // threshold. 9471 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9472 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9473 if (Size > LangOpts.NumLargeByValueCopy) 9474 Diag(D->getLocation(), diag::warn_return_value_size) 9475 << D->getDeclName() << Size; 9476 } 9477 9478 // Warn if any parameter is pass-by-value and larger than the specified 9479 // threshold. 9480 for (; Param != ParamEnd; ++Param) { 9481 QualType T = (*Param)->getType(); 9482 if (T->isDependentType() || !T.isPODType(Context)) 9483 continue; 9484 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9485 if (Size > LangOpts.NumLargeByValueCopy) 9486 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9487 << (*Param)->getDeclName() << Size; 9488 } 9489 } 9490 9491 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9492 SourceLocation NameLoc, IdentifierInfo *Name, 9493 QualType T, TypeSourceInfo *TSInfo, 9494 VarDecl::StorageClass StorageClass) { 9495 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9496 if (getLangOpts().ObjCAutoRefCount && 9497 T.getObjCLifetime() == Qualifiers::OCL_None && 9498 T->isObjCLifetimeType()) { 9499 9500 Qualifiers::ObjCLifetime lifetime; 9501 9502 // Special cases for arrays: 9503 // - if it's const, use __unsafe_unretained 9504 // - otherwise, it's an error 9505 if (T->isArrayType()) { 9506 if (!T.isConstQualified()) { 9507 DelayedDiagnostics.add( 9508 sema::DelayedDiagnostic::makeForbiddenType( 9509 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9510 } 9511 lifetime = Qualifiers::OCL_ExplicitNone; 9512 } else { 9513 lifetime = T->getObjCARCImplicitLifetime(); 9514 } 9515 T = Context.getLifetimeQualifiedType(T, lifetime); 9516 } 9517 9518 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9519 Context.getAdjustedParameterType(T), 9520 TSInfo, 9521 StorageClass, nullptr); 9522 9523 // Parameters can not be abstract class types. 9524 // For record types, this is done by the AbstractClassUsageDiagnoser once 9525 // the class has been completely parsed. 9526 if (!CurContext->isRecord() && 9527 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9528 AbstractParamType)) 9529 New->setInvalidDecl(); 9530 9531 // Parameter declarators cannot be interface types. All ObjC objects are 9532 // passed by reference. 9533 if (T->isObjCObjectType()) { 9534 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9535 Diag(NameLoc, 9536 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9537 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9538 T = Context.getObjCObjectPointerType(T); 9539 New->setType(T); 9540 } 9541 9542 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9543 // duration shall not be qualified by an address-space qualifier." 9544 // Since all parameters have automatic store duration, they can not have 9545 // an address space. 9546 if (T.getAddressSpace() != 0) { 9547 // OpenCL allows function arguments declared to be an array of a type 9548 // to be qualified with an address space. 9549 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9550 Diag(NameLoc, diag::err_arg_with_address_space); 9551 New->setInvalidDecl(); 9552 } 9553 } 9554 9555 return New; 9556 } 9557 9558 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9559 SourceLocation LocAfterDecls) { 9560 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9561 9562 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9563 // for a K&R function. 9564 if (!FTI.hasPrototype) { 9565 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 9566 --i; 9567 if (FTI.Params[i].Param == nullptr) { 9568 SmallString<256> Code; 9569 llvm::raw_svector_ostream(Code) 9570 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 9571 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 9572 << FTI.Params[i].Ident 9573 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 9574 9575 // Implicitly declare the argument as type 'int' for lack of a better 9576 // type. 9577 AttributeFactory attrs; 9578 DeclSpec DS(attrs); 9579 const char* PrevSpec; // unused 9580 unsigned DiagID; // unused 9581 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 9582 DiagID, Context.getPrintingPolicy()); 9583 // Use the identifier location for the type source range. 9584 DS.SetRangeStart(FTI.Params[i].IdentLoc); 9585 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 9586 Declarator ParamD(DS, Declarator::KNRTypeListContext); 9587 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 9588 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 9589 } 9590 } 9591 } 9592 } 9593 9594 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 9595 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 9596 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 9597 Scope *ParentScope = FnBodyScope->getParent(); 9598 9599 D.setFunctionDefinitionKind(FDK_Definition); 9600 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 9601 return ActOnStartOfFunctionDef(FnBodyScope, DP); 9602 } 9603 9604 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 9605 Consumer.HandleInlineMethodDefinition(D); 9606 } 9607 9608 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 9609 const FunctionDecl*& PossibleZeroParamPrototype) { 9610 // Don't warn about invalid declarations. 9611 if (FD->isInvalidDecl()) 9612 return false; 9613 9614 // Or declarations that aren't global. 9615 if (!FD->isGlobal()) 9616 return false; 9617 9618 // Don't warn about C++ member functions. 9619 if (isa<CXXMethodDecl>(FD)) 9620 return false; 9621 9622 // Don't warn about 'main'. 9623 if (FD->isMain()) 9624 return false; 9625 9626 // Don't warn about inline functions. 9627 if (FD->isInlined()) 9628 return false; 9629 9630 // Don't warn about function templates. 9631 if (FD->getDescribedFunctionTemplate()) 9632 return false; 9633 9634 // Don't warn about function template specializations. 9635 if (FD->isFunctionTemplateSpecialization()) 9636 return false; 9637 9638 // Don't warn for OpenCL kernels. 9639 if (FD->hasAttr<OpenCLKernelAttr>()) 9640 return false; 9641 9642 bool MissingPrototype = true; 9643 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 9644 Prev; Prev = Prev->getPreviousDecl()) { 9645 // Ignore any declarations that occur in function or method 9646 // scope, because they aren't visible from the header. 9647 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 9648 continue; 9649 9650 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 9651 if (FD->getNumParams() == 0) 9652 PossibleZeroParamPrototype = Prev; 9653 break; 9654 } 9655 9656 return MissingPrototype; 9657 } 9658 9659 void 9660 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 9661 const FunctionDecl *EffectiveDefinition) { 9662 // Don't complain if we're in GNU89 mode and the previous definition 9663 // was an extern inline function. 9664 const FunctionDecl *Definition = EffectiveDefinition; 9665 if (!Definition) 9666 if (!FD->isDefined(Definition)) 9667 return; 9668 9669 if (canRedefineFunction(Definition, getLangOpts())) 9670 return; 9671 9672 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 9673 Definition->getStorageClass() == SC_Extern) 9674 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 9675 << FD->getDeclName() << getLangOpts().CPlusPlus; 9676 else 9677 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 9678 9679 Diag(Definition->getLocation(), diag::note_previous_definition); 9680 FD->setInvalidDecl(); 9681 } 9682 9683 9684 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 9685 Sema &S) { 9686 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 9687 9688 LambdaScopeInfo *LSI = S.PushLambdaScope(); 9689 LSI->CallOperator = CallOperator; 9690 LSI->Lambda = LambdaClass; 9691 LSI->ReturnType = CallOperator->getReturnType(); 9692 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 9693 9694 if (LCD == LCD_None) 9695 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 9696 else if (LCD == LCD_ByCopy) 9697 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 9698 else if (LCD == LCD_ByRef) 9699 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 9700 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 9701 9702 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 9703 LSI->Mutable = !CallOperator->isConst(); 9704 9705 // Add the captures to the LSI so they can be noted as already 9706 // captured within tryCaptureVar. 9707 for (const auto &C : LambdaClass->captures()) { 9708 if (C.capturesVariable()) { 9709 VarDecl *VD = C.getCapturedVar(); 9710 if (VD->isInitCapture()) 9711 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 9712 QualType CaptureType = VD->getType(); 9713 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 9714 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 9715 /*RefersToEnclosingLocal*/true, C.getLocation(), 9716 /*EllipsisLoc*/C.isPackExpansion() 9717 ? C.getEllipsisLoc() : SourceLocation(), 9718 CaptureType, /*Expr*/ nullptr); 9719 9720 } else if (C.capturesThis()) { 9721 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 9722 S.getCurrentThisType(), /*Expr*/ nullptr); 9723 } 9724 } 9725 } 9726 9727 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 9728 // Clear the last template instantiation error context. 9729 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 9730 9731 if (!D) 9732 return D; 9733 FunctionDecl *FD = nullptr; 9734 9735 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 9736 FD = FunTmpl->getTemplatedDecl(); 9737 else 9738 FD = cast<FunctionDecl>(D); 9739 // If we are instantiating a generic lambda call operator, push 9740 // a LambdaScopeInfo onto the function stack. But use the information 9741 // that's already been calculated (ActOnLambdaExpr) to prime the current 9742 // LambdaScopeInfo. 9743 // When the template operator is being specialized, the LambdaScopeInfo, 9744 // has to be properly restored so that tryCaptureVariable doesn't try 9745 // and capture any new variables. In addition when calculating potential 9746 // captures during transformation of nested lambdas, it is necessary to 9747 // have the LSI properly restored. 9748 if (isGenericLambdaCallOperatorSpecialization(FD)) { 9749 assert(ActiveTemplateInstantiations.size() && 9750 "There should be an active template instantiation on the stack " 9751 "when instantiating a generic lambda!"); 9752 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 9753 } 9754 else 9755 // Enter a new function scope 9756 PushFunctionScope(); 9757 9758 // See if this is a redefinition. 9759 if (!FD->isLateTemplateParsed()) 9760 CheckForFunctionRedefinition(FD); 9761 9762 // Builtin functions cannot be defined. 9763 if (unsigned BuiltinID = FD->getBuiltinID()) { 9764 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 9765 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 9766 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 9767 FD->setInvalidDecl(); 9768 } 9769 } 9770 9771 // The return type of a function definition must be complete 9772 // (C99 6.9.1p3, C++ [dcl.fct]p6). 9773 QualType ResultType = FD->getReturnType(); 9774 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 9775 !FD->isInvalidDecl() && 9776 RequireCompleteType(FD->getLocation(), ResultType, 9777 diag::err_func_def_incomplete_result)) 9778 FD->setInvalidDecl(); 9779 9780 // GNU warning -Wmissing-prototypes: 9781 // Warn if a global function is defined without a previous 9782 // prototype declaration. This warning is issued even if the 9783 // definition itself provides a prototype. The aim is to detect 9784 // global functions that fail to be declared in header files. 9785 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 9786 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 9787 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 9788 9789 if (PossibleZeroParamPrototype) { 9790 // We found a declaration that is not a prototype, 9791 // but that could be a zero-parameter prototype 9792 if (TypeSourceInfo *TI = 9793 PossibleZeroParamPrototype->getTypeSourceInfo()) { 9794 TypeLoc TL = TI->getTypeLoc(); 9795 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 9796 Diag(PossibleZeroParamPrototype->getLocation(), 9797 diag::note_declaration_not_a_prototype) 9798 << PossibleZeroParamPrototype 9799 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 9800 } 9801 } 9802 } 9803 9804 if (FnBodyScope) 9805 PushDeclContext(FnBodyScope, FD); 9806 9807 // Check the validity of our function parameters 9808 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 9809 /*CheckParameterNames=*/true); 9810 9811 // Introduce our parameters into the function scope 9812 for (auto Param : FD->params()) { 9813 Param->setOwningFunction(FD); 9814 9815 // If this has an identifier, add it to the scope stack. 9816 if (Param->getIdentifier() && FnBodyScope) { 9817 CheckShadow(FnBodyScope, Param); 9818 9819 PushOnScopeChains(Param, FnBodyScope); 9820 } 9821 } 9822 9823 // If we had any tags defined in the function prototype, 9824 // introduce them into the function scope. 9825 if (FnBodyScope) { 9826 for (ArrayRef<NamedDecl *>::iterator 9827 I = FD->getDeclsInPrototypeScope().begin(), 9828 E = FD->getDeclsInPrototypeScope().end(); 9829 I != E; ++I) { 9830 NamedDecl *D = *I; 9831 9832 // Some of these decls (like enums) may have been pinned to the translation unit 9833 // for lack of a real context earlier. If so, remove from the translation unit 9834 // and reattach to the current context. 9835 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 9836 // Is the decl actually in the context? 9837 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 9838 if (DI == D) { 9839 Context.getTranslationUnitDecl()->removeDecl(D); 9840 break; 9841 } 9842 } 9843 // Either way, reassign the lexical decl context to our FunctionDecl. 9844 D->setLexicalDeclContext(CurContext); 9845 } 9846 9847 // If the decl has a non-null name, make accessible in the current scope. 9848 if (!D->getName().empty()) 9849 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 9850 9851 // Similarly, dive into enums and fish their constants out, making them 9852 // accessible in this scope. 9853 if (auto *ED = dyn_cast<EnumDecl>(D)) { 9854 for (auto *EI : ED->enumerators()) 9855 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 9856 } 9857 } 9858 } 9859 9860 // Ensure that the function's exception specification is instantiated. 9861 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 9862 ResolveExceptionSpec(D->getLocation(), FPT); 9863 9864 // dllimport cannot be applied to non-inline function definitions. 9865 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 9866 !FD->isTemplateInstantiation()) { 9867 assert(!FD->hasAttr<DLLExportAttr>()); 9868 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 9869 FD->setInvalidDecl(); 9870 return D; 9871 } 9872 // We want to attach documentation to original Decl (which might be 9873 // a function template). 9874 ActOnDocumentableDecl(D); 9875 if (getCurLexicalContext()->isObjCContainer() && 9876 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 9877 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 9878 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 9879 9880 return D; 9881 } 9882 9883 /// \brief Given the set of return statements within a function body, 9884 /// compute the variables that are subject to the named return value 9885 /// optimization. 9886 /// 9887 /// Each of the variables that is subject to the named return value 9888 /// optimization will be marked as NRVO variables in the AST, and any 9889 /// return statement that has a marked NRVO variable as its NRVO candidate can 9890 /// use the named return value optimization. 9891 /// 9892 /// This function applies a very simplistic algorithm for NRVO: if every return 9893 /// statement in the scope of a variable has the same NRVO candidate, that 9894 /// candidate is an NRVO variable. 9895 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 9896 ReturnStmt **Returns = Scope->Returns.data(); 9897 9898 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 9899 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 9900 if (!NRVOCandidate->isNRVOVariable()) 9901 Returns[I]->setNRVOCandidate(nullptr); 9902 } 9903 } 9904 } 9905 9906 bool Sema::canDelayFunctionBody(const Declarator &D) { 9907 // We can't delay parsing the body of a constexpr function template (yet). 9908 if (D.getDeclSpec().isConstexprSpecified()) 9909 return false; 9910 9911 // We can't delay parsing the body of a function template with a deduced 9912 // return type (yet). 9913 if (D.getDeclSpec().containsPlaceholderType()) { 9914 // If the placeholder introduces a non-deduced trailing return type, 9915 // we can still delay parsing it. 9916 if (D.getNumTypeObjects()) { 9917 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 9918 if (Outer.Kind == DeclaratorChunk::Function && 9919 Outer.Fun.hasTrailingReturnType()) { 9920 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 9921 return Ty.isNull() || !Ty->isUndeducedType(); 9922 } 9923 } 9924 return false; 9925 } 9926 9927 return true; 9928 } 9929 9930 bool Sema::canSkipFunctionBody(Decl *D) { 9931 // We cannot skip the body of a function (or function template) which is 9932 // constexpr, since we may need to evaluate its body in order to parse the 9933 // rest of the file. 9934 // We cannot skip the body of a function with an undeduced return type, 9935 // because any callers of that function need to know the type. 9936 if (const FunctionDecl *FD = D->getAsFunction()) 9937 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 9938 return false; 9939 return Consumer.shouldSkipFunctionBody(D); 9940 } 9941 9942 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 9943 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 9944 FD->setHasSkippedBody(); 9945 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 9946 MD->setHasSkippedBody(); 9947 return ActOnFinishFunctionBody(Decl, nullptr); 9948 } 9949 9950 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 9951 return ActOnFinishFunctionBody(D, BodyArg, false); 9952 } 9953 9954 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 9955 bool IsInstantiation) { 9956 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 9957 9958 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 9959 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 9960 9961 if (FD) { 9962 FD->setBody(Body); 9963 9964 if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body && 9965 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 9966 // If the function has a deduced result type but contains no 'return' 9967 // statements, the result type as written must be exactly 'auto', and 9968 // the deduced result type is 'void'. 9969 if (!FD->getReturnType()->getAs<AutoType>()) { 9970 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 9971 << FD->getReturnType(); 9972 FD->setInvalidDecl(); 9973 } else { 9974 // Substitute 'void' for the 'auto' in the type. 9975 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 9976 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 9977 Context.adjustDeducedFunctionResultType( 9978 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 9979 } 9980 } 9981 9982 // The only way to be included in UndefinedButUsed is if there is an 9983 // ODR use before the definition. Avoid the expensive map lookup if this 9984 // is the first declaration. 9985 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 9986 if (!FD->isExternallyVisible()) 9987 UndefinedButUsed.erase(FD); 9988 else if (FD->isInlined() && 9989 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 9990 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 9991 UndefinedButUsed.erase(FD); 9992 } 9993 9994 // If the function implicitly returns zero (like 'main') or is naked, 9995 // don't complain about missing return statements. 9996 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 9997 WP.disableCheckFallThrough(); 9998 9999 // MSVC permits the use of pure specifier (=0) on function definition, 10000 // defined at class scope, warn about this non-standard construct. 10001 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10002 Diag(FD->getLocation(), diag::warn_pure_function_definition); 10003 10004 if (!FD->isInvalidDecl()) { 10005 // Don't diagnose unused parameters of defaulted or deleted functions. 10006 if (Body) 10007 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10008 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10009 FD->getReturnType(), FD); 10010 10011 // If this is a constructor, we need a vtable. 10012 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10013 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10014 10015 // Try to apply the named return value optimization. We have to check 10016 // if we can do this here because lambdas keep return statements around 10017 // to deduce an implicit return type. 10018 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10019 !FD->isDependentContext()) 10020 computeNRVO(Body, getCurFunction()); 10021 } 10022 10023 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10024 "Function parsing confused"); 10025 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10026 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10027 MD->setBody(Body); 10028 if (!MD->isInvalidDecl()) { 10029 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10030 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10031 MD->getReturnType(), MD); 10032 10033 if (Body) 10034 computeNRVO(Body, getCurFunction()); 10035 } 10036 if (getCurFunction()->ObjCShouldCallSuper) { 10037 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10038 << MD->getSelector().getAsString(); 10039 getCurFunction()->ObjCShouldCallSuper = false; 10040 } 10041 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10042 const ObjCMethodDecl *InitMethod = nullptr; 10043 bool isDesignated = 10044 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10045 assert(isDesignated && InitMethod); 10046 (void)isDesignated; 10047 10048 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10049 auto IFace = MD->getClassInterface(); 10050 if (!IFace) 10051 return false; 10052 auto SuperD = IFace->getSuperClass(); 10053 if (!SuperD) 10054 return false; 10055 return SuperD->getIdentifier() == 10056 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10057 }; 10058 // Don't issue this warning for unavailable inits or direct subclasses 10059 // of NSObject. 10060 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10061 Diag(MD->getLocation(), 10062 diag::warn_objc_designated_init_missing_super_call); 10063 Diag(InitMethod->getLocation(), 10064 diag::note_objc_designated_init_marked_here); 10065 } 10066 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10067 } 10068 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10069 // Don't issue this warning for unavaialable inits. 10070 if (!MD->isUnavailable()) 10071 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 10072 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10073 } 10074 } else { 10075 return nullptr; 10076 } 10077 10078 assert(!getCurFunction()->ObjCShouldCallSuper && 10079 "This should only be set for ObjC methods, which should have been " 10080 "handled in the block above."); 10081 10082 // Verify and clean out per-function state. 10083 if (Body) { 10084 // C++ constructors that have function-try-blocks can't have return 10085 // statements in the handlers of that block. (C++ [except.handle]p14) 10086 // Verify this. 10087 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10088 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10089 10090 // Verify that gotos and switch cases don't jump into scopes illegally. 10091 if (getCurFunction()->NeedsScopeChecking() && 10092 !PP.isCodeCompletionEnabled()) 10093 DiagnoseInvalidJumps(Body); 10094 10095 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10096 if (!Destructor->getParent()->isDependentType()) 10097 CheckDestructor(Destructor); 10098 10099 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10100 Destructor->getParent()); 10101 } 10102 10103 // If any errors have occurred, clear out any temporaries that may have 10104 // been leftover. This ensures that these temporaries won't be picked up for 10105 // deletion in some later function. 10106 if (getDiagnostics().hasErrorOccurred() || 10107 getDiagnostics().getSuppressAllDiagnostics()) { 10108 DiscardCleanupsInEvaluationContext(); 10109 } 10110 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10111 !isa<FunctionTemplateDecl>(dcl)) { 10112 // Since the body is valid, issue any analysis-based warnings that are 10113 // enabled. 10114 ActivePolicy = &WP; 10115 } 10116 10117 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10118 (!CheckConstexprFunctionDecl(FD) || 10119 !CheckConstexprFunctionBody(FD, Body))) 10120 FD->setInvalidDecl(); 10121 10122 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10123 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10124 assert(MaybeODRUseExprs.empty() && 10125 "Leftover expressions for odr-use checking"); 10126 } 10127 10128 if (!IsInstantiation) 10129 PopDeclContext(); 10130 10131 PopFunctionScopeInfo(ActivePolicy, dcl); 10132 // If any errors have occurred, clear out any temporaries that may have 10133 // been leftover. This ensures that these temporaries won't be picked up for 10134 // deletion in some later function. 10135 if (getDiagnostics().hasErrorOccurred()) { 10136 DiscardCleanupsInEvaluationContext(); 10137 } 10138 10139 return dcl; 10140 } 10141 10142 10143 /// When we finish delayed parsing of an attribute, we must attach it to the 10144 /// relevant Decl. 10145 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10146 ParsedAttributes &Attrs) { 10147 // Always attach attributes to the underlying decl. 10148 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10149 D = TD->getTemplatedDecl(); 10150 ProcessDeclAttributeList(S, D, Attrs.getList()); 10151 10152 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10153 if (Method->isStatic()) 10154 checkThisInStaticMemberFunctionAttributes(Method); 10155 } 10156 10157 10158 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10159 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10160 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10161 IdentifierInfo &II, Scope *S) { 10162 // Before we produce a declaration for an implicitly defined 10163 // function, see whether there was a locally-scoped declaration of 10164 // this name as a function or variable. If so, use that 10165 // (non-visible) declaration, and complain about it. 10166 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10167 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10168 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10169 return ExternCPrev; 10170 } 10171 10172 // Extension in C99. Legal in C90, but warn about it. 10173 unsigned diag_id; 10174 if (II.getName().startswith("__builtin_")) 10175 diag_id = diag::warn_builtin_unknown; 10176 else if (getLangOpts().C99) 10177 diag_id = diag::ext_implicit_function_decl; 10178 else 10179 diag_id = diag::warn_implicit_function_decl; 10180 Diag(Loc, diag_id) << &II; 10181 10182 // Because typo correction is expensive, only do it if the implicit 10183 // function declaration is going to be treated as an error. 10184 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10185 TypoCorrection Corrected; 10186 DeclFilterCCC<FunctionDecl> Validator; 10187 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10188 LookupOrdinaryName, S, nullptr, Validator, 10189 CTK_NonError))) 10190 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10191 /*ErrorRecovery*/false); 10192 } 10193 10194 // Set a Declarator for the implicit definition: int foo(); 10195 const char *Dummy; 10196 AttributeFactory attrFactory; 10197 DeclSpec DS(attrFactory); 10198 unsigned DiagID; 10199 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10200 Context.getPrintingPolicy()); 10201 (void)Error; // Silence warning. 10202 assert(!Error && "Error setting up implicit decl!"); 10203 SourceLocation NoLoc; 10204 Declarator D(DS, Declarator::BlockContext); 10205 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10206 /*IsAmbiguous=*/false, 10207 /*LParenLoc=*/NoLoc, 10208 /*Params=*/nullptr, 10209 /*NumParams=*/0, 10210 /*EllipsisLoc=*/NoLoc, 10211 /*RParenLoc=*/NoLoc, 10212 /*TypeQuals=*/0, 10213 /*RefQualifierIsLvalueRef=*/true, 10214 /*RefQualifierLoc=*/NoLoc, 10215 /*ConstQualifierLoc=*/NoLoc, 10216 /*VolatileQualifierLoc=*/NoLoc, 10217 /*MutableLoc=*/NoLoc, 10218 EST_None, 10219 /*ESpecLoc=*/NoLoc, 10220 /*Exceptions=*/nullptr, 10221 /*ExceptionRanges=*/nullptr, 10222 /*NumExceptions=*/0, 10223 /*NoexceptExpr=*/nullptr, 10224 Loc, Loc, D), 10225 DS.getAttributes(), 10226 SourceLocation()); 10227 D.SetIdentifier(&II, Loc); 10228 10229 // Insert this function into translation-unit scope. 10230 10231 DeclContext *PrevDC = CurContext; 10232 CurContext = Context.getTranslationUnitDecl(); 10233 10234 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10235 FD->setImplicit(); 10236 10237 CurContext = PrevDC; 10238 10239 AddKnownFunctionAttributes(FD); 10240 10241 return FD; 10242 } 10243 10244 /// \brief Adds any function attributes that we know a priori based on 10245 /// the declaration of this function. 10246 /// 10247 /// These attributes can apply both to implicitly-declared builtins 10248 /// (like __builtin___printf_chk) or to library-declared functions 10249 /// like NSLog or printf. 10250 /// 10251 /// We need to check for duplicate attributes both here and where user-written 10252 /// attributes are applied to declarations. 10253 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10254 if (FD->isInvalidDecl()) 10255 return; 10256 10257 // If this is a built-in function, map its builtin attributes to 10258 // actual attributes. 10259 if (unsigned BuiltinID = FD->getBuiltinID()) { 10260 // Handle printf-formatting attributes. 10261 unsigned FormatIdx; 10262 bool HasVAListArg; 10263 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10264 if (!FD->hasAttr<FormatAttr>()) { 10265 const char *fmt = "printf"; 10266 unsigned int NumParams = FD->getNumParams(); 10267 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10268 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10269 fmt = "NSString"; 10270 FD->addAttr(FormatAttr::CreateImplicit(Context, 10271 &Context.Idents.get(fmt), 10272 FormatIdx+1, 10273 HasVAListArg ? 0 : FormatIdx+2, 10274 FD->getLocation())); 10275 } 10276 } 10277 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10278 HasVAListArg)) { 10279 if (!FD->hasAttr<FormatAttr>()) 10280 FD->addAttr(FormatAttr::CreateImplicit(Context, 10281 &Context.Idents.get("scanf"), 10282 FormatIdx+1, 10283 HasVAListArg ? 0 : FormatIdx+2, 10284 FD->getLocation())); 10285 } 10286 10287 // Mark const if we don't care about errno and that is the only 10288 // thing preventing the function from being const. This allows 10289 // IRgen to use LLVM intrinsics for such functions. 10290 if (!getLangOpts().MathErrno && 10291 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10292 if (!FD->hasAttr<ConstAttr>()) 10293 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10294 } 10295 10296 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10297 !FD->hasAttr<ReturnsTwiceAttr>()) 10298 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10299 FD->getLocation())); 10300 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10301 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10302 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10303 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10304 } 10305 10306 IdentifierInfo *Name = FD->getIdentifier(); 10307 if (!Name) 10308 return; 10309 if ((!getLangOpts().CPlusPlus && 10310 FD->getDeclContext()->isTranslationUnit()) || 10311 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10312 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10313 LinkageSpecDecl::lang_c)) { 10314 // Okay: this could be a libc/libm/Objective-C function we know 10315 // about. 10316 } else 10317 return; 10318 10319 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10320 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10321 // target-specific builtins, perhaps? 10322 if (!FD->hasAttr<FormatAttr>()) 10323 FD->addAttr(FormatAttr::CreateImplicit(Context, 10324 &Context.Idents.get("printf"), 2, 10325 Name->isStr("vasprintf") ? 0 : 3, 10326 FD->getLocation())); 10327 } 10328 10329 if (Name->isStr("__CFStringMakeConstantString")) { 10330 // We already have a __builtin___CFStringMakeConstantString, 10331 // but builds that use -fno-constant-cfstrings don't go through that. 10332 if (!FD->hasAttr<FormatArgAttr>()) 10333 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10334 FD->getLocation())); 10335 } 10336 } 10337 10338 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10339 TypeSourceInfo *TInfo) { 10340 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10341 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10342 10343 if (!TInfo) { 10344 assert(D.isInvalidType() && "no declarator info for valid type"); 10345 TInfo = Context.getTrivialTypeSourceInfo(T); 10346 } 10347 10348 // Scope manipulation handled by caller. 10349 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10350 D.getLocStart(), 10351 D.getIdentifierLoc(), 10352 D.getIdentifier(), 10353 TInfo); 10354 10355 // Bail out immediately if we have an invalid declaration. 10356 if (D.isInvalidType()) { 10357 NewTD->setInvalidDecl(); 10358 return NewTD; 10359 } 10360 10361 if (D.getDeclSpec().isModulePrivateSpecified()) { 10362 if (CurContext->isFunctionOrMethod()) 10363 Diag(NewTD->getLocation(), diag::err_module_private_local) 10364 << 2 << NewTD->getDeclName() 10365 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10366 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10367 else 10368 NewTD->setModulePrivate(); 10369 } 10370 10371 // C++ [dcl.typedef]p8: 10372 // If the typedef declaration defines an unnamed class (or 10373 // enum), the first typedef-name declared by the declaration 10374 // to be that class type (or enum type) is used to denote the 10375 // class type (or enum type) for linkage purposes only. 10376 // We need to check whether the type was declared in the declaration. 10377 switch (D.getDeclSpec().getTypeSpecType()) { 10378 case TST_enum: 10379 case TST_struct: 10380 case TST_interface: 10381 case TST_union: 10382 case TST_class: { 10383 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10384 10385 // Do nothing if the tag is not anonymous or already has an 10386 // associated typedef (from an earlier typedef in this decl group). 10387 if (tagFromDeclSpec->getIdentifier()) break; 10388 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10389 10390 // A well-formed anonymous tag must always be a TUK_Definition. 10391 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10392 10393 // The type must match the tag exactly; no qualifiers allowed. 10394 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10395 break; 10396 10397 // If we've already computed linkage for the anonymous tag, then 10398 // adding a typedef name for the anonymous decl can change that 10399 // linkage, which might be a serious problem. Diagnose this as 10400 // unsupported and ignore the typedef name. TODO: we should 10401 // pursue this as a language defect and establish a formal rule 10402 // for how to handle it. 10403 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10404 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10405 10406 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10407 tagLoc = getLocForEndOfToken(tagLoc); 10408 10409 llvm::SmallString<40> textToInsert; 10410 textToInsert += ' '; 10411 textToInsert += D.getIdentifier()->getName(); 10412 Diag(tagLoc, diag::note_typedef_changes_linkage) 10413 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10414 break; 10415 } 10416 10417 // Otherwise, set this is the anon-decl typedef for the tag. 10418 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10419 break; 10420 } 10421 10422 default: 10423 break; 10424 } 10425 10426 return NewTD; 10427 } 10428 10429 10430 /// \brief Check that this is a valid underlying type for an enum declaration. 10431 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10432 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10433 QualType T = TI->getType(); 10434 10435 if (T->isDependentType()) 10436 return false; 10437 10438 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10439 if (BT->isInteger()) 10440 return false; 10441 10442 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10443 return true; 10444 } 10445 10446 /// Check whether this is a valid redeclaration of a previous enumeration. 10447 /// \return true if the redeclaration was invalid. 10448 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10449 QualType EnumUnderlyingTy, 10450 const EnumDecl *Prev) { 10451 bool IsFixed = !EnumUnderlyingTy.isNull(); 10452 10453 if (IsScoped != Prev->isScoped()) { 10454 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10455 << Prev->isScoped(); 10456 Diag(Prev->getLocation(), diag::note_previous_declaration); 10457 return true; 10458 } 10459 10460 if (IsFixed && Prev->isFixed()) { 10461 if (!EnumUnderlyingTy->isDependentType() && 10462 !Prev->getIntegerType()->isDependentType() && 10463 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10464 Prev->getIntegerType())) { 10465 // TODO: Highlight the underlying type of the redeclaration. 10466 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10467 << EnumUnderlyingTy << Prev->getIntegerType(); 10468 Diag(Prev->getLocation(), diag::note_previous_declaration) 10469 << Prev->getIntegerTypeRange(); 10470 return true; 10471 } 10472 } else if (IsFixed != Prev->isFixed()) { 10473 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10474 << Prev->isFixed(); 10475 Diag(Prev->getLocation(), diag::note_previous_declaration); 10476 return true; 10477 } 10478 10479 return false; 10480 } 10481 10482 /// \brief Get diagnostic %select index for tag kind for 10483 /// redeclaration diagnostic message. 10484 /// WARNING: Indexes apply to particular diagnostics only! 10485 /// 10486 /// \returns diagnostic %select index. 10487 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10488 switch (Tag) { 10489 case TTK_Struct: return 0; 10490 case TTK_Interface: return 1; 10491 case TTK_Class: return 2; 10492 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10493 } 10494 } 10495 10496 /// \brief Determine if tag kind is a class-key compatible with 10497 /// class for redeclaration (class, struct, or __interface). 10498 /// 10499 /// \returns true iff the tag kind is compatible. 10500 static bool isClassCompatTagKind(TagTypeKind Tag) 10501 { 10502 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10503 } 10504 10505 /// \brief Determine whether a tag with a given kind is acceptable 10506 /// as a redeclaration of the given tag declaration. 10507 /// 10508 /// \returns true if the new tag kind is acceptable, false otherwise. 10509 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10510 TagTypeKind NewTag, bool isDefinition, 10511 SourceLocation NewTagLoc, 10512 const IdentifierInfo &Name) { 10513 // C++ [dcl.type.elab]p3: 10514 // The class-key or enum keyword present in the 10515 // elaborated-type-specifier shall agree in kind with the 10516 // declaration to which the name in the elaborated-type-specifier 10517 // refers. This rule also applies to the form of 10518 // elaborated-type-specifier that declares a class-name or 10519 // friend class since it can be construed as referring to the 10520 // definition of the class. Thus, in any 10521 // elaborated-type-specifier, the enum keyword shall be used to 10522 // refer to an enumeration (7.2), the union class-key shall be 10523 // used to refer to a union (clause 9), and either the class or 10524 // struct class-key shall be used to refer to a class (clause 9) 10525 // declared using the class or struct class-key. 10526 TagTypeKind OldTag = Previous->getTagKind(); 10527 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10528 if (OldTag == NewTag) 10529 return true; 10530 10531 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10532 // Warn about the struct/class tag mismatch. 10533 bool isTemplate = false; 10534 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10535 isTemplate = Record->getDescribedClassTemplate(); 10536 10537 if (!ActiveTemplateInstantiations.empty()) { 10538 // In a template instantiation, do not offer fix-its for tag mismatches 10539 // since they usually mess up the template instead of fixing the problem. 10540 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10541 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10542 << getRedeclDiagFromTagKind(OldTag); 10543 return true; 10544 } 10545 10546 if (isDefinition) { 10547 // On definitions, check previous tags and issue a fix-it for each 10548 // one that doesn't match the current tag. 10549 if (Previous->getDefinition()) { 10550 // Don't suggest fix-its for redefinitions. 10551 return true; 10552 } 10553 10554 bool previousMismatch = false; 10555 for (auto I : Previous->redecls()) { 10556 if (I->getTagKind() != NewTag) { 10557 if (!previousMismatch) { 10558 previousMismatch = true; 10559 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 10560 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10561 << getRedeclDiagFromTagKind(I->getTagKind()); 10562 } 10563 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 10564 << getRedeclDiagFromTagKind(NewTag) 10565 << FixItHint::CreateReplacement(I->getInnerLocStart(), 10566 TypeWithKeyword::getTagTypeKindName(NewTag)); 10567 } 10568 } 10569 return true; 10570 } 10571 10572 // Check for a previous definition. If current tag and definition 10573 // are same type, do nothing. If no definition, but disagree with 10574 // with previous tag type, give a warning, but no fix-it. 10575 const TagDecl *Redecl = Previous->getDefinition() ? 10576 Previous->getDefinition() : Previous; 10577 if (Redecl->getTagKind() == NewTag) { 10578 return true; 10579 } 10580 10581 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10582 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10583 << getRedeclDiagFromTagKind(OldTag); 10584 Diag(Redecl->getLocation(), diag::note_previous_use); 10585 10586 // If there is a previous definition, suggest a fix-it. 10587 if (Previous->getDefinition()) { 10588 Diag(NewTagLoc, diag::note_struct_class_suggestion) 10589 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 10590 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 10591 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 10592 } 10593 10594 return true; 10595 } 10596 return false; 10597 } 10598 10599 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 10600 /// former case, Name will be non-null. In the later case, Name will be null. 10601 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 10602 /// reference/declaration/definition of a tag. 10603 /// 10604 /// IsTypeSpecifier is true if this is a type-specifier (or 10605 /// trailing-type-specifier) other than one in an alias-declaration. 10606 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10607 SourceLocation KWLoc, CXXScopeSpec &SS, 10608 IdentifierInfo *Name, SourceLocation NameLoc, 10609 AttributeList *Attr, AccessSpecifier AS, 10610 SourceLocation ModulePrivateLoc, 10611 MultiTemplateParamsArg TemplateParameterLists, 10612 bool &OwnedDecl, bool &IsDependent, 10613 SourceLocation ScopedEnumKWLoc, 10614 bool ScopedEnumUsesClassTag, 10615 TypeResult UnderlyingType, 10616 bool IsTypeSpecifier) { 10617 // If this is not a definition, it must have a name. 10618 IdentifierInfo *OrigName = Name; 10619 assert((Name != nullptr || TUK == TUK_Definition) && 10620 "Nameless record must be a definition!"); 10621 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 10622 10623 OwnedDecl = false; 10624 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10625 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 10626 10627 // FIXME: Check explicit specializations more carefully. 10628 bool isExplicitSpecialization = false; 10629 bool Invalid = false; 10630 10631 // We only need to do this matching if we have template parameters 10632 // or a scope specifier, which also conveniently avoids this work 10633 // for non-C++ cases. 10634 if (TemplateParameterLists.size() > 0 || 10635 (SS.isNotEmpty() && TUK != TUK_Reference)) { 10636 if (TemplateParameterList *TemplateParams = 10637 MatchTemplateParametersToScopeSpecifier( 10638 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 10639 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 10640 if (Kind == TTK_Enum) { 10641 Diag(KWLoc, diag::err_enum_template); 10642 return nullptr; 10643 } 10644 10645 if (TemplateParams->size() > 0) { 10646 // This is a declaration or definition of a class template (which may 10647 // be a member of another template). 10648 10649 if (Invalid) 10650 return nullptr; 10651 10652 OwnedDecl = false; 10653 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 10654 SS, Name, NameLoc, Attr, 10655 TemplateParams, AS, 10656 ModulePrivateLoc, 10657 TemplateParameterLists.size()-1, 10658 TemplateParameterLists.data()); 10659 return Result.get(); 10660 } else { 10661 // The "template<>" header is extraneous. 10662 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10663 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10664 isExplicitSpecialization = true; 10665 } 10666 } 10667 } 10668 10669 // Figure out the underlying type if this a enum declaration. We need to do 10670 // this early, because it's needed to detect if this is an incompatible 10671 // redeclaration. 10672 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 10673 10674 if (Kind == TTK_Enum) { 10675 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 10676 // No underlying type explicitly specified, or we failed to parse the 10677 // type, default to int. 10678 EnumUnderlying = Context.IntTy.getTypePtr(); 10679 else if (UnderlyingType.get()) { 10680 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 10681 // integral type; any cv-qualification is ignored. 10682 TypeSourceInfo *TI = nullptr; 10683 GetTypeFromParser(UnderlyingType.get(), &TI); 10684 EnumUnderlying = TI; 10685 10686 if (CheckEnumUnderlyingType(TI)) 10687 // Recover by falling back to int. 10688 EnumUnderlying = Context.IntTy.getTypePtr(); 10689 10690 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 10691 UPPC_FixedUnderlyingType)) 10692 EnumUnderlying = Context.IntTy.getTypePtr(); 10693 10694 } else if (getLangOpts().MSVCCompat) 10695 // Microsoft enums are always of int type. 10696 EnumUnderlying = Context.IntTy.getTypePtr(); 10697 } 10698 10699 DeclContext *SearchDC = CurContext; 10700 DeclContext *DC = CurContext; 10701 bool isStdBadAlloc = false; 10702 10703 RedeclarationKind Redecl = ForRedeclaration; 10704 if (TUK == TUK_Friend || TUK == TUK_Reference) 10705 Redecl = NotForRedeclaration; 10706 10707 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 10708 bool FriendSawTagOutsideEnclosingNamespace = false; 10709 if (Name && SS.isNotEmpty()) { 10710 // We have a nested-name tag ('struct foo::bar'). 10711 10712 // Check for invalid 'foo::'. 10713 if (SS.isInvalid()) { 10714 Name = nullptr; 10715 goto CreateNewDecl; 10716 } 10717 10718 // If this is a friend or a reference to a class in a dependent 10719 // context, don't try to make a decl for it. 10720 if (TUK == TUK_Friend || TUK == TUK_Reference) { 10721 DC = computeDeclContext(SS, false); 10722 if (!DC) { 10723 IsDependent = true; 10724 return nullptr; 10725 } 10726 } else { 10727 DC = computeDeclContext(SS, true); 10728 if (!DC) { 10729 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 10730 << SS.getRange(); 10731 return nullptr; 10732 } 10733 } 10734 10735 if (RequireCompleteDeclContext(SS, DC)) 10736 return nullptr; 10737 10738 SearchDC = DC; 10739 // Look-up name inside 'foo::'. 10740 LookupQualifiedName(Previous, DC); 10741 10742 if (Previous.isAmbiguous()) 10743 return nullptr; 10744 10745 if (Previous.empty()) { 10746 // Name lookup did not find anything. However, if the 10747 // nested-name-specifier refers to the current instantiation, 10748 // and that current instantiation has any dependent base 10749 // classes, we might find something at instantiation time: treat 10750 // this as a dependent elaborated-type-specifier. 10751 // But this only makes any sense for reference-like lookups. 10752 if (Previous.wasNotFoundInCurrentInstantiation() && 10753 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10754 IsDependent = true; 10755 return nullptr; 10756 } 10757 10758 // A tag 'foo::bar' must already exist. 10759 Diag(NameLoc, diag::err_not_tag_in_scope) 10760 << Kind << Name << DC << SS.getRange(); 10761 Name = nullptr; 10762 Invalid = true; 10763 goto CreateNewDecl; 10764 } 10765 } else if (Name) { 10766 // If this is a named struct, check to see if there was a previous forward 10767 // declaration or definition. 10768 // FIXME: We're looking into outer scopes here, even when we 10769 // shouldn't be. Doing so can result in ambiguities that we 10770 // shouldn't be diagnosing. 10771 LookupName(Previous, S); 10772 10773 // When declaring or defining a tag, ignore ambiguities introduced 10774 // by types using'ed into this scope. 10775 if (Previous.isAmbiguous() && 10776 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 10777 LookupResult::Filter F = Previous.makeFilter(); 10778 while (F.hasNext()) { 10779 NamedDecl *ND = F.next(); 10780 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 10781 F.erase(); 10782 } 10783 F.done(); 10784 } 10785 10786 // C++11 [namespace.memdef]p3: 10787 // If the name in a friend declaration is neither qualified nor 10788 // a template-id and the declaration is a function or an 10789 // elaborated-type-specifier, the lookup to determine whether 10790 // the entity has been previously declared shall not consider 10791 // any scopes outside the innermost enclosing namespace. 10792 // 10793 // Does it matter that this should be by scope instead of by 10794 // semantic context? 10795 if (!Previous.empty() && TUK == TUK_Friend) { 10796 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 10797 LookupResult::Filter F = Previous.makeFilter(); 10798 while (F.hasNext()) { 10799 NamedDecl *ND = F.next(); 10800 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 10801 if (DC->isFileContext() && 10802 !EnclosingNS->Encloses(ND->getDeclContext())) { 10803 F.erase(); 10804 FriendSawTagOutsideEnclosingNamespace = true; 10805 } 10806 } 10807 F.done(); 10808 } 10809 10810 // Note: there used to be some attempt at recovery here. 10811 if (Previous.isAmbiguous()) 10812 return nullptr; 10813 10814 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 10815 // FIXME: This makes sure that we ignore the contexts associated 10816 // with C structs, unions, and enums when looking for a matching 10817 // tag declaration or definition. See the similar lookup tweak 10818 // in Sema::LookupName; is there a better way to deal with this? 10819 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 10820 SearchDC = SearchDC->getParent(); 10821 } 10822 } else if (S->isFunctionPrototypeScope()) { 10823 // If this is an enum declaration in function prototype scope, set its 10824 // initial context to the translation unit. 10825 // FIXME: [citation needed] 10826 SearchDC = Context.getTranslationUnitDecl(); 10827 } 10828 10829 if (Previous.isSingleResult() && 10830 Previous.getFoundDecl()->isTemplateParameter()) { 10831 // Maybe we will complain about the shadowed template parameter. 10832 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 10833 // Just pretend that we didn't see the previous declaration. 10834 Previous.clear(); 10835 } 10836 10837 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 10838 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 10839 // This is a declaration of or a reference to "std::bad_alloc". 10840 isStdBadAlloc = true; 10841 10842 if (Previous.empty() && StdBadAlloc) { 10843 // std::bad_alloc has been implicitly declared (but made invisible to 10844 // name lookup). Fill in this implicit declaration as the previous 10845 // declaration, so that the declarations get chained appropriately. 10846 Previous.addDecl(getStdBadAlloc()); 10847 } 10848 } 10849 10850 // If we didn't find a previous declaration, and this is a reference 10851 // (or friend reference), move to the correct scope. In C++, we 10852 // also need to do a redeclaration lookup there, just in case 10853 // there's a shadow friend decl. 10854 if (Name && Previous.empty() && 10855 (TUK == TUK_Reference || TUK == TUK_Friend)) { 10856 if (Invalid) goto CreateNewDecl; 10857 assert(SS.isEmpty()); 10858 10859 if (TUK == TUK_Reference) { 10860 // C++ [basic.scope.pdecl]p5: 10861 // -- for an elaborated-type-specifier of the form 10862 // 10863 // class-key identifier 10864 // 10865 // if the elaborated-type-specifier is used in the 10866 // decl-specifier-seq or parameter-declaration-clause of a 10867 // function defined in namespace scope, the identifier is 10868 // declared as a class-name in the namespace that contains 10869 // the declaration; otherwise, except as a friend 10870 // declaration, the identifier is declared in the smallest 10871 // non-class, non-function-prototype scope that contains the 10872 // declaration. 10873 // 10874 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 10875 // C structs and unions. 10876 // 10877 // It is an error in C++ to declare (rather than define) an enum 10878 // type, including via an elaborated type specifier. We'll 10879 // diagnose that later; for now, declare the enum in the same 10880 // scope as we would have picked for any other tag type. 10881 // 10882 // GNU C also supports this behavior as part of its incomplete 10883 // enum types extension, while GNU C++ does not. 10884 // 10885 // Find the context where we'll be declaring the tag. 10886 // FIXME: We would like to maintain the current DeclContext as the 10887 // lexical context, 10888 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 10889 SearchDC = SearchDC->getParent(); 10890 10891 // Find the scope where we'll be declaring the tag. 10892 while (S->isClassScope() || 10893 (getLangOpts().CPlusPlus && 10894 S->isFunctionPrototypeScope()) || 10895 ((S->getFlags() & Scope::DeclScope) == 0) || 10896 (S->getEntity() && S->getEntity()->isTransparentContext())) 10897 S = S->getParent(); 10898 } else { 10899 assert(TUK == TUK_Friend); 10900 // C++ [namespace.memdef]p3: 10901 // If a friend declaration in a non-local class first declares a 10902 // class or function, the friend class or function is a member of 10903 // the innermost enclosing namespace. 10904 SearchDC = SearchDC->getEnclosingNamespaceContext(); 10905 } 10906 10907 // In C++, we need to do a redeclaration lookup to properly 10908 // diagnose some problems. 10909 if (getLangOpts().CPlusPlus) { 10910 Previous.setRedeclarationKind(ForRedeclaration); 10911 LookupQualifiedName(Previous, SearchDC); 10912 } 10913 } 10914 10915 if (!Previous.empty()) { 10916 NamedDecl *PrevDecl = Previous.getFoundDecl(); 10917 NamedDecl *DirectPrevDecl = 10918 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 10919 10920 // It's okay to have a tag decl in the same scope as a typedef 10921 // which hides a tag decl in the same scope. Finding this 10922 // insanity with a redeclaration lookup can only actually happen 10923 // in C++. 10924 // 10925 // This is also okay for elaborated-type-specifiers, which is 10926 // technically forbidden by the current standard but which is 10927 // okay according to the likely resolution of an open issue; 10928 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 10929 if (getLangOpts().CPlusPlus) { 10930 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 10931 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 10932 TagDecl *Tag = TT->getDecl(); 10933 if (Tag->getDeclName() == Name && 10934 Tag->getDeclContext()->getRedeclContext() 10935 ->Equals(TD->getDeclContext()->getRedeclContext())) { 10936 PrevDecl = Tag; 10937 Previous.clear(); 10938 Previous.addDecl(Tag); 10939 Previous.resolveKind(); 10940 } 10941 } 10942 } 10943 } 10944 10945 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 10946 // If this is a use of a previous tag, or if the tag is already declared 10947 // in the same scope (so that the definition/declaration completes or 10948 // rementions the tag), reuse the decl. 10949 if (TUK == TUK_Reference || TUK == TUK_Friend || 10950 isDeclInScope(DirectPrevDecl, SearchDC, S, 10951 SS.isNotEmpty() || isExplicitSpecialization)) { 10952 // Make sure that this wasn't declared as an enum and now used as a 10953 // struct or something similar. 10954 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 10955 TUK == TUK_Definition, KWLoc, 10956 *Name)) { 10957 bool SafeToContinue 10958 = (PrevTagDecl->getTagKind() != TTK_Enum && 10959 Kind != TTK_Enum); 10960 if (SafeToContinue) 10961 Diag(KWLoc, diag::err_use_with_wrong_tag) 10962 << Name 10963 << FixItHint::CreateReplacement(SourceRange(KWLoc), 10964 PrevTagDecl->getKindName()); 10965 else 10966 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 10967 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 10968 10969 if (SafeToContinue) 10970 Kind = PrevTagDecl->getTagKind(); 10971 else { 10972 // Recover by making this an anonymous redefinition. 10973 Name = nullptr; 10974 Previous.clear(); 10975 Invalid = true; 10976 } 10977 } 10978 10979 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 10980 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 10981 10982 // If this is an elaborated-type-specifier for a scoped enumeration, 10983 // the 'class' keyword is not necessary and not permitted. 10984 if (TUK == TUK_Reference || TUK == TUK_Friend) { 10985 if (ScopedEnum) 10986 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 10987 << PrevEnum->isScoped() 10988 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 10989 return PrevTagDecl; 10990 } 10991 10992 QualType EnumUnderlyingTy; 10993 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 10994 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 10995 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 10996 EnumUnderlyingTy = QualType(T, 0); 10997 10998 // All conflicts with previous declarations are recovered by 10999 // returning the previous declaration, unless this is a definition, 11000 // in which case we want the caller to bail out. 11001 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11002 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11003 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11004 } 11005 11006 // C++11 [class.mem]p1: 11007 // A member shall not be declared twice in the member-specification, 11008 // except that a nested class or member class template can be declared 11009 // and then later defined. 11010 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11011 S->isDeclScope(PrevDecl)) { 11012 Diag(NameLoc, diag::ext_member_redeclared); 11013 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11014 } 11015 11016 if (!Invalid) { 11017 // If this is a use, just return the declaration we found, unless 11018 // we have attributes. 11019 11020 // FIXME: In the future, return a variant or some other clue 11021 // for the consumer of this Decl to know it doesn't own it. 11022 // For our current ASTs this shouldn't be a problem, but will 11023 // need to be changed with DeclGroups. 11024 if (!Attr && 11025 ((TUK == TUK_Reference && 11026 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11027 || TUK == TUK_Friend)) 11028 return PrevTagDecl; 11029 11030 // Diagnose attempts to redefine a tag. 11031 if (TUK == TUK_Definition) { 11032 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11033 // If we're defining a specialization and the previous definition 11034 // is from an implicit instantiation, don't emit an error 11035 // here; we'll catch this in the general case below. 11036 bool IsExplicitSpecializationAfterInstantiation = false; 11037 if (isExplicitSpecialization) { 11038 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11039 IsExplicitSpecializationAfterInstantiation = 11040 RD->getTemplateSpecializationKind() != 11041 TSK_ExplicitSpecialization; 11042 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11043 IsExplicitSpecializationAfterInstantiation = 11044 ED->getTemplateSpecializationKind() != 11045 TSK_ExplicitSpecialization; 11046 } 11047 11048 if (!IsExplicitSpecializationAfterInstantiation) { 11049 // A redeclaration in function prototype scope in C isn't 11050 // visible elsewhere, so merely issue a warning. 11051 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11052 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11053 else 11054 Diag(NameLoc, diag::err_redefinition) << Name; 11055 Diag(Def->getLocation(), diag::note_previous_definition); 11056 // If this is a redefinition, recover by making this 11057 // struct be anonymous, which will make any later 11058 // references get the previous definition. 11059 Name = nullptr; 11060 Previous.clear(); 11061 Invalid = true; 11062 } 11063 } else { 11064 // If the type is currently being defined, complain 11065 // about a nested redefinition. 11066 const TagType *Tag 11067 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 11068 if (Tag->isBeingDefined()) { 11069 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11070 Diag(PrevTagDecl->getLocation(), 11071 diag::note_previous_definition); 11072 Name = nullptr; 11073 Previous.clear(); 11074 Invalid = true; 11075 } 11076 } 11077 11078 // Okay, this is definition of a previously declared or referenced 11079 // tag. We're going to create a new Decl for it. 11080 } 11081 11082 // Okay, we're going to make a redeclaration. If this is some kind 11083 // of reference, make sure we build the redeclaration in the same DC 11084 // as the original, and ignore the current access specifier. 11085 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11086 SearchDC = PrevTagDecl->getDeclContext(); 11087 AS = AS_none; 11088 } 11089 } 11090 // If we get here we have (another) forward declaration or we 11091 // have a definition. Just create a new decl. 11092 11093 } else { 11094 // If we get here, this is a definition of a new tag type in a nested 11095 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11096 // new decl/type. We set PrevDecl to NULL so that the entities 11097 // have distinct types. 11098 Previous.clear(); 11099 } 11100 // If we get here, we're going to create a new Decl. If PrevDecl 11101 // is non-NULL, it's a definition of the tag declared by 11102 // PrevDecl. If it's NULL, we have a new definition. 11103 11104 11105 // Otherwise, PrevDecl is not a tag, but was found with tag 11106 // lookup. This is only actually possible in C++, where a few 11107 // things like templates still live in the tag namespace. 11108 } else { 11109 // Use a better diagnostic if an elaborated-type-specifier 11110 // found the wrong kind of type on the first 11111 // (non-redeclaration) lookup. 11112 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11113 !Previous.isForRedeclaration()) { 11114 unsigned Kind = 0; 11115 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11116 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11117 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11118 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11119 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11120 Invalid = true; 11121 11122 // Otherwise, only diagnose if the declaration is in scope. 11123 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11124 SS.isNotEmpty() || isExplicitSpecialization)) { 11125 // do nothing 11126 11127 // Diagnose implicit declarations introduced by elaborated types. 11128 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11129 unsigned Kind = 0; 11130 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11131 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11132 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11133 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11134 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11135 Invalid = true; 11136 11137 // Otherwise it's a declaration. Call out a particularly common 11138 // case here. 11139 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11140 unsigned Kind = 0; 11141 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11142 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11143 << Name << Kind << TND->getUnderlyingType(); 11144 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11145 Invalid = true; 11146 11147 // Otherwise, diagnose. 11148 } else { 11149 // The tag name clashes with something else in the target scope, 11150 // issue an error and recover by making this tag be anonymous. 11151 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11152 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11153 Name = nullptr; 11154 Invalid = true; 11155 } 11156 11157 // The existing declaration isn't relevant to us; we're in a 11158 // new scope, so clear out the previous declaration. 11159 Previous.clear(); 11160 } 11161 } 11162 11163 CreateNewDecl: 11164 11165 TagDecl *PrevDecl = nullptr; 11166 if (Previous.isSingleResult()) 11167 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11168 11169 // If there is an identifier, use the location of the identifier as the 11170 // location of the decl, otherwise use the location of the struct/union 11171 // keyword. 11172 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11173 11174 // Otherwise, create a new declaration. If there is a previous 11175 // declaration of the same entity, the two will be linked via 11176 // PrevDecl. 11177 TagDecl *New; 11178 11179 bool IsForwardReference = false; 11180 if (Kind == TTK_Enum) { 11181 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11182 // enum X { A, B, C } D; D should chain to X. 11183 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11184 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11185 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11186 // If this is an undefined enum, warn. 11187 if (TUK != TUK_Definition && !Invalid) { 11188 TagDecl *Def; 11189 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11190 cast<EnumDecl>(New)->isFixed()) { 11191 // C++0x: 7.2p2: opaque-enum-declaration. 11192 // Conflicts are diagnosed above. Do nothing. 11193 } 11194 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11195 Diag(Loc, diag::ext_forward_ref_enum_def) 11196 << New; 11197 Diag(Def->getLocation(), diag::note_previous_definition); 11198 } else { 11199 unsigned DiagID = diag::ext_forward_ref_enum; 11200 if (getLangOpts().MSVCCompat) 11201 DiagID = diag::ext_ms_forward_ref_enum; 11202 else if (getLangOpts().CPlusPlus) 11203 DiagID = diag::err_forward_ref_enum; 11204 Diag(Loc, DiagID); 11205 11206 // If this is a forward-declared reference to an enumeration, make a 11207 // note of it; we won't actually be introducing the declaration into 11208 // the declaration context. 11209 if (TUK == TUK_Reference) 11210 IsForwardReference = true; 11211 } 11212 } 11213 11214 if (EnumUnderlying) { 11215 EnumDecl *ED = cast<EnumDecl>(New); 11216 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11217 ED->setIntegerTypeSourceInfo(TI); 11218 else 11219 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11220 ED->setPromotionType(ED->getIntegerType()); 11221 } 11222 11223 } else { 11224 // struct/union/class 11225 11226 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11227 // struct X { int A; } D; D should chain to X. 11228 if (getLangOpts().CPlusPlus) { 11229 // FIXME: Look for a way to use RecordDecl for simple structs. 11230 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11231 cast_or_null<CXXRecordDecl>(PrevDecl)); 11232 11233 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11234 StdBadAlloc = cast<CXXRecordDecl>(New); 11235 } else 11236 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11237 cast_or_null<RecordDecl>(PrevDecl)); 11238 } 11239 11240 // C++11 [dcl.type]p3: 11241 // A type-specifier-seq shall not define a class or enumeration [...]. 11242 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11243 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11244 << Context.getTagDeclType(New); 11245 Invalid = true; 11246 } 11247 11248 // Maybe add qualifier info. 11249 if (SS.isNotEmpty()) { 11250 if (SS.isSet()) { 11251 // If this is either a declaration or a definition, check the 11252 // nested-name-specifier against the current context. We don't do this 11253 // for explicit specializations, because they have similar checking 11254 // (with more specific diagnostics) in the call to 11255 // CheckMemberSpecialization, below. 11256 if (!isExplicitSpecialization && 11257 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11258 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11259 Invalid = true; 11260 11261 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11262 if (TemplateParameterLists.size() > 0) { 11263 New->setTemplateParameterListsInfo(Context, 11264 TemplateParameterLists.size(), 11265 TemplateParameterLists.data()); 11266 } 11267 } 11268 else 11269 Invalid = true; 11270 } 11271 11272 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11273 // Add alignment attributes if necessary; these attributes are checked when 11274 // the ASTContext lays out the structure. 11275 // 11276 // It is important for implementing the correct semantics that this 11277 // happen here (in act on tag decl). The #pragma pack stack is 11278 // maintained as a result of parser callbacks which can occur at 11279 // many points during the parsing of a struct declaration (because 11280 // the #pragma tokens are effectively skipped over during the 11281 // parsing of the struct). 11282 if (TUK == TUK_Definition) { 11283 AddAlignmentAttributesForRecord(RD); 11284 AddMsStructLayoutForRecord(RD); 11285 } 11286 } 11287 11288 if (ModulePrivateLoc.isValid()) { 11289 if (isExplicitSpecialization) 11290 Diag(New->getLocation(), diag::err_module_private_specialization) 11291 << 2 11292 << FixItHint::CreateRemoval(ModulePrivateLoc); 11293 // __module_private__ does not apply to local classes. However, we only 11294 // diagnose this as an error when the declaration specifiers are 11295 // freestanding. Here, we just ignore the __module_private__. 11296 else if (!SearchDC->isFunctionOrMethod()) 11297 New->setModulePrivate(); 11298 } 11299 11300 // If this is a specialization of a member class (of a class template), 11301 // check the specialization. 11302 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11303 Invalid = true; 11304 11305 if (Invalid) 11306 New->setInvalidDecl(); 11307 11308 if (Attr) 11309 ProcessDeclAttributeList(S, New, Attr); 11310 11311 // If we're declaring or defining a tag in function prototype scope in C, 11312 // note that this type can only be used within the function and add it to 11313 // the list of decls to inject into the function definition scope. 11314 if (!getLangOpts().CPlusPlus && (Name || Kind == TTK_Enum) && 11315 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11316 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11317 DeclsInPrototypeScope.push_back(New); 11318 } 11319 11320 // Set the lexical context. If the tag has a C++ scope specifier, the 11321 // lexical context will be different from the semantic context. 11322 New->setLexicalDeclContext(CurContext); 11323 11324 // Mark this as a friend decl if applicable. 11325 // In Microsoft mode, a friend declaration also acts as a forward 11326 // declaration so we always pass true to setObjectOfFriendDecl to make 11327 // the tag name visible. 11328 if (TUK == TUK_Friend) 11329 New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace && 11330 getLangOpts().MicrosoftExt); 11331 11332 // Set the access specifier. 11333 if (!Invalid && SearchDC->isRecord()) 11334 SetMemberAccessSpecifier(New, PrevDecl, AS); 11335 11336 if (TUK == TUK_Definition) 11337 New->startDefinition(); 11338 11339 // If this has an identifier, add it to the scope stack. 11340 if (TUK == TUK_Friend) { 11341 // We might be replacing an existing declaration in the lookup tables; 11342 // if so, borrow its access specifier. 11343 if (PrevDecl) 11344 New->setAccess(PrevDecl->getAccess()); 11345 11346 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11347 DC->makeDeclVisibleInContext(New); 11348 if (Name) // can be null along some error paths 11349 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11350 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11351 } else if (Name) { 11352 S = getNonFieldDeclScope(S); 11353 PushOnScopeChains(New, S, !IsForwardReference); 11354 if (IsForwardReference) 11355 SearchDC->makeDeclVisibleInContext(New); 11356 11357 } else { 11358 CurContext->addDecl(New); 11359 } 11360 11361 // If this is the C FILE type, notify the AST context. 11362 if (IdentifierInfo *II = New->getIdentifier()) 11363 if (!New->isInvalidDecl() && 11364 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11365 II->isStr("FILE")) 11366 Context.setFILEDecl(New); 11367 11368 if (PrevDecl) 11369 mergeDeclAttributes(New, PrevDecl); 11370 11371 // If there's a #pragma GCC visibility in scope, set the visibility of this 11372 // record. 11373 AddPushedVisibilityAttribute(New); 11374 11375 OwnedDecl = true; 11376 // In C++, don't return an invalid declaration. We can't recover well from 11377 // the cases where we make the type anonymous. 11378 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 11379 } 11380 11381 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11382 AdjustDeclIfTemplate(TagD); 11383 TagDecl *Tag = cast<TagDecl>(TagD); 11384 11385 // Enter the tag context. 11386 PushDeclContext(S, Tag); 11387 11388 ActOnDocumentableDecl(TagD); 11389 11390 // If there's a #pragma GCC visibility in scope, set the visibility of this 11391 // record. 11392 AddPushedVisibilityAttribute(Tag); 11393 } 11394 11395 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11396 assert(isa<ObjCContainerDecl>(IDecl) && 11397 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11398 DeclContext *OCD = cast<DeclContext>(IDecl); 11399 assert(getContainingDC(OCD) == CurContext && 11400 "The next DeclContext should be lexically contained in the current one."); 11401 CurContext = OCD; 11402 return IDecl; 11403 } 11404 11405 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11406 SourceLocation FinalLoc, 11407 bool IsFinalSpelledSealed, 11408 SourceLocation LBraceLoc) { 11409 AdjustDeclIfTemplate(TagD); 11410 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11411 11412 FieldCollector->StartClass(); 11413 11414 if (!Record->getIdentifier()) 11415 return; 11416 11417 if (FinalLoc.isValid()) 11418 Record->addAttr(new (Context) 11419 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11420 11421 // C++ [class]p2: 11422 // [...] The class-name is also inserted into the scope of the 11423 // class itself; this is known as the injected-class-name. For 11424 // purposes of access checking, the injected-class-name is treated 11425 // as if it were a public member name. 11426 CXXRecordDecl *InjectedClassName 11427 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11428 Record->getLocStart(), Record->getLocation(), 11429 Record->getIdentifier(), 11430 /*PrevDecl=*/nullptr, 11431 /*DelayTypeCreation=*/true); 11432 Context.getTypeDeclType(InjectedClassName, Record); 11433 InjectedClassName->setImplicit(); 11434 InjectedClassName->setAccess(AS_public); 11435 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11436 InjectedClassName->setDescribedClassTemplate(Template); 11437 PushOnScopeChains(InjectedClassName, S); 11438 assert(InjectedClassName->isInjectedClassName() && 11439 "Broken injected-class-name"); 11440 } 11441 11442 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11443 SourceLocation RBraceLoc) { 11444 AdjustDeclIfTemplate(TagD); 11445 TagDecl *Tag = cast<TagDecl>(TagD); 11446 Tag->setRBraceLoc(RBraceLoc); 11447 11448 // Make sure we "complete" the definition even it is invalid. 11449 if (Tag->isBeingDefined()) { 11450 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11451 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11452 RD->completeDefinition(); 11453 } 11454 11455 if (isa<CXXRecordDecl>(Tag)) 11456 FieldCollector->FinishClass(); 11457 11458 // Exit this scope of this tag's definition. 11459 PopDeclContext(); 11460 11461 if (getCurLexicalContext()->isObjCContainer() && 11462 Tag->getDeclContext()->isFileContext()) 11463 Tag->setTopLevelDeclInObjCContainer(); 11464 11465 // Notify the consumer that we've defined a tag. 11466 if (!Tag->isInvalidDecl()) 11467 Consumer.HandleTagDeclDefinition(Tag); 11468 } 11469 11470 void Sema::ActOnObjCContainerFinishDefinition() { 11471 // Exit this scope of this interface definition. 11472 PopDeclContext(); 11473 } 11474 11475 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11476 assert(DC == CurContext && "Mismatch of container contexts"); 11477 OriginalLexicalContext = DC; 11478 ActOnObjCContainerFinishDefinition(); 11479 } 11480 11481 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11482 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11483 OriginalLexicalContext = nullptr; 11484 } 11485 11486 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11487 AdjustDeclIfTemplate(TagD); 11488 TagDecl *Tag = cast<TagDecl>(TagD); 11489 Tag->setInvalidDecl(); 11490 11491 // Make sure we "complete" the definition even it is invalid. 11492 if (Tag->isBeingDefined()) { 11493 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11494 RD->completeDefinition(); 11495 } 11496 11497 // We're undoing ActOnTagStartDefinition here, not 11498 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 11499 // the FieldCollector. 11500 11501 PopDeclContext(); 11502 } 11503 11504 // Note that FieldName may be null for anonymous bitfields. 11505 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 11506 IdentifierInfo *FieldName, 11507 QualType FieldTy, bool IsMsStruct, 11508 Expr *BitWidth, bool *ZeroWidth) { 11509 // Default to true; that shouldn't confuse checks for emptiness 11510 if (ZeroWidth) 11511 *ZeroWidth = true; 11512 11513 // C99 6.7.2.1p4 - verify the field type. 11514 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 11515 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 11516 // Handle incomplete types with specific error. 11517 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 11518 return ExprError(); 11519 if (FieldName) 11520 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 11521 << FieldName << FieldTy << BitWidth->getSourceRange(); 11522 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 11523 << FieldTy << BitWidth->getSourceRange(); 11524 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 11525 UPPC_BitFieldWidth)) 11526 return ExprError(); 11527 11528 // If the bit-width is type- or value-dependent, don't try to check 11529 // it now. 11530 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 11531 return BitWidth; 11532 11533 llvm::APSInt Value; 11534 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 11535 if (ICE.isInvalid()) 11536 return ICE; 11537 BitWidth = ICE.get(); 11538 11539 if (Value != 0 && ZeroWidth) 11540 *ZeroWidth = false; 11541 11542 // Zero-width bitfield is ok for anonymous field. 11543 if (Value == 0 && FieldName) 11544 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 11545 11546 if (Value.isSigned() && Value.isNegative()) { 11547 if (FieldName) 11548 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 11549 << FieldName << Value.toString(10); 11550 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 11551 << Value.toString(10); 11552 } 11553 11554 if (!FieldTy->isDependentType()) { 11555 uint64_t TypeSize = Context.getTypeSize(FieldTy); 11556 if (Value.getZExtValue() > TypeSize) { 11557 if (!getLangOpts().CPlusPlus || IsMsStruct || 11558 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11559 if (FieldName) 11560 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 11561 << FieldName << (unsigned)Value.getZExtValue() 11562 << (unsigned)TypeSize; 11563 11564 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 11565 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11566 } 11567 11568 if (FieldName) 11569 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 11570 << FieldName << (unsigned)Value.getZExtValue() 11571 << (unsigned)TypeSize; 11572 else 11573 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 11574 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 11575 } 11576 } 11577 11578 return BitWidth; 11579 } 11580 11581 /// ActOnField - Each field of a C struct/union is passed into this in order 11582 /// to create a FieldDecl object for it. 11583 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 11584 Declarator &D, Expr *BitfieldWidth) { 11585 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 11586 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 11587 /*InitStyle=*/ICIS_NoInit, AS_public); 11588 return Res; 11589 } 11590 11591 /// HandleField - Analyze a field of a C struct or a C++ data member. 11592 /// 11593 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 11594 SourceLocation DeclStart, 11595 Declarator &D, Expr *BitWidth, 11596 InClassInitStyle InitStyle, 11597 AccessSpecifier AS) { 11598 IdentifierInfo *II = D.getIdentifier(); 11599 SourceLocation Loc = DeclStart; 11600 if (II) Loc = D.getIdentifierLoc(); 11601 11602 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11603 QualType T = TInfo->getType(); 11604 if (getLangOpts().CPlusPlus) { 11605 CheckExtraCXXDefaultArguments(D); 11606 11607 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11608 UPPC_DataMemberType)) { 11609 D.setInvalidType(); 11610 T = Context.IntTy; 11611 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 11612 } 11613 } 11614 11615 // TR 18037 does not allow fields to be declared with address spaces. 11616 if (T.getQualifiers().hasAddressSpace()) { 11617 Diag(Loc, diag::err_field_with_address_space); 11618 D.setInvalidType(); 11619 } 11620 11621 // OpenCL 1.2 spec, s6.9 r: 11622 // The event type cannot be used to declare a structure or union field. 11623 if (LangOpts.OpenCL && T->isEventT()) { 11624 Diag(Loc, diag::err_event_t_struct_field); 11625 D.setInvalidType(); 11626 } 11627 11628 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 11629 11630 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 11631 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 11632 diag::err_invalid_thread) 11633 << DeclSpec::getSpecifierName(TSCS); 11634 11635 // Check to see if this name was declared as a member previously 11636 NamedDecl *PrevDecl = nullptr; 11637 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 11638 LookupName(Previous, S); 11639 switch (Previous.getResultKind()) { 11640 case LookupResult::Found: 11641 case LookupResult::FoundUnresolvedValue: 11642 PrevDecl = Previous.getAsSingle<NamedDecl>(); 11643 break; 11644 11645 case LookupResult::FoundOverloaded: 11646 PrevDecl = Previous.getRepresentativeDecl(); 11647 break; 11648 11649 case LookupResult::NotFound: 11650 case LookupResult::NotFoundInCurrentInstantiation: 11651 case LookupResult::Ambiguous: 11652 break; 11653 } 11654 Previous.suppressDiagnostics(); 11655 11656 if (PrevDecl && PrevDecl->isTemplateParameter()) { 11657 // Maybe we will complain about the shadowed template parameter. 11658 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11659 // Just pretend that we didn't see the previous declaration. 11660 PrevDecl = nullptr; 11661 } 11662 11663 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 11664 PrevDecl = nullptr; 11665 11666 bool Mutable 11667 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 11668 SourceLocation TSSL = D.getLocStart(); 11669 FieldDecl *NewFD 11670 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 11671 TSSL, AS, PrevDecl, &D); 11672 11673 if (NewFD->isInvalidDecl()) 11674 Record->setInvalidDecl(); 11675 11676 if (D.getDeclSpec().isModulePrivateSpecified()) 11677 NewFD->setModulePrivate(); 11678 11679 if (NewFD->isInvalidDecl() && PrevDecl) { 11680 // Don't introduce NewFD into scope; there's already something 11681 // with the same name in the same scope. 11682 } else if (II) { 11683 PushOnScopeChains(NewFD, S); 11684 } else 11685 Record->addDecl(NewFD); 11686 11687 return NewFD; 11688 } 11689 11690 /// \brief Build a new FieldDecl and check its well-formedness. 11691 /// 11692 /// This routine builds a new FieldDecl given the fields name, type, 11693 /// record, etc. \p PrevDecl should refer to any previous declaration 11694 /// with the same name and in the same scope as the field to be 11695 /// created. 11696 /// 11697 /// \returns a new FieldDecl. 11698 /// 11699 /// \todo The Declarator argument is a hack. It will be removed once 11700 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 11701 TypeSourceInfo *TInfo, 11702 RecordDecl *Record, SourceLocation Loc, 11703 bool Mutable, Expr *BitWidth, 11704 InClassInitStyle InitStyle, 11705 SourceLocation TSSL, 11706 AccessSpecifier AS, NamedDecl *PrevDecl, 11707 Declarator *D) { 11708 IdentifierInfo *II = Name.getAsIdentifierInfo(); 11709 bool InvalidDecl = false; 11710 if (D) InvalidDecl = D->isInvalidType(); 11711 11712 // If we receive a broken type, recover by assuming 'int' and 11713 // marking this declaration as invalid. 11714 if (T.isNull()) { 11715 InvalidDecl = true; 11716 T = Context.IntTy; 11717 } 11718 11719 QualType EltTy = Context.getBaseElementType(T); 11720 if (!EltTy->isDependentType()) { 11721 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 11722 // Fields of incomplete type force their record to be invalid. 11723 Record->setInvalidDecl(); 11724 InvalidDecl = true; 11725 } else { 11726 NamedDecl *Def; 11727 EltTy->isIncompleteType(&Def); 11728 if (Def && Def->isInvalidDecl()) { 11729 Record->setInvalidDecl(); 11730 InvalidDecl = true; 11731 } 11732 } 11733 } 11734 11735 // OpenCL v1.2 s6.9.c: bitfields are not supported. 11736 if (BitWidth && getLangOpts().OpenCL) { 11737 Diag(Loc, diag::err_opencl_bitfields); 11738 InvalidDecl = true; 11739 } 11740 11741 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11742 // than a variably modified type. 11743 if (!InvalidDecl && T->isVariablyModifiedType()) { 11744 bool SizeIsNegative; 11745 llvm::APSInt Oversized; 11746 11747 TypeSourceInfo *FixedTInfo = 11748 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 11749 SizeIsNegative, 11750 Oversized); 11751 if (FixedTInfo) { 11752 Diag(Loc, diag::warn_illegal_constant_array_size); 11753 TInfo = FixedTInfo; 11754 T = FixedTInfo->getType(); 11755 } else { 11756 if (SizeIsNegative) 11757 Diag(Loc, diag::err_typecheck_negative_array_size); 11758 else if (Oversized.getBoolValue()) 11759 Diag(Loc, diag::err_array_too_large) 11760 << Oversized.toString(10); 11761 else 11762 Diag(Loc, diag::err_typecheck_field_variable_size); 11763 InvalidDecl = true; 11764 } 11765 } 11766 11767 // Fields can not have abstract class types 11768 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 11769 diag::err_abstract_type_in_decl, 11770 AbstractFieldType)) 11771 InvalidDecl = true; 11772 11773 bool ZeroWidth = false; 11774 // If this is declared as a bit-field, check the bit-field. 11775 if (!InvalidDecl && BitWidth) { 11776 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 11777 &ZeroWidth).get(); 11778 if (!BitWidth) { 11779 InvalidDecl = true; 11780 BitWidth = nullptr; 11781 ZeroWidth = false; 11782 } 11783 } 11784 11785 // Check that 'mutable' is consistent with the type of the declaration. 11786 if (!InvalidDecl && Mutable) { 11787 unsigned DiagID = 0; 11788 if (T->isReferenceType()) 11789 DiagID = diag::err_mutable_reference; 11790 else if (T.isConstQualified()) 11791 DiagID = diag::err_mutable_const; 11792 11793 if (DiagID) { 11794 SourceLocation ErrLoc = Loc; 11795 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 11796 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 11797 Diag(ErrLoc, DiagID); 11798 Mutable = false; 11799 InvalidDecl = true; 11800 } 11801 } 11802 11803 // C++11 [class.union]p8 (DR1460): 11804 // At most one variant member of a union may have a 11805 // brace-or-equal-initializer. 11806 if (InitStyle != ICIS_NoInit) 11807 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 11808 11809 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 11810 BitWidth, Mutable, InitStyle); 11811 if (InvalidDecl) 11812 NewFD->setInvalidDecl(); 11813 11814 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 11815 Diag(Loc, diag::err_duplicate_member) << II; 11816 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11817 NewFD->setInvalidDecl(); 11818 } 11819 11820 if (!InvalidDecl && getLangOpts().CPlusPlus) { 11821 if (Record->isUnion()) { 11822 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11823 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11824 if (RDecl->getDefinition()) { 11825 // C++ [class.union]p1: An object of a class with a non-trivial 11826 // constructor, a non-trivial copy constructor, a non-trivial 11827 // destructor, or a non-trivial copy assignment operator 11828 // cannot be a member of a union, nor can an array of such 11829 // objects. 11830 if (CheckNontrivialField(NewFD)) 11831 NewFD->setInvalidDecl(); 11832 } 11833 } 11834 11835 // C++ [class.union]p1: If a union contains a member of reference type, 11836 // the program is ill-formed, except when compiling with MSVC extensions 11837 // enabled. 11838 if (EltTy->isReferenceType()) { 11839 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 11840 diag::ext_union_member_of_reference_type : 11841 diag::err_union_member_of_reference_type) 11842 << NewFD->getDeclName() << EltTy; 11843 if (!getLangOpts().MicrosoftExt) 11844 NewFD->setInvalidDecl(); 11845 } 11846 } 11847 } 11848 11849 // FIXME: We need to pass in the attributes given an AST 11850 // representation, not a parser representation. 11851 if (D) { 11852 // FIXME: The current scope is almost... but not entirely... correct here. 11853 ProcessDeclAttributes(getCurScope(), NewFD, *D); 11854 11855 if (NewFD->hasAttrs()) 11856 CheckAlignasUnderalignment(NewFD); 11857 } 11858 11859 // In auto-retain/release, infer strong retension for fields of 11860 // retainable type. 11861 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 11862 NewFD->setInvalidDecl(); 11863 11864 if (T.isObjCGCWeak()) 11865 Diag(Loc, diag::warn_attribute_weak_on_field); 11866 11867 NewFD->setAccess(AS); 11868 return NewFD; 11869 } 11870 11871 bool Sema::CheckNontrivialField(FieldDecl *FD) { 11872 assert(FD); 11873 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 11874 11875 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 11876 return false; 11877 11878 QualType EltTy = Context.getBaseElementType(FD->getType()); 11879 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 11880 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 11881 if (RDecl->getDefinition()) { 11882 // We check for copy constructors before constructors 11883 // because otherwise we'll never get complaints about 11884 // copy constructors. 11885 11886 CXXSpecialMember member = CXXInvalid; 11887 // We're required to check for any non-trivial constructors. Since the 11888 // implicit default constructor is suppressed if there are any 11889 // user-declared constructors, we just need to check that there is a 11890 // trivial default constructor and a trivial copy constructor. (We don't 11891 // worry about move constructors here, since this is a C++98 check.) 11892 if (RDecl->hasNonTrivialCopyConstructor()) 11893 member = CXXCopyConstructor; 11894 else if (!RDecl->hasTrivialDefaultConstructor()) 11895 member = CXXDefaultConstructor; 11896 else if (RDecl->hasNonTrivialCopyAssignment()) 11897 member = CXXCopyAssignment; 11898 else if (RDecl->hasNonTrivialDestructor()) 11899 member = CXXDestructor; 11900 11901 if (member != CXXInvalid) { 11902 if (!getLangOpts().CPlusPlus11 && 11903 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 11904 // Objective-C++ ARC: it is an error to have a non-trivial field of 11905 // a union. However, system headers in Objective-C programs 11906 // occasionally have Objective-C lifetime objects within unions, 11907 // and rather than cause the program to fail, we make those 11908 // members unavailable. 11909 SourceLocation Loc = FD->getLocation(); 11910 if (getSourceManager().isInSystemHeader(Loc)) { 11911 if (!FD->hasAttr<UnavailableAttr>()) 11912 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 11913 "this system field has retaining ownership", 11914 Loc)); 11915 return false; 11916 } 11917 } 11918 11919 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 11920 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 11921 diag::err_illegal_union_or_anon_struct_member) 11922 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 11923 DiagnoseNontrivial(RDecl, member); 11924 return !getLangOpts().CPlusPlus11; 11925 } 11926 } 11927 } 11928 11929 return false; 11930 } 11931 11932 /// TranslateIvarVisibility - Translate visibility from a token ID to an 11933 /// AST enum value. 11934 static ObjCIvarDecl::AccessControl 11935 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 11936 switch (ivarVisibility) { 11937 default: llvm_unreachable("Unknown visitibility kind"); 11938 case tok::objc_private: return ObjCIvarDecl::Private; 11939 case tok::objc_public: return ObjCIvarDecl::Public; 11940 case tok::objc_protected: return ObjCIvarDecl::Protected; 11941 case tok::objc_package: return ObjCIvarDecl::Package; 11942 } 11943 } 11944 11945 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 11946 /// in order to create an IvarDecl object for it. 11947 Decl *Sema::ActOnIvar(Scope *S, 11948 SourceLocation DeclStart, 11949 Declarator &D, Expr *BitfieldWidth, 11950 tok::ObjCKeywordKind Visibility) { 11951 11952 IdentifierInfo *II = D.getIdentifier(); 11953 Expr *BitWidth = (Expr*)BitfieldWidth; 11954 SourceLocation Loc = DeclStart; 11955 if (II) Loc = D.getIdentifierLoc(); 11956 11957 // FIXME: Unnamed fields can be handled in various different ways, for 11958 // example, unnamed unions inject all members into the struct namespace! 11959 11960 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11961 QualType T = TInfo->getType(); 11962 11963 if (BitWidth) { 11964 // 6.7.2.1p3, 6.7.2.1p4 11965 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 11966 if (!BitWidth) 11967 D.setInvalidType(); 11968 } else { 11969 // Not a bitfield. 11970 11971 // validate II. 11972 11973 } 11974 if (T->isReferenceType()) { 11975 Diag(Loc, diag::err_ivar_reference_type); 11976 D.setInvalidType(); 11977 } 11978 // C99 6.7.2.1p8: A member of a structure or union may have any type other 11979 // than a variably modified type. 11980 else if (T->isVariablyModifiedType()) { 11981 Diag(Loc, diag::err_typecheck_ivar_variable_size); 11982 D.setInvalidType(); 11983 } 11984 11985 // Get the visibility (access control) for this ivar. 11986 ObjCIvarDecl::AccessControl ac = 11987 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 11988 : ObjCIvarDecl::None; 11989 // Must set ivar's DeclContext to its enclosing interface. 11990 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 11991 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 11992 return nullptr; 11993 ObjCContainerDecl *EnclosingContext; 11994 if (ObjCImplementationDecl *IMPDecl = 11995 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 11996 if (LangOpts.ObjCRuntime.isFragile()) { 11997 // Case of ivar declared in an implementation. Context is that of its class. 11998 EnclosingContext = IMPDecl->getClassInterface(); 11999 assert(EnclosingContext && "Implementation has no class interface!"); 12000 } 12001 else 12002 EnclosingContext = EnclosingDecl; 12003 } else { 12004 if (ObjCCategoryDecl *CDecl = 12005 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12006 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12007 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12008 return nullptr; 12009 } 12010 } 12011 EnclosingContext = EnclosingDecl; 12012 } 12013 12014 // Construct the decl. 12015 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12016 DeclStart, Loc, II, T, 12017 TInfo, ac, (Expr *)BitfieldWidth); 12018 12019 if (II) { 12020 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12021 ForRedeclaration); 12022 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12023 && !isa<TagDecl>(PrevDecl)) { 12024 Diag(Loc, diag::err_duplicate_member) << II; 12025 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12026 NewID->setInvalidDecl(); 12027 } 12028 } 12029 12030 // Process attributes attached to the ivar. 12031 ProcessDeclAttributes(S, NewID, D); 12032 12033 if (D.isInvalidType()) 12034 NewID->setInvalidDecl(); 12035 12036 // In ARC, infer 'retaining' for ivars of retainable type. 12037 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12038 NewID->setInvalidDecl(); 12039 12040 if (D.getDeclSpec().isModulePrivateSpecified()) 12041 NewID->setModulePrivate(); 12042 12043 if (II) { 12044 // FIXME: When interfaces are DeclContexts, we'll need to add 12045 // these to the interface. 12046 S->AddDecl(NewID); 12047 IdResolver.AddDecl(NewID); 12048 } 12049 12050 if (LangOpts.ObjCRuntime.isNonFragile() && 12051 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12052 Diag(Loc, diag::warn_ivars_in_interface); 12053 12054 return NewID; 12055 } 12056 12057 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12058 /// class and class extensions. For every class \@interface and class 12059 /// extension \@interface, if the last ivar is a bitfield of any type, 12060 /// then add an implicit `char :0` ivar to the end of that interface. 12061 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12062 SmallVectorImpl<Decl *> &AllIvarDecls) { 12063 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12064 return; 12065 12066 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12067 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12068 12069 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12070 return; 12071 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12072 if (!ID) { 12073 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12074 if (!CD->IsClassExtension()) 12075 return; 12076 } 12077 // No need to add this to end of @implementation. 12078 else 12079 return; 12080 } 12081 // All conditions are met. Add a new bitfield to the tail end of ivars. 12082 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12083 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12084 12085 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12086 DeclLoc, DeclLoc, nullptr, 12087 Context.CharTy, 12088 Context.getTrivialTypeSourceInfo(Context.CharTy, 12089 DeclLoc), 12090 ObjCIvarDecl::Private, BW, 12091 true); 12092 AllIvarDecls.push_back(Ivar); 12093 } 12094 12095 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12096 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12097 SourceLocation RBrac, AttributeList *Attr) { 12098 assert(EnclosingDecl && "missing record or interface decl"); 12099 12100 // If this is an Objective-C @implementation or category and we have 12101 // new fields here we should reset the layout of the interface since 12102 // it will now change. 12103 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12104 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12105 switch (DC->getKind()) { 12106 default: break; 12107 case Decl::ObjCCategory: 12108 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12109 break; 12110 case Decl::ObjCImplementation: 12111 Context. 12112 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12113 break; 12114 } 12115 } 12116 12117 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12118 12119 // Start counting up the number of named members; make sure to include 12120 // members of anonymous structs and unions in the total. 12121 unsigned NumNamedMembers = 0; 12122 if (Record) { 12123 for (const auto *I : Record->decls()) { 12124 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12125 if (IFD->getDeclName()) 12126 ++NumNamedMembers; 12127 } 12128 } 12129 12130 // Verify that all the fields are okay. 12131 SmallVector<FieldDecl*, 32> RecFields; 12132 12133 bool ARCErrReported = false; 12134 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12135 i != end; ++i) { 12136 FieldDecl *FD = cast<FieldDecl>(*i); 12137 12138 // Get the type for the field. 12139 const Type *FDTy = FD->getType().getTypePtr(); 12140 12141 if (!FD->isAnonymousStructOrUnion()) { 12142 // Remember all fields written by the user. 12143 RecFields.push_back(FD); 12144 } 12145 12146 // If the field is already invalid for some reason, don't emit more 12147 // diagnostics about it. 12148 if (FD->isInvalidDecl()) { 12149 EnclosingDecl->setInvalidDecl(); 12150 continue; 12151 } 12152 12153 // C99 6.7.2.1p2: 12154 // A structure or union shall not contain a member with 12155 // incomplete or function type (hence, a structure shall not 12156 // contain an instance of itself, but may contain a pointer to 12157 // an instance of itself), except that the last member of a 12158 // structure with more than one named member may have incomplete 12159 // array type; such a structure (and any union containing, 12160 // possibly recursively, a member that is such a structure) 12161 // shall not be a member of a structure or an element of an 12162 // array. 12163 if (FDTy->isFunctionType()) { 12164 // Field declared as a function. 12165 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12166 << FD->getDeclName(); 12167 FD->setInvalidDecl(); 12168 EnclosingDecl->setInvalidDecl(); 12169 continue; 12170 } else if (FDTy->isIncompleteArrayType() && Record && 12171 ((i + 1 == Fields.end() && !Record->isUnion()) || 12172 ((getLangOpts().MicrosoftExt || 12173 getLangOpts().CPlusPlus) && 12174 (i + 1 == Fields.end() || Record->isUnion())))) { 12175 // Flexible array member. 12176 // Microsoft and g++ is more permissive regarding flexible array. 12177 // It will accept flexible array in union and also 12178 // as the sole element of a struct/class. 12179 unsigned DiagID = 0; 12180 if (Record->isUnion()) 12181 DiagID = getLangOpts().MicrosoftExt 12182 ? diag::ext_flexible_array_union_ms 12183 : getLangOpts().CPlusPlus 12184 ? diag::ext_flexible_array_union_gnu 12185 : diag::err_flexible_array_union; 12186 else if (Fields.size() == 1) 12187 DiagID = getLangOpts().MicrosoftExt 12188 ? diag::ext_flexible_array_empty_aggregate_ms 12189 : getLangOpts().CPlusPlus 12190 ? diag::ext_flexible_array_empty_aggregate_gnu 12191 : NumNamedMembers < 1 12192 ? diag::err_flexible_array_empty_aggregate 12193 : 0; 12194 12195 if (DiagID) 12196 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12197 << Record->getTagKind(); 12198 // While the layout of types that contain virtual bases is not specified 12199 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12200 // virtual bases after the derived members. This would make a flexible 12201 // array member declared at the end of an object not adjacent to the end 12202 // of the type. 12203 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12204 if (RD->getNumVBases() != 0) 12205 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12206 << FD->getDeclName() << Record->getTagKind(); 12207 if (!getLangOpts().C99) 12208 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12209 << FD->getDeclName() << Record->getTagKind(); 12210 12211 // If the element type has a non-trivial destructor, we would not 12212 // implicitly destroy the elements, so disallow it for now. 12213 // 12214 // FIXME: GCC allows this. We should probably either implicitly delete 12215 // the destructor of the containing class, or just allow this. 12216 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12217 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12218 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12219 << FD->getDeclName() << FD->getType(); 12220 FD->setInvalidDecl(); 12221 EnclosingDecl->setInvalidDecl(); 12222 continue; 12223 } 12224 // Okay, we have a legal flexible array member at the end of the struct. 12225 if (Record) 12226 Record->setHasFlexibleArrayMember(true); 12227 } else if (!FDTy->isDependentType() && 12228 RequireCompleteType(FD->getLocation(), FD->getType(), 12229 diag::err_field_incomplete)) { 12230 // Incomplete type 12231 FD->setInvalidDecl(); 12232 EnclosingDecl->setInvalidDecl(); 12233 continue; 12234 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12235 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 12236 // If this is a member of a union, then entire union becomes "flexible". 12237 if (Record && Record->isUnion()) { 12238 Record->setHasFlexibleArrayMember(true); 12239 } else { 12240 // If this is a struct/class and this is not the last element, reject 12241 // it. Note that GCC supports variable sized arrays in the middle of 12242 // structures. 12243 if (i + 1 != Fields.end()) 12244 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12245 << FD->getDeclName() << FD->getType(); 12246 else { 12247 // We support flexible arrays at the end of structs in 12248 // other structs as an extension. 12249 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12250 << FD->getDeclName(); 12251 if (Record) 12252 Record->setHasFlexibleArrayMember(true); 12253 } 12254 } 12255 } 12256 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12257 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12258 diag::err_abstract_type_in_decl, 12259 AbstractIvarType)) { 12260 // Ivars can not have abstract class types 12261 FD->setInvalidDecl(); 12262 } 12263 if (Record && FDTTy->getDecl()->hasObjectMember()) 12264 Record->setHasObjectMember(true); 12265 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12266 Record->setHasVolatileMember(true); 12267 } else if (FDTy->isObjCObjectType()) { 12268 /// A field cannot be an Objective-c object 12269 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12270 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12271 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12272 FD->setType(T); 12273 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12274 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12275 // It's an error in ARC if a field has lifetime. 12276 // We don't want to report this in a system header, though, 12277 // so we just make the field unavailable. 12278 // FIXME: that's really not sufficient; we need to make the type 12279 // itself invalid to, say, initialize or copy. 12280 QualType T = FD->getType(); 12281 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12282 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12283 SourceLocation loc = FD->getLocation(); 12284 if (getSourceManager().isInSystemHeader(loc)) { 12285 if (!FD->hasAttr<UnavailableAttr>()) { 12286 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12287 "this system field has retaining ownership", 12288 loc)); 12289 } 12290 } else { 12291 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12292 << T->isBlockPointerType() << Record->getTagKind(); 12293 } 12294 ARCErrReported = true; 12295 } 12296 } else if (getLangOpts().ObjC1 && 12297 getLangOpts().getGC() != LangOptions::NonGC && 12298 Record && !Record->hasObjectMember()) { 12299 if (FD->getType()->isObjCObjectPointerType() || 12300 FD->getType().isObjCGCStrong()) 12301 Record->setHasObjectMember(true); 12302 else if (Context.getAsArrayType(FD->getType())) { 12303 QualType BaseType = Context.getBaseElementType(FD->getType()); 12304 if (BaseType->isRecordType() && 12305 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12306 Record->setHasObjectMember(true); 12307 else if (BaseType->isObjCObjectPointerType() || 12308 BaseType.isObjCGCStrong()) 12309 Record->setHasObjectMember(true); 12310 } 12311 } 12312 if (Record && FD->getType().isVolatileQualified()) 12313 Record->setHasVolatileMember(true); 12314 // Keep track of the number of named members. 12315 if (FD->getIdentifier()) 12316 ++NumNamedMembers; 12317 } 12318 12319 // Okay, we successfully defined 'Record'. 12320 if (Record) { 12321 bool Completed = false; 12322 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12323 if (!CXXRecord->isInvalidDecl()) { 12324 // Set access bits correctly on the directly-declared conversions. 12325 for (CXXRecordDecl::conversion_iterator 12326 I = CXXRecord->conversion_begin(), 12327 E = CXXRecord->conversion_end(); I != E; ++I) 12328 I.setAccess((*I)->getAccess()); 12329 12330 if (!CXXRecord->isDependentType()) { 12331 if (CXXRecord->hasUserDeclaredDestructor()) { 12332 // Adjust user-defined destructor exception spec. 12333 if (getLangOpts().CPlusPlus11) 12334 AdjustDestructorExceptionSpec(CXXRecord, 12335 CXXRecord->getDestructor()); 12336 } 12337 12338 // Add any implicitly-declared members to this class. 12339 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12340 12341 // If we have virtual base classes, we may end up finding multiple 12342 // final overriders for a given virtual function. Check for this 12343 // problem now. 12344 if (CXXRecord->getNumVBases()) { 12345 CXXFinalOverriderMap FinalOverriders; 12346 CXXRecord->getFinalOverriders(FinalOverriders); 12347 12348 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12349 MEnd = FinalOverriders.end(); 12350 M != MEnd; ++M) { 12351 for (OverridingMethods::iterator SO = M->second.begin(), 12352 SOEnd = M->second.end(); 12353 SO != SOEnd; ++SO) { 12354 assert(SO->second.size() > 0 && 12355 "Virtual function without overridding functions?"); 12356 if (SO->second.size() == 1) 12357 continue; 12358 12359 // C++ [class.virtual]p2: 12360 // In a derived class, if a virtual member function of a base 12361 // class subobject has more than one final overrider the 12362 // program is ill-formed. 12363 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12364 << (const NamedDecl *)M->first << Record; 12365 Diag(M->first->getLocation(), 12366 diag::note_overridden_virtual_function); 12367 for (OverridingMethods::overriding_iterator 12368 OM = SO->second.begin(), 12369 OMEnd = SO->second.end(); 12370 OM != OMEnd; ++OM) 12371 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12372 << (const NamedDecl *)M->first << OM->Method->getParent(); 12373 12374 Record->setInvalidDecl(); 12375 } 12376 } 12377 CXXRecord->completeDefinition(&FinalOverriders); 12378 Completed = true; 12379 } 12380 } 12381 } 12382 } 12383 12384 if (!Completed) 12385 Record->completeDefinition(); 12386 12387 if (Record->hasAttrs()) { 12388 CheckAlignasUnderalignment(Record); 12389 12390 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12391 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12392 IA->getRange(), IA->getBestCase(), 12393 IA->getSemanticSpelling()); 12394 } 12395 12396 // Check if the structure/union declaration is a type that can have zero 12397 // size in C. For C this is a language extension, for C++ it may cause 12398 // compatibility problems. 12399 bool CheckForZeroSize; 12400 if (!getLangOpts().CPlusPlus) { 12401 CheckForZeroSize = true; 12402 } else { 12403 // For C++ filter out types that cannot be referenced in C code. 12404 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12405 CheckForZeroSize = 12406 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12407 !CXXRecord->isDependentType() && 12408 CXXRecord->isCLike(); 12409 } 12410 if (CheckForZeroSize) { 12411 bool ZeroSize = true; 12412 bool IsEmpty = true; 12413 unsigned NonBitFields = 0; 12414 for (RecordDecl::field_iterator I = Record->field_begin(), 12415 E = Record->field_end(); 12416 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12417 IsEmpty = false; 12418 if (I->isUnnamedBitfield()) { 12419 if (I->getBitWidthValue(Context) > 0) 12420 ZeroSize = false; 12421 } else { 12422 ++NonBitFields; 12423 QualType FieldType = I->getType(); 12424 if (FieldType->isIncompleteType() || 12425 !Context.getTypeSizeInChars(FieldType).isZero()) 12426 ZeroSize = false; 12427 } 12428 } 12429 12430 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12431 // allowed in C++, but warn if its declaration is inside 12432 // extern "C" block. 12433 if (ZeroSize) { 12434 Diag(RecLoc, getLangOpts().CPlusPlus ? 12435 diag::warn_zero_size_struct_union_in_extern_c : 12436 diag::warn_zero_size_struct_union_compat) 12437 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12438 } 12439 12440 // Structs without named members are extension in C (C99 6.7.2.1p7), 12441 // but are accepted by GCC. 12442 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12443 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12444 diag::ext_no_named_members_in_struct_union) 12445 << Record->isUnion(); 12446 } 12447 } 12448 } else { 12449 ObjCIvarDecl **ClsFields = 12450 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12451 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12452 ID->setEndOfDefinitionLoc(RBrac); 12453 // Add ivar's to class's DeclContext. 12454 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12455 ClsFields[i]->setLexicalDeclContext(ID); 12456 ID->addDecl(ClsFields[i]); 12457 } 12458 // Must enforce the rule that ivars in the base classes may not be 12459 // duplicates. 12460 if (ID->getSuperClass()) 12461 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12462 } else if (ObjCImplementationDecl *IMPDecl = 12463 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12464 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12465 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12466 // Ivar declared in @implementation never belongs to the implementation. 12467 // Only it is in implementation's lexical context. 12468 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12469 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12470 IMPDecl->setIvarLBraceLoc(LBrac); 12471 IMPDecl->setIvarRBraceLoc(RBrac); 12472 } else if (ObjCCategoryDecl *CDecl = 12473 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12474 // case of ivars in class extension; all other cases have been 12475 // reported as errors elsewhere. 12476 // FIXME. Class extension does not have a LocEnd field. 12477 // CDecl->setLocEnd(RBrac); 12478 // Add ivar's to class extension's DeclContext. 12479 // Diagnose redeclaration of private ivars. 12480 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12481 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12482 if (IDecl) { 12483 if (const ObjCIvarDecl *ClsIvar = 12484 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12485 Diag(ClsFields[i]->getLocation(), 12486 diag::err_duplicate_ivar_declaration); 12487 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12488 continue; 12489 } 12490 for (const auto *Ext : IDecl->known_extensions()) { 12491 if (const ObjCIvarDecl *ClsExtIvar 12492 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 12493 Diag(ClsFields[i]->getLocation(), 12494 diag::err_duplicate_ivar_declaration); 12495 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 12496 continue; 12497 } 12498 } 12499 } 12500 ClsFields[i]->setLexicalDeclContext(CDecl); 12501 CDecl->addDecl(ClsFields[i]); 12502 } 12503 CDecl->setIvarLBraceLoc(LBrac); 12504 CDecl->setIvarRBraceLoc(RBrac); 12505 } 12506 } 12507 12508 if (Attr) 12509 ProcessDeclAttributeList(S, Record, Attr); 12510 } 12511 12512 /// \brief Determine whether the given integral value is representable within 12513 /// the given type T. 12514 static bool isRepresentableIntegerValue(ASTContext &Context, 12515 llvm::APSInt &Value, 12516 QualType T) { 12517 assert(T->isIntegralType(Context) && "Integral type required!"); 12518 unsigned BitWidth = Context.getIntWidth(T); 12519 12520 if (Value.isUnsigned() || Value.isNonNegative()) { 12521 if (T->isSignedIntegerOrEnumerationType()) 12522 --BitWidth; 12523 return Value.getActiveBits() <= BitWidth; 12524 } 12525 return Value.getMinSignedBits() <= BitWidth; 12526 } 12527 12528 // \brief Given an integral type, return the next larger integral type 12529 // (or a NULL type of no such type exists). 12530 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 12531 // FIXME: Int128/UInt128 support, which also needs to be introduced into 12532 // enum checking below. 12533 assert(T->isIntegralType(Context) && "Integral type required!"); 12534 const unsigned NumTypes = 4; 12535 QualType SignedIntegralTypes[NumTypes] = { 12536 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 12537 }; 12538 QualType UnsignedIntegralTypes[NumTypes] = { 12539 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 12540 Context.UnsignedLongLongTy 12541 }; 12542 12543 unsigned BitWidth = Context.getTypeSize(T); 12544 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 12545 : UnsignedIntegralTypes; 12546 for (unsigned I = 0; I != NumTypes; ++I) 12547 if (Context.getTypeSize(Types[I]) > BitWidth) 12548 return Types[I]; 12549 12550 return QualType(); 12551 } 12552 12553 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 12554 EnumConstantDecl *LastEnumConst, 12555 SourceLocation IdLoc, 12556 IdentifierInfo *Id, 12557 Expr *Val) { 12558 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12559 llvm::APSInt EnumVal(IntWidth); 12560 QualType EltTy; 12561 12562 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 12563 Val = nullptr; 12564 12565 if (Val) 12566 Val = DefaultLvalueConversion(Val).get(); 12567 12568 if (Val) { 12569 if (Enum->isDependentType() || Val->isTypeDependent()) 12570 EltTy = Context.DependentTy; 12571 else { 12572 SourceLocation ExpLoc; 12573 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 12574 !getLangOpts().MSVCCompat) { 12575 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 12576 // constant-expression in the enumerator-definition shall be a converted 12577 // constant expression of the underlying type. 12578 EltTy = Enum->getIntegerType(); 12579 ExprResult Converted = 12580 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 12581 CCEK_Enumerator); 12582 if (Converted.isInvalid()) 12583 Val = nullptr; 12584 else 12585 Val = Converted.get(); 12586 } else if (!Val->isValueDependent() && 12587 !(Val = VerifyIntegerConstantExpression(Val, 12588 &EnumVal).get())) { 12589 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 12590 } else { 12591 if (Enum->isFixed()) { 12592 EltTy = Enum->getIntegerType(); 12593 12594 // In Obj-C and Microsoft mode, require the enumeration value to be 12595 // representable in the underlying type of the enumeration. In C++11, 12596 // we perform a non-narrowing conversion as part of converted constant 12597 // expression checking. 12598 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12599 if (getLangOpts().MSVCCompat) { 12600 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 12601 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 12602 } else 12603 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 12604 } else 12605 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 12606 } else if (getLangOpts().CPlusPlus) { 12607 // C++11 [dcl.enum]p5: 12608 // If the underlying type is not fixed, the type of each enumerator 12609 // is the type of its initializing value: 12610 // - If an initializer is specified for an enumerator, the 12611 // initializing value has the same type as the expression. 12612 EltTy = Val->getType(); 12613 } else { 12614 // C99 6.7.2.2p2: 12615 // The expression that defines the value of an enumeration constant 12616 // shall be an integer constant expression that has a value 12617 // representable as an int. 12618 12619 // Complain if the value is not representable in an int. 12620 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 12621 Diag(IdLoc, diag::ext_enum_value_not_int) 12622 << EnumVal.toString(10) << Val->getSourceRange() 12623 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 12624 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 12625 // Force the type of the expression to 'int'. 12626 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 12627 } 12628 EltTy = Val->getType(); 12629 } 12630 } 12631 } 12632 } 12633 12634 if (!Val) { 12635 if (Enum->isDependentType()) 12636 EltTy = Context.DependentTy; 12637 else if (!LastEnumConst) { 12638 // C++0x [dcl.enum]p5: 12639 // If the underlying type is not fixed, the type of each enumerator 12640 // is the type of its initializing value: 12641 // - If no initializer is specified for the first enumerator, the 12642 // initializing value has an unspecified integral type. 12643 // 12644 // GCC uses 'int' for its unspecified integral type, as does 12645 // C99 6.7.2.2p3. 12646 if (Enum->isFixed()) { 12647 EltTy = Enum->getIntegerType(); 12648 } 12649 else { 12650 EltTy = Context.IntTy; 12651 } 12652 } else { 12653 // Assign the last value + 1. 12654 EnumVal = LastEnumConst->getInitVal(); 12655 ++EnumVal; 12656 EltTy = LastEnumConst->getType(); 12657 12658 // Check for overflow on increment. 12659 if (EnumVal < LastEnumConst->getInitVal()) { 12660 // C++0x [dcl.enum]p5: 12661 // If the underlying type is not fixed, the type of each enumerator 12662 // is the type of its initializing value: 12663 // 12664 // - Otherwise the type of the initializing value is the same as 12665 // the type of the initializing value of the preceding enumerator 12666 // unless the incremented value is not representable in that type, 12667 // in which case the type is an unspecified integral type 12668 // sufficient to contain the incremented value. If no such type 12669 // exists, the program is ill-formed. 12670 QualType T = getNextLargerIntegralType(Context, EltTy); 12671 if (T.isNull() || Enum->isFixed()) { 12672 // There is no integral type larger enough to represent this 12673 // value. Complain, then allow the value to wrap around. 12674 EnumVal = LastEnumConst->getInitVal(); 12675 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 12676 ++EnumVal; 12677 if (Enum->isFixed()) 12678 // When the underlying type is fixed, this is ill-formed. 12679 Diag(IdLoc, diag::err_enumerator_wrapped) 12680 << EnumVal.toString(10) 12681 << EltTy; 12682 else 12683 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 12684 << EnumVal.toString(10); 12685 } else { 12686 EltTy = T; 12687 } 12688 12689 // Retrieve the last enumerator's value, extent that type to the 12690 // type that is supposed to be large enough to represent the incremented 12691 // value, then increment. 12692 EnumVal = LastEnumConst->getInitVal(); 12693 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12694 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 12695 ++EnumVal; 12696 12697 // If we're not in C++, diagnose the overflow of enumerator values, 12698 // which in C99 means that the enumerator value is not representable in 12699 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 12700 // permits enumerator values that are representable in some larger 12701 // integral type. 12702 if (!getLangOpts().CPlusPlus && !T.isNull()) 12703 Diag(IdLoc, diag::warn_enum_value_overflow); 12704 } else if (!getLangOpts().CPlusPlus && 12705 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 12706 // Enforce C99 6.7.2.2p2 even when we compute the next value. 12707 Diag(IdLoc, diag::ext_enum_value_not_int) 12708 << EnumVal.toString(10) << 1; 12709 } 12710 } 12711 } 12712 12713 if (!EltTy->isDependentType()) { 12714 // Make the enumerator value match the signedness and size of the 12715 // enumerator's type. 12716 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 12717 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 12718 } 12719 12720 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 12721 Val, EnumVal); 12722 } 12723 12724 12725 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 12726 SourceLocation IdLoc, IdentifierInfo *Id, 12727 AttributeList *Attr, 12728 SourceLocation EqualLoc, Expr *Val) { 12729 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 12730 EnumConstantDecl *LastEnumConst = 12731 cast_or_null<EnumConstantDecl>(lastEnumConst); 12732 12733 // The scope passed in may not be a decl scope. Zip up the scope tree until 12734 // we find one that is. 12735 S = getNonFieldDeclScope(S); 12736 12737 // Verify that there isn't already something declared with this name in this 12738 // scope. 12739 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 12740 ForRedeclaration); 12741 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12742 // Maybe we will complain about the shadowed template parameter. 12743 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 12744 // Just pretend that we didn't see the previous declaration. 12745 PrevDecl = nullptr; 12746 } 12747 12748 if (PrevDecl) { 12749 // When in C++, we may get a TagDecl with the same name; in this case the 12750 // enum constant will 'hide' the tag. 12751 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 12752 "Received TagDecl when not in C++!"); 12753 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 12754 if (isa<EnumConstantDecl>(PrevDecl)) 12755 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 12756 else 12757 Diag(IdLoc, diag::err_redefinition) << Id; 12758 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12759 return nullptr; 12760 } 12761 } 12762 12763 // C++ [class.mem]p15: 12764 // If T is the name of a class, then each of the following shall have a name 12765 // different from T: 12766 // - every enumerator of every member of class T that is an unscoped 12767 // enumerated type 12768 if (CXXRecordDecl *Record 12769 = dyn_cast<CXXRecordDecl>( 12770 TheEnumDecl->getDeclContext()->getRedeclContext())) 12771 if (!TheEnumDecl->isScoped() && 12772 Record->getIdentifier() && Record->getIdentifier() == Id) 12773 Diag(IdLoc, diag::err_member_name_of_class) << Id; 12774 12775 EnumConstantDecl *New = 12776 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 12777 12778 if (New) { 12779 // Process attributes. 12780 if (Attr) ProcessDeclAttributeList(S, New, Attr); 12781 12782 // Register this decl in the current scope stack. 12783 New->setAccess(TheEnumDecl->getAccess()); 12784 PushOnScopeChains(New, S); 12785 } 12786 12787 ActOnDocumentableDecl(New); 12788 12789 return New; 12790 } 12791 12792 // Returns true when the enum initial expression does not trigger the 12793 // duplicate enum warning. A few common cases are exempted as follows: 12794 // Element2 = Element1 12795 // Element2 = Element1 + 1 12796 // Element2 = Element1 - 1 12797 // Where Element2 and Element1 are from the same enum. 12798 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 12799 Expr *InitExpr = ECD->getInitExpr(); 12800 if (!InitExpr) 12801 return true; 12802 InitExpr = InitExpr->IgnoreImpCasts(); 12803 12804 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 12805 if (!BO->isAdditiveOp()) 12806 return true; 12807 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 12808 if (!IL) 12809 return true; 12810 if (IL->getValue() != 1) 12811 return true; 12812 12813 InitExpr = BO->getLHS(); 12814 } 12815 12816 // This checks if the elements are from the same enum. 12817 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 12818 if (!DRE) 12819 return true; 12820 12821 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 12822 if (!EnumConstant) 12823 return true; 12824 12825 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 12826 Enum) 12827 return true; 12828 12829 return false; 12830 } 12831 12832 struct DupKey { 12833 int64_t val; 12834 bool isTombstoneOrEmptyKey; 12835 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 12836 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 12837 }; 12838 12839 static DupKey GetDupKey(const llvm::APSInt& Val) { 12840 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 12841 false); 12842 } 12843 12844 struct DenseMapInfoDupKey { 12845 static DupKey getEmptyKey() { return DupKey(0, true); } 12846 static DupKey getTombstoneKey() { return DupKey(1, true); } 12847 static unsigned getHashValue(const DupKey Key) { 12848 return (unsigned)(Key.val * 37); 12849 } 12850 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 12851 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 12852 LHS.val == RHS.val; 12853 } 12854 }; 12855 12856 // Emits a warning when an element is implicitly set a value that 12857 // a previous element has already been set to. 12858 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 12859 EnumDecl *Enum, 12860 QualType EnumType) { 12861 if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values, 12862 Enum->getLocation()) == 12863 DiagnosticsEngine::Ignored) 12864 return; 12865 // Avoid anonymous enums 12866 if (!Enum->getIdentifier()) 12867 return; 12868 12869 // Only check for small enums. 12870 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 12871 return; 12872 12873 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 12874 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 12875 12876 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 12877 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 12878 ValueToVectorMap; 12879 12880 DuplicatesVector DupVector; 12881 ValueToVectorMap EnumMap; 12882 12883 // Populate the EnumMap with all values represented by enum constants without 12884 // an initialier. 12885 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12886 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 12887 12888 // Null EnumConstantDecl means a previous diagnostic has been emitted for 12889 // this constant. Skip this enum since it may be ill-formed. 12890 if (!ECD) { 12891 return; 12892 } 12893 12894 if (ECD->getInitExpr()) 12895 continue; 12896 12897 DupKey Key = GetDupKey(ECD->getInitVal()); 12898 DeclOrVector &Entry = EnumMap[Key]; 12899 12900 // First time encountering this value. 12901 if (Entry.isNull()) 12902 Entry = ECD; 12903 } 12904 12905 // Create vectors for any values that has duplicates. 12906 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12907 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 12908 if (!ValidDuplicateEnum(ECD, Enum)) 12909 continue; 12910 12911 DupKey Key = GetDupKey(ECD->getInitVal()); 12912 12913 DeclOrVector& Entry = EnumMap[Key]; 12914 if (Entry.isNull()) 12915 continue; 12916 12917 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 12918 // Ensure constants are different. 12919 if (D == ECD) 12920 continue; 12921 12922 // Create new vector and push values onto it. 12923 ECDVector *Vec = new ECDVector(); 12924 Vec->push_back(D); 12925 Vec->push_back(ECD); 12926 12927 // Update entry to point to the duplicates vector. 12928 Entry = Vec; 12929 12930 // Store the vector somewhere we can consult later for quick emission of 12931 // diagnostics. 12932 DupVector.push_back(Vec); 12933 continue; 12934 } 12935 12936 ECDVector *Vec = Entry.get<ECDVector*>(); 12937 // Make sure constants are not added more than once. 12938 if (*Vec->begin() == ECD) 12939 continue; 12940 12941 Vec->push_back(ECD); 12942 } 12943 12944 // Emit diagnostics. 12945 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 12946 DupVectorEnd = DupVector.end(); 12947 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 12948 ECDVector *Vec = *DupVectorIter; 12949 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 12950 12951 // Emit warning for one enum constant. 12952 ECDVector::iterator I = Vec->begin(); 12953 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 12954 << (*I)->getName() << (*I)->getInitVal().toString(10) 12955 << (*I)->getSourceRange(); 12956 ++I; 12957 12958 // Emit one note for each of the remaining enum constants with 12959 // the same value. 12960 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 12961 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 12962 << (*I)->getName() << (*I)->getInitVal().toString(10) 12963 << (*I)->getSourceRange(); 12964 delete Vec; 12965 } 12966 } 12967 12968 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 12969 SourceLocation RBraceLoc, Decl *EnumDeclX, 12970 ArrayRef<Decl *> Elements, 12971 Scope *S, AttributeList *Attr) { 12972 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 12973 QualType EnumType = Context.getTypeDeclType(Enum); 12974 12975 if (Attr) 12976 ProcessDeclAttributeList(S, Enum, Attr); 12977 12978 if (Enum->isDependentType()) { 12979 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 12980 EnumConstantDecl *ECD = 12981 cast_or_null<EnumConstantDecl>(Elements[i]); 12982 if (!ECD) continue; 12983 12984 ECD->setType(EnumType); 12985 } 12986 12987 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 12988 return; 12989 } 12990 12991 // TODO: If the result value doesn't fit in an int, it must be a long or long 12992 // long value. ISO C does not support this, but GCC does as an extension, 12993 // emit a warning. 12994 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 12995 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 12996 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 12997 12998 // Verify that all the values are okay, compute the size of the values, and 12999 // reverse the list. 13000 unsigned NumNegativeBits = 0; 13001 unsigned NumPositiveBits = 0; 13002 13003 // Keep track of whether all elements have type int. 13004 bool AllElementsInt = true; 13005 13006 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13007 EnumConstantDecl *ECD = 13008 cast_or_null<EnumConstantDecl>(Elements[i]); 13009 if (!ECD) continue; // Already issued a diagnostic. 13010 13011 const llvm::APSInt &InitVal = ECD->getInitVal(); 13012 13013 // Keep track of the size of positive and negative values. 13014 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13015 NumPositiveBits = std::max(NumPositiveBits, 13016 (unsigned)InitVal.getActiveBits()); 13017 else 13018 NumNegativeBits = std::max(NumNegativeBits, 13019 (unsigned)InitVal.getMinSignedBits()); 13020 13021 // Keep track of whether every enum element has type int (very commmon). 13022 if (AllElementsInt) 13023 AllElementsInt = ECD->getType() == Context.IntTy; 13024 } 13025 13026 // Figure out the type that should be used for this enum. 13027 QualType BestType; 13028 unsigned BestWidth; 13029 13030 // C++0x N3000 [conv.prom]p3: 13031 // An rvalue of an unscoped enumeration type whose underlying 13032 // type is not fixed can be converted to an rvalue of the first 13033 // of the following types that can represent all the values of 13034 // the enumeration: int, unsigned int, long int, unsigned long 13035 // int, long long int, or unsigned long long int. 13036 // C99 6.4.4.3p2: 13037 // An identifier declared as an enumeration constant has type int. 13038 // The C99 rule is modified by a gcc extension 13039 QualType BestPromotionType; 13040 13041 bool Packed = Enum->hasAttr<PackedAttr>(); 13042 // -fshort-enums is the equivalent to specifying the packed attribute on all 13043 // enum definitions. 13044 if (LangOpts.ShortEnums) 13045 Packed = true; 13046 13047 if (Enum->isFixed()) { 13048 BestType = Enum->getIntegerType(); 13049 if (BestType->isPromotableIntegerType()) 13050 BestPromotionType = Context.getPromotedIntegerType(BestType); 13051 else 13052 BestPromotionType = BestType; 13053 // We don't need to set BestWidth, because BestType is going to be the type 13054 // of the enumerators, but we do anyway because otherwise some compilers 13055 // warn that it might be used uninitialized. 13056 BestWidth = CharWidth; 13057 } 13058 else if (NumNegativeBits) { 13059 // If there is a negative value, figure out the smallest integer type (of 13060 // int/long/longlong) that fits. 13061 // If it's packed, check also if it fits a char or a short. 13062 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13063 BestType = Context.SignedCharTy; 13064 BestWidth = CharWidth; 13065 } else if (Packed && NumNegativeBits <= ShortWidth && 13066 NumPositiveBits < ShortWidth) { 13067 BestType = Context.ShortTy; 13068 BestWidth = ShortWidth; 13069 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13070 BestType = Context.IntTy; 13071 BestWidth = IntWidth; 13072 } else { 13073 BestWidth = Context.getTargetInfo().getLongWidth(); 13074 13075 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13076 BestType = Context.LongTy; 13077 } else { 13078 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13079 13080 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13081 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13082 BestType = Context.LongLongTy; 13083 } 13084 } 13085 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13086 } else { 13087 // If there is no negative value, figure out the smallest type that fits 13088 // all of the enumerator values. 13089 // If it's packed, check also if it fits a char or a short. 13090 if (Packed && NumPositiveBits <= CharWidth) { 13091 BestType = Context.UnsignedCharTy; 13092 BestPromotionType = Context.IntTy; 13093 BestWidth = CharWidth; 13094 } else if (Packed && NumPositiveBits <= ShortWidth) { 13095 BestType = Context.UnsignedShortTy; 13096 BestPromotionType = Context.IntTy; 13097 BestWidth = ShortWidth; 13098 } else if (NumPositiveBits <= IntWidth) { 13099 BestType = Context.UnsignedIntTy; 13100 BestWidth = IntWidth; 13101 BestPromotionType 13102 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13103 ? Context.UnsignedIntTy : Context.IntTy; 13104 } else if (NumPositiveBits <= 13105 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13106 BestType = Context.UnsignedLongTy; 13107 BestPromotionType 13108 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13109 ? Context.UnsignedLongTy : Context.LongTy; 13110 } else { 13111 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13112 assert(NumPositiveBits <= BestWidth && 13113 "How could an initializer get larger than ULL?"); 13114 BestType = Context.UnsignedLongLongTy; 13115 BestPromotionType 13116 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13117 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13118 } 13119 } 13120 13121 // Loop over all of the enumerator constants, changing their types to match 13122 // the type of the enum if needed. 13123 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13124 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13125 if (!ECD) continue; // Already issued a diagnostic. 13126 13127 // Standard C says the enumerators have int type, but we allow, as an 13128 // extension, the enumerators to be larger than int size. If each 13129 // enumerator value fits in an int, type it as an int, otherwise type it the 13130 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13131 // that X has type 'int', not 'unsigned'. 13132 13133 // Determine whether the value fits into an int. 13134 llvm::APSInt InitVal = ECD->getInitVal(); 13135 13136 // If it fits into an integer type, force it. Otherwise force it to match 13137 // the enum decl type. 13138 QualType NewTy; 13139 unsigned NewWidth; 13140 bool NewSign; 13141 if (!getLangOpts().CPlusPlus && 13142 !Enum->isFixed() && 13143 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13144 NewTy = Context.IntTy; 13145 NewWidth = IntWidth; 13146 NewSign = true; 13147 } else if (ECD->getType() == BestType) { 13148 // Already the right type! 13149 if (getLangOpts().CPlusPlus) 13150 // C++ [dcl.enum]p4: Following the closing brace of an 13151 // enum-specifier, each enumerator has the type of its 13152 // enumeration. 13153 ECD->setType(EnumType); 13154 continue; 13155 } else { 13156 NewTy = BestType; 13157 NewWidth = BestWidth; 13158 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13159 } 13160 13161 // Adjust the APSInt value. 13162 InitVal = InitVal.extOrTrunc(NewWidth); 13163 InitVal.setIsSigned(NewSign); 13164 ECD->setInitVal(InitVal); 13165 13166 // Adjust the Expr initializer and type. 13167 if (ECD->getInitExpr() && 13168 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13169 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13170 CK_IntegralCast, 13171 ECD->getInitExpr(), 13172 /*base paths*/ nullptr, 13173 VK_RValue)); 13174 if (getLangOpts().CPlusPlus) 13175 // C++ [dcl.enum]p4: Following the closing brace of an 13176 // enum-specifier, each enumerator has the type of its 13177 // enumeration. 13178 ECD->setType(EnumType); 13179 else 13180 ECD->setType(NewTy); 13181 } 13182 13183 Enum->completeDefinition(BestType, BestPromotionType, 13184 NumPositiveBits, NumNegativeBits); 13185 13186 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13187 13188 // Now that the enum type is defined, ensure it's not been underaligned. 13189 if (Enum->hasAttrs()) 13190 CheckAlignasUnderalignment(Enum); 13191 } 13192 13193 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13194 SourceLocation StartLoc, 13195 SourceLocation EndLoc) { 13196 StringLiteral *AsmString = cast<StringLiteral>(expr); 13197 13198 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13199 AsmString, StartLoc, 13200 EndLoc); 13201 CurContext->addDecl(New); 13202 return New; 13203 } 13204 13205 static void checkModuleImportContext(Sema &S, Module *M, 13206 SourceLocation ImportLoc, 13207 DeclContext *DC) { 13208 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13209 switch (LSD->getLanguage()) { 13210 case LinkageSpecDecl::lang_c: 13211 if (!M->IsExternC) { 13212 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13213 << M->getFullModuleName(); 13214 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13215 return; 13216 } 13217 break; 13218 case LinkageSpecDecl::lang_cxx: 13219 break; 13220 } 13221 DC = LSD->getParent(); 13222 } 13223 13224 while (isa<LinkageSpecDecl>(DC)) 13225 DC = DC->getParent(); 13226 if (!isa<TranslationUnitDecl>(DC)) { 13227 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13228 << M->getFullModuleName() << DC; 13229 S.Diag(cast<Decl>(DC)->getLocStart(), 13230 diag::note_module_import_not_at_top_level) 13231 << DC; 13232 } 13233 } 13234 13235 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13236 SourceLocation ImportLoc, 13237 ModuleIdPath Path) { 13238 Module *Mod = 13239 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13240 /*IsIncludeDirective=*/false); 13241 if (!Mod) 13242 return true; 13243 13244 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13245 13246 // FIXME: we should support importing a submodule within a different submodule 13247 // of the same top-level module. Until we do, make it an error rather than 13248 // silently ignoring the import. 13249 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13250 Diag(ImportLoc, diag::err_module_self_import) 13251 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13252 13253 SmallVector<SourceLocation, 2> IdentifierLocs; 13254 Module *ModCheck = Mod; 13255 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13256 // If we've run out of module parents, just drop the remaining identifiers. 13257 // We need the length to be consistent. 13258 if (!ModCheck) 13259 break; 13260 ModCheck = ModCheck->Parent; 13261 13262 IdentifierLocs.push_back(Path[I].second); 13263 } 13264 13265 ImportDecl *Import = ImportDecl::Create(Context, 13266 Context.getTranslationUnitDecl(), 13267 AtLoc.isValid()? AtLoc : ImportLoc, 13268 Mod, IdentifierLocs); 13269 Context.getTranslationUnitDecl()->addDecl(Import); 13270 return Import; 13271 } 13272 13273 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13274 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13275 13276 // FIXME: Should we synthesize an ImportDecl here? 13277 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13278 /*Complain=*/true); 13279 } 13280 13281 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13282 Module *Mod) { 13283 // Bail if we're not allowed to implicitly import a module here. 13284 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13285 return; 13286 13287 // Create the implicit import declaration. 13288 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13289 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13290 Loc, Mod, Loc); 13291 TU->addDecl(ImportD); 13292 Consumer.HandleImplicitImportDecl(ImportD); 13293 13294 // Make the module visible. 13295 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13296 /*Complain=*/false); 13297 } 13298 13299 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13300 IdentifierInfo* AliasName, 13301 SourceLocation PragmaLoc, 13302 SourceLocation NameLoc, 13303 SourceLocation AliasNameLoc) { 13304 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13305 LookupOrdinaryName); 13306 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13307 AliasName->getName(), 0); 13308 13309 if (PrevDecl) 13310 PrevDecl->addAttr(Attr); 13311 else 13312 (void)ExtnameUndeclaredIdentifiers.insert( 13313 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13314 } 13315 13316 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13317 SourceLocation PragmaLoc, 13318 SourceLocation NameLoc) { 13319 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13320 13321 if (PrevDecl) { 13322 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13323 } else { 13324 (void)WeakUndeclaredIdentifiers.insert( 13325 std::pair<IdentifierInfo*,WeakInfo> 13326 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 13327 } 13328 } 13329 13330 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13331 IdentifierInfo* AliasName, 13332 SourceLocation PragmaLoc, 13333 SourceLocation NameLoc, 13334 SourceLocation AliasNameLoc) { 13335 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13336 LookupOrdinaryName); 13337 WeakInfo W = WeakInfo(Name, NameLoc); 13338 13339 if (PrevDecl) { 13340 if (!PrevDecl->hasAttr<AliasAttr>()) 13341 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13342 DeclApplyPragmaWeak(TUScope, ND, W); 13343 } else { 13344 (void)WeakUndeclaredIdentifiers.insert( 13345 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13346 } 13347 } 13348 13349 Decl *Sema::getObjCDeclContext() const { 13350 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13351 } 13352 13353 AvailabilityResult Sema::getCurContextAvailability() const { 13354 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13355 // If we are within an Objective-C method, we should consult 13356 // both the availability of the method as well as the 13357 // enclosing class. If the class is (say) deprecated, 13358 // the entire method is considered deprecated from the 13359 // purpose of checking if the current context is deprecated. 13360 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13361 AvailabilityResult R = MD->getAvailability(); 13362 if (R != AR_Available) 13363 return R; 13364 D = MD->getClassInterface(); 13365 } 13366 // If we are within an Objective-c @implementation, it 13367 // gets the same availability context as the @interface. 13368 else if (const ObjCImplementationDecl *ID = 13369 dyn_cast<ObjCImplementationDecl>(D)) { 13370 D = ID->getClassInterface(); 13371 } 13372 return D->getAvailability(); 13373 } 13374