1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/NonTrivialTypeVisitor.h" 28 #include "clang/AST/Randstruct.h" 29 #include "clang/AST/StmtCXX.h" 30 #include "clang/AST/Type.h" 31 #include "clang/Basic/Builtins.h" 32 #include "clang/Basic/HLSLRuntime.h" 33 #include "clang/Basic/PartialDiagnostic.h" 34 #include "clang/Basic/SourceManager.h" 35 #include "clang/Basic/TargetInfo.h" 36 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 37 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 38 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 39 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 40 #include "clang/Sema/CXXFieldCollector.h" 41 #include "clang/Sema/DeclSpec.h" 42 #include "clang/Sema/DelayedDiagnostic.h" 43 #include "clang/Sema/Initialization.h" 44 #include "clang/Sema/Lookup.h" 45 #include "clang/Sema/ParsedTemplate.h" 46 #include "clang/Sema/Scope.h" 47 #include "clang/Sema/ScopeInfo.h" 48 #include "clang/Sema/SemaInternal.h" 49 #include "clang/Sema/Template.h" 50 #include "llvm/ADT/SmallString.h" 51 #include "llvm/ADT/StringExtras.h" 52 #include "llvm/TargetParser/Triple.h" 53 #include <algorithm> 54 #include <cstring> 55 #include <functional> 56 #include <optional> 57 #include <unordered_map> 58 59 using namespace clang; 60 using namespace sema; 61 62 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 63 if (OwnedType) { 64 Decl *Group[2] = { OwnedType, Ptr }; 65 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 66 } 67 68 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 69 } 70 71 namespace { 72 73 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 74 public: 75 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 76 bool AllowTemplates = false, 77 bool AllowNonTemplates = true) 78 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 79 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 80 WantExpressionKeywords = false; 81 WantCXXNamedCasts = false; 82 WantRemainingKeywords = false; 83 } 84 85 bool ValidateCandidate(const TypoCorrection &candidate) override { 86 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 87 if (!AllowInvalidDecl && ND->isInvalidDecl()) 88 return false; 89 90 if (getAsTypeTemplateDecl(ND)) 91 return AllowTemplates; 92 93 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 94 if (!IsType) 95 return false; 96 97 if (AllowNonTemplates) 98 return true; 99 100 // An injected-class-name of a class template (specialization) is valid 101 // as a template or as a non-template. 102 if (AllowTemplates) { 103 auto *RD = dyn_cast<CXXRecordDecl>(ND); 104 if (!RD || !RD->isInjectedClassName()) 105 return false; 106 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 107 return RD->getDescribedClassTemplate() || 108 isa<ClassTemplateSpecializationDecl>(RD); 109 } 110 111 return false; 112 } 113 114 return !WantClassName && candidate.isKeyword(); 115 } 116 117 std::unique_ptr<CorrectionCandidateCallback> clone() override { 118 return std::make_unique<TypeNameValidatorCCC>(*this); 119 } 120 121 private: 122 bool AllowInvalidDecl; 123 bool WantClassName; 124 bool AllowTemplates; 125 bool AllowNonTemplates; 126 }; 127 128 } // end anonymous namespace 129 130 /// Determine whether the token kind starts a simple-type-specifier. 131 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 132 switch (Kind) { 133 // FIXME: Take into account the current language when deciding whether a 134 // token kind is a valid type specifier 135 case tok::kw_short: 136 case tok::kw_long: 137 case tok::kw___int64: 138 case tok::kw___int128: 139 case tok::kw_signed: 140 case tok::kw_unsigned: 141 case tok::kw_void: 142 case tok::kw_char: 143 case tok::kw_int: 144 case tok::kw_half: 145 case tok::kw_float: 146 case tok::kw_double: 147 case tok::kw___bf16: 148 case tok::kw__Float16: 149 case tok::kw___float128: 150 case tok::kw___ibm128: 151 case tok::kw_wchar_t: 152 case tok::kw_bool: 153 case tok::kw__Accum: 154 case tok::kw__Fract: 155 case tok::kw__Sat: 156 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait: 157 #include "clang/Basic/TransformTypeTraits.def" 158 case tok::kw___auto_type: 159 return true; 160 161 case tok::annot_typename: 162 case tok::kw_char16_t: 163 case tok::kw_char32_t: 164 case tok::kw_typeof: 165 case tok::annot_decltype: 166 case tok::kw_decltype: 167 return getLangOpts().CPlusPlus; 168 169 case tok::kw_char8_t: 170 return getLangOpts().Char8; 171 172 default: 173 break; 174 } 175 176 return false; 177 } 178 179 namespace { 180 enum class UnqualifiedTypeNameLookupResult { 181 NotFound, 182 FoundNonType, 183 FoundType 184 }; 185 } // end anonymous namespace 186 187 /// Tries to perform unqualified lookup of the type decls in bases for 188 /// dependent class. 189 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 190 /// type decl, \a FoundType if only type decls are found. 191 static UnqualifiedTypeNameLookupResult 192 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 193 SourceLocation NameLoc, 194 const CXXRecordDecl *RD) { 195 if (!RD->hasDefinition()) 196 return UnqualifiedTypeNameLookupResult::NotFound; 197 // Look for type decls in base classes. 198 UnqualifiedTypeNameLookupResult FoundTypeDecl = 199 UnqualifiedTypeNameLookupResult::NotFound; 200 for (const auto &Base : RD->bases()) { 201 const CXXRecordDecl *BaseRD = nullptr; 202 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 203 BaseRD = BaseTT->getAsCXXRecordDecl(); 204 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 205 // Look for type decls in dependent base classes that have known primary 206 // templates. 207 if (!TST || !TST->isDependentType()) 208 continue; 209 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 210 if (!TD) 211 continue; 212 if (auto *BasePrimaryTemplate = 213 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 214 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 215 BaseRD = BasePrimaryTemplate; 216 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 217 if (const ClassTemplatePartialSpecializationDecl *PS = 218 CTD->findPartialSpecialization(Base.getType())) 219 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 220 BaseRD = PS; 221 } 222 } 223 } 224 if (BaseRD) { 225 for (NamedDecl *ND : BaseRD->lookup(&II)) { 226 if (!isa<TypeDecl>(ND)) 227 return UnqualifiedTypeNameLookupResult::FoundNonType; 228 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 229 } 230 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 231 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 232 case UnqualifiedTypeNameLookupResult::FoundNonType: 233 return UnqualifiedTypeNameLookupResult::FoundNonType; 234 case UnqualifiedTypeNameLookupResult::FoundType: 235 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 236 break; 237 case UnqualifiedTypeNameLookupResult::NotFound: 238 break; 239 } 240 } 241 } 242 } 243 244 return FoundTypeDecl; 245 } 246 247 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 248 const IdentifierInfo &II, 249 SourceLocation NameLoc) { 250 // Lookup in the parent class template context, if any. 251 const CXXRecordDecl *RD = nullptr; 252 UnqualifiedTypeNameLookupResult FoundTypeDecl = 253 UnqualifiedTypeNameLookupResult::NotFound; 254 for (DeclContext *DC = S.CurContext; 255 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 256 DC = DC->getParent()) { 257 // Look for type decls in dependent base classes that have known primary 258 // templates. 259 RD = dyn_cast<CXXRecordDecl>(DC); 260 if (RD && RD->getDescribedClassTemplate()) 261 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 262 } 263 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 264 return nullptr; 265 266 // We found some types in dependent base classes. Recover as if the user 267 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 268 // lookup during template instantiation. 269 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 270 271 ASTContext &Context = S.Context; 272 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 273 cast<Type>(Context.getRecordType(RD))); 274 QualType T = 275 Context.getDependentNameType(ElaboratedTypeKeyword::Typename, NNS, &II); 276 277 CXXScopeSpec SS; 278 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 279 280 TypeLocBuilder Builder; 281 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 282 DepTL.setNameLoc(NameLoc); 283 DepTL.setElaboratedKeywordLoc(SourceLocation()); 284 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 285 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 286 } 287 288 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 289 static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T, 290 SourceLocation NameLoc, 291 bool WantNontrivialTypeSourceInfo = true) { 292 switch (T->getTypeClass()) { 293 case Type::DeducedTemplateSpecialization: 294 case Type::Enum: 295 case Type::InjectedClassName: 296 case Type::Record: 297 case Type::Typedef: 298 case Type::UnresolvedUsing: 299 case Type::Using: 300 break; 301 // These can never be qualified so an ElaboratedType node 302 // would carry no additional meaning. 303 case Type::ObjCInterface: 304 case Type::ObjCTypeParam: 305 case Type::TemplateTypeParm: 306 return ParsedType::make(T); 307 default: 308 llvm_unreachable("Unexpected Type Class"); 309 } 310 311 if (!SS || SS->isEmpty()) 312 return ParsedType::make(S.Context.getElaboratedType( 313 ElaboratedTypeKeyword::None, nullptr, T, nullptr)); 314 315 QualType ElTy = S.getElaboratedType(ElaboratedTypeKeyword::None, *SS, T); 316 if (!WantNontrivialTypeSourceInfo) 317 return ParsedType::make(ElTy); 318 319 TypeLocBuilder Builder; 320 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 321 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy); 322 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 323 ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context)); 324 return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy)); 325 } 326 327 /// If the identifier refers to a type name within this scope, 328 /// return the declaration of that type. 329 /// 330 /// This routine performs ordinary name lookup of the identifier II 331 /// within the given scope, with optional C++ scope specifier SS, to 332 /// determine whether the name refers to a type. If so, returns an 333 /// opaque pointer (actually a QualType) corresponding to that 334 /// type. Otherwise, returns NULL. 335 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 336 Scope *S, CXXScopeSpec *SS, bool isClassName, 337 bool HasTrailingDot, ParsedType ObjectTypePtr, 338 bool IsCtorOrDtorName, 339 bool WantNontrivialTypeSourceInfo, 340 bool IsClassTemplateDeductionContext, 341 ImplicitTypenameContext AllowImplicitTypename, 342 IdentifierInfo **CorrectedII) { 343 // FIXME: Consider allowing this outside C++1z mode as an extension. 344 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 345 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 346 !isClassName && !HasTrailingDot; 347 348 // Determine where we will perform name lookup. 349 DeclContext *LookupCtx = nullptr; 350 if (ObjectTypePtr) { 351 QualType ObjectType = ObjectTypePtr.get(); 352 if (ObjectType->isRecordType()) 353 LookupCtx = computeDeclContext(ObjectType); 354 } else if (SS && SS->isNotEmpty()) { 355 LookupCtx = computeDeclContext(*SS, false); 356 357 if (!LookupCtx) { 358 if (isDependentScopeSpecifier(*SS)) { 359 // C++ [temp.res]p3: 360 // A qualified-id that refers to a type and in which the 361 // nested-name-specifier depends on a template-parameter (14.6.2) 362 // shall be prefixed by the keyword typename to indicate that the 363 // qualified-id denotes a type, forming an 364 // elaborated-type-specifier (7.1.5.3). 365 // 366 // We therefore do not perform any name lookup if the result would 367 // refer to a member of an unknown specialization. 368 // In C++2a, in several contexts a 'typename' is not required. Also 369 // allow this as an extension. 370 if (AllowImplicitTypename == ImplicitTypenameContext::No && 371 !isClassName && !IsCtorOrDtorName) 372 return nullptr; 373 bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName; 374 if (IsImplicitTypename) { 375 SourceLocation QualifiedLoc = SS->getRange().getBegin(); 376 if (getLangOpts().CPlusPlus20) 377 Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename); 378 else 379 Diag(QualifiedLoc, diag::ext_implicit_typename) 380 << SS->getScopeRep() << II.getName() 381 << FixItHint::CreateInsertion(QualifiedLoc, "typename "); 382 } 383 384 // We know from the grammar that this name refers to a type, 385 // so build a dependent node to describe the type. 386 if (WantNontrivialTypeSourceInfo) 387 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc, 388 (ImplicitTypenameContext)IsImplicitTypename) 389 .get(); 390 391 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 392 QualType T = CheckTypenameType( 393 IsImplicitTypename ? ElaboratedTypeKeyword::Typename 394 : ElaboratedTypeKeyword::None, 395 SourceLocation(), QualifierLoc, II, NameLoc); 396 return ParsedType::make(T); 397 } 398 399 return nullptr; 400 } 401 402 if (!LookupCtx->isDependentContext() && 403 RequireCompleteDeclContext(*SS, LookupCtx)) 404 return nullptr; 405 } 406 407 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 408 // lookup for class-names. 409 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 410 LookupOrdinaryName; 411 LookupResult Result(*this, &II, NameLoc, Kind); 412 if (LookupCtx) { 413 // Perform "qualified" name lookup into the declaration context we 414 // computed, which is either the type of the base of a member access 415 // expression or the declaration context associated with a prior 416 // nested-name-specifier. 417 LookupQualifiedName(Result, LookupCtx); 418 419 if (ObjectTypePtr && Result.empty()) { 420 // C++ [basic.lookup.classref]p3: 421 // If the unqualified-id is ~type-name, the type-name is looked up 422 // in the context of the entire postfix-expression. If the type T of 423 // the object expression is of a class type C, the type-name is also 424 // looked up in the scope of class C. At least one of the lookups shall 425 // find a name that refers to (possibly cv-qualified) T. 426 LookupName(Result, S); 427 } 428 } else { 429 // Perform unqualified name lookup. 430 LookupName(Result, S); 431 432 // For unqualified lookup in a class template in MSVC mode, look into 433 // dependent base classes where the primary class template is known. 434 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 435 if (ParsedType TypeInBase = 436 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 437 return TypeInBase; 438 } 439 } 440 441 NamedDecl *IIDecl = nullptr; 442 UsingShadowDecl *FoundUsingShadow = nullptr; 443 switch (Result.getResultKind()) { 444 case LookupResult::NotFound: 445 if (CorrectedII) { 446 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 447 AllowDeducedTemplate); 448 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 449 S, SS, CCC, CTK_ErrorRecovery); 450 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 451 TemplateTy Template; 452 bool MemberOfUnknownSpecialization; 453 UnqualifiedId TemplateName; 454 TemplateName.setIdentifier(NewII, NameLoc); 455 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 456 CXXScopeSpec NewSS, *NewSSPtr = SS; 457 if (SS && NNS) { 458 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 459 NewSSPtr = &NewSS; 460 } 461 if (Correction && (NNS || NewII != &II) && 462 // Ignore a correction to a template type as the to-be-corrected 463 // identifier is not a template (typo correction for template names 464 // is handled elsewhere). 465 !(getLangOpts().CPlusPlus && NewSSPtr && 466 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 467 Template, MemberOfUnknownSpecialization))) { 468 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 469 isClassName, HasTrailingDot, ObjectTypePtr, 470 IsCtorOrDtorName, 471 WantNontrivialTypeSourceInfo, 472 IsClassTemplateDeductionContext); 473 if (Ty) { 474 diagnoseTypo(Correction, 475 PDiag(diag::err_unknown_type_or_class_name_suggest) 476 << Result.getLookupName() << isClassName); 477 if (SS && NNS) 478 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 479 *CorrectedII = NewII; 480 return Ty; 481 } 482 } 483 } 484 Result.suppressDiagnostics(); 485 return nullptr; 486 case LookupResult::NotFoundInCurrentInstantiation: 487 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { 488 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None, 489 SS->getScopeRep(), &II); 490 TypeLocBuilder TLB; 491 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T); 492 TL.setElaboratedKeywordLoc(SourceLocation()); 493 TL.setQualifierLoc(SS->getWithLocInContext(Context)); 494 TL.setNameLoc(NameLoc); 495 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 496 } 497 [[fallthrough]]; 498 case LookupResult::FoundOverloaded: 499 case LookupResult::FoundUnresolvedValue: 500 Result.suppressDiagnostics(); 501 return nullptr; 502 503 case LookupResult::Ambiguous: 504 // Recover from type-hiding ambiguities by hiding the type. We'll 505 // do the lookup again when looking for an object, and we can 506 // diagnose the error then. If we don't do this, then the error 507 // about hiding the type will be immediately followed by an error 508 // that only makes sense if the identifier was treated like a type. 509 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 510 Result.suppressDiagnostics(); 511 return nullptr; 512 } 513 514 // Look to see if we have a type anywhere in the list of results. 515 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 516 Res != ResEnd; ++Res) { 517 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 518 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 519 RealRes) || 520 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 521 if (!IIDecl || 522 // Make the selection of the recovery decl deterministic. 523 RealRes->getLocation() < IIDecl->getLocation()) { 524 IIDecl = RealRes; 525 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 526 } 527 } 528 } 529 530 if (!IIDecl) { 531 // None of the entities we found is a type, so there is no way 532 // to even assume that the result is a type. In this case, don't 533 // complain about the ambiguity. The parser will either try to 534 // perform this lookup again (e.g., as an object name), which 535 // will produce the ambiguity, or will complain that it expected 536 // a type name. 537 Result.suppressDiagnostics(); 538 return nullptr; 539 } 540 541 // We found a type within the ambiguous lookup; diagnose the 542 // ambiguity and then return that type. This might be the right 543 // answer, or it might not be, but it suppresses any attempt to 544 // perform the name lookup again. 545 break; 546 547 case LookupResult::Found: 548 IIDecl = Result.getFoundDecl(); 549 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 550 break; 551 } 552 553 assert(IIDecl && "Didn't find decl"); 554 555 QualType T; 556 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 557 // C++ [class.qual]p2: A lookup that would find the injected-class-name 558 // instead names the constructors of the class, except when naming a class. 559 // This is ill-formed when we're not actually forming a ctor or dtor name. 560 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 561 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 562 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 563 FoundRD->isInjectedClassName() && 564 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 565 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 566 << &II << /*Type*/1; 567 568 DiagnoseUseOfDecl(IIDecl, NameLoc); 569 570 T = Context.getTypeDeclType(TD); 571 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 572 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 573 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 574 if (!HasTrailingDot) 575 T = Context.getObjCInterfaceType(IDecl); 576 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 577 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 578 (void)DiagnoseUseOfDecl(UD, NameLoc); 579 // Recover with 'int' 580 return ParsedType::make(Context.IntTy); 581 } else if (AllowDeducedTemplate) { 582 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 583 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 584 TemplateName Template = 585 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 586 T = Context.getDeducedTemplateSpecializationType(Template, QualType(), 587 false); 588 // Don't wrap in a further UsingType. 589 FoundUsingShadow = nullptr; 590 } 591 } 592 593 if (T.isNull()) { 594 // If it's not plausibly a type, suppress diagnostics. 595 Result.suppressDiagnostics(); 596 return nullptr; 597 } 598 599 if (FoundUsingShadow) 600 T = Context.getUsingType(FoundUsingShadow, T); 601 602 return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo); 603 } 604 605 // Builds a fake NNS for the given decl context. 606 static NestedNameSpecifier * 607 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 608 for (;; DC = DC->getLookupParent()) { 609 DC = DC->getPrimaryContext(); 610 auto *ND = dyn_cast<NamespaceDecl>(DC); 611 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 612 return NestedNameSpecifier::Create(Context, nullptr, ND); 613 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 614 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 615 RD->getTypeForDecl()); 616 else if (isa<TranslationUnitDecl>(DC)) 617 return NestedNameSpecifier::GlobalSpecifier(Context); 618 } 619 llvm_unreachable("something isn't in TU scope?"); 620 } 621 622 /// Find the parent class with dependent bases of the innermost enclosing method 623 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 624 /// up allowing unqualified dependent type names at class-level, which MSVC 625 /// correctly rejects. 626 static const CXXRecordDecl * 627 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 628 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 629 DC = DC->getPrimaryContext(); 630 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 631 if (MD->getParent()->hasAnyDependentBases()) 632 return MD->getParent(); 633 } 634 return nullptr; 635 } 636 637 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 638 SourceLocation NameLoc, 639 bool IsTemplateTypeArg) { 640 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 641 642 NestedNameSpecifier *NNS = nullptr; 643 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 644 // If we weren't able to parse a default template argument, delay lookup 645 // until instantiation time by making a non-dependent DependentTypeName. We 646 // pretend we saw a NestedNameSpecifier referring to the current scope, and 647 // lookup is retried. 648 // FIXME: This hurts our diagnostic quality, since we get errors like "no 649 // type named 'Foo' in 'current_namespace'" when the user didn't write any 650 // name specifiers. 651 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 652 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 653 } else if (const CXXRecordDecl *RD = 654 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 655 // Build a DependentNameType that will perform lookup into RD at 656 // instantiation time. 657 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 658 RD->getTypeForDecl()); 659 660 // Diagnose that this identifier was undeclared, and retry the lookup during 661 // template instantiation. 662 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 663 << RD; 664 } else { 665 // This is not a situation that we should recover from. 666 return ParsedType(); 667 } 668 669 QualType T = 670 Context.getDependentNameType(ElaboratedTypeKeyword::None, NNS, &II); 671 672 // Build type location information. We synthesized the qualifier, so we have 673 // to build a fake NestedNameSpecifierLoc. 674 NestedNameSpecifierLocBuilder NNSLocBuilder; 675 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 676 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 677 678 TypeLocBuilder Builder; 679 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 680 DepTL.setNameLoc(NameLoc); 681 DepTL.setElaboratedKeywordLoc(SourceLocation()); 682 DepTL.setQualifierLoc(QualifierLoc); 683 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 684 } 685 686 /// isTagName() - This method is called *for error recovery purposes only* 687 /// to determine if the specified name is a valid tag name ("struct foo"). If 688 /// so, this returns the TST for the tag corresponding to it (TST_enum, 689 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 690 /// cases in C where the user forgot to specify the tag. 691 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 692 // Do a tag name lookup in this scope. 693 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 694 LookupName(R, S, false); 695 R.suppressDiagnostics(); 696 if (R.getResultKind() == LookupResult::Found) 697 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 698 switch (TD->getTagKind()) { 699 case TagTypeKind::Struct: 700 return DeclSpec::TST_struct; 701 case TagTypeKind::Interface: 702 return DeclSpec::TST_interface; 703 case TagTypeKind::Union: 704 return DeclSpec::TST_union; 705 case TagTypeKind::Class: 706 return DeclSpec::TST_class; 707 case TagTypeKind::Enum: 708 return DeclSpec::TST_enum; 709 } 710 } 711 712 return DeclSpec::TST_unspecified; 713 } 714 715 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 716 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 717 /// then downgrade the missing typename error to a warning. 718 /// This is needed for MSVC compatibility; Example: 719 /// @code 720 /// template<class T> class A { 721 /// public: 722 /// typedef int TYPE; 723 /// }; 724 /// template<class T> class B : public A<T> { 725 /// public: 726 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 727 /// }; 728 /// @endcode 729 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 730 if (CurContext->isRecord()) { 731 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 732 return true; 733 734 const Type *Ty = SS->getScopeRep()->getAsType(); 735 736 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 737 for (const auto &Base : RD->bases()) 738 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 739 return true; 740 return S->isFunctionPrototypeScope(); 741 } 742 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 743 } 744 745 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 746 SourceLocation IILoc, 747 Scope *S, 748 CXXScopeSpec *SS, 749 ParsedType &SuggestedType, 750 bool IsTemplateName) { 751 // Don't report typename errors for editor placeholders. 752 if (II->isEditorPlaceholder()) 753 return; 754 // We don't have anything to suggest (yet). 755 SuggestedType = nullptr; 756 757 // There may have been a typo in the name of the type. Look up typo 758 // results, in case we have something that we can suggest. 759 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 760 /*AllowTemplates=*/IsTemplateName, 761 /*AllowNonTemplates=*/!IsTemplateName); 762 if (TypoCorrection Corrected = 763 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 764 CCC, CTK_ErrorRecovery)) { 765 // FIXME: Support error recovery for the template-name case. 766 bool CanRecover = !IsTemplateName; 767 if (Corrected.isKeyword()) { 768 // We corrected to a keyword. 769 diagnoseTypo(Corrected, 770 PDiag(IsTemplateName ? diag::err_no_template_suggest 771 : diag::err_unknown_typename_suggest) 772 << II); 773 II = Corrected.getCorrectionAsIdentifierInfo(); 774 } else { 775 // We found a similarly-named type or interface; suggest that. 776 if (!SS || !SS->isSet()) { 777 diagnoseTypo(Corrected, 778 PDiag(IsTemplateName ? diag::err_no_template_suggest 779 : diag::err_unknown_typename_suggest) 780 << II, CanRecover); 781 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 782 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 783 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 784 II->getName().equals(CorrectedStr); 785 diagnoseTypo(Corrected, 786 PDiag(IsTemplateName 787 ? diag::err_no_member_template_suggest 788 : diag::err_unknown_nested_typename_suggest) 789 << II << DC << DroppedSpecifier << SS->getRange(), 790 CanRecover); 791 } else { 792 llvm_unreachable("could not have corrected a typo here"); 793 } 794 795 if (!CanRecover) 796 return; 797 798 CXXScopeSpec tmpSS; 799 if (Corrected.getCorrectionSpecifier()) 800 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 801 SourceRange(IILoc)); 802 // FIXME: Support class template argument deduction here. 803 SuggestedType = 804 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 805 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 806 /*IsCtorOrDtorName=*/false, 807 /*WantNontrivialTypeSourceInfo=*/true); 808 } 809 return; 810 } 811 812 if (getLangOpts().CPlusPlus && !IsTemplateName) { 813 // See if II is a class template that the user forgot to pass arguments to. 814 UnqualifiedId Name; 815 Name.setIdentifier(II, IILoc); 816 CXXScopeSpec EmptySS; 817 TemplateTy TemplateResult; 818 bool MemberOfUnknownSpecialization; 819 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 820 Name, nullptr, true, TemplateResult, 821 MemberOfUnknownSpecialization) == TNK_Type_template) { 822 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 823 return; 824 } 825 } 826 827 // FIXME: Should we move the logic that tries to recover from a missing tag 828 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 829 830 if (!SS || (!SS->isSet() && !SS->isInvalid())) 831 Diag(IILoc, IsTemplateName ? diag::err_no_template 832 : diag::err_unknown_typename) 833 << II; 834 else if (DeclContext *DC = computeDeclContext(*SS, false)) 835 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 836 : diag::err_typename_nested_not_found) 837 << II << DC << SS->getRange(); 838 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 839 SuggestedType = 840 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 841 } else if (isDependentScopeSpecifier(*SS)) { 842 unsigned DiagID = diag::err_typename_missing; 843 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 844 DiagID = diag::ext_typename_missing; 845 846 Diag(SS->getRange().getBegin(), DiagID) 847 << SS->getScopeRep() << II->getName() 848 << SourceRange(SS->getRange().getBegin(), IILoc) 849 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 850 SuggestedType = ActOnTypenameType(S, SourceLocation(), 851 *SS, *II, IILoc).get(); 852 } else { 853 assert(SS && SS->isInvalid() && 854 "Invalid scope specifier has already been diagnosed"); 855 } 856 } 857 858 /// Determine whether the given result set contains either a type name 859 /// or 860 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 861 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 862 NextToken.is(tok::less); 863 864 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 865 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 866 return true; 867 868 if (CheckTemplate && isa<TemplateDecl>(*I)) 869 return true; 870 } 871 872 return false; 873 } 874 875 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 876 Scope *S, CXXScopeSpec &SS, 877 IdentifierInfo *&Name, 878 SourceLocation NameLoc) { 879 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 880 SemaRef.LookupParsedName(R, S, &SS); 881 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 882 StringRef FixItTagName; 883 switch (Tag->getTagKind()) { 884 case TagTypeKind::Class: 885 FixItTagName = "class "; 886 break; 887 888 case TagTypeKind::Enum: 889 FixItTagName = "enum "; 890 break; 891 892 case TagTypeKind::Struct: 893 FixItTagName = "struct "; 894 break; 895 896 case TagTypeKind::Interface: 897 FixItTagName = "__interface "; 898 break; 899 900 case TagTypeKind::Union: 901 FixItTagName = "union "; 902 break; 903 } 904 905 StringRef TagName = FixItTagName.drop_back(); 906 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 907 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 908 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 909 910 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 911 I != IEnd; ++I) 912 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 913 << Name << TagName; 914 915 // Replace lookup results with just the tag decl. 916 Result.clear(Sema::LookupTagName); 917 SemaRef.LookupParsedName(Result, S, &SS); 918 return true; 919 } 920 921 return false; 922 } 923 924 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 925 IdentifierInfo *&Name, 926 SourceLocation NameLoc, 927 const Token &NextToken, 928 CorrectionCandidateCallback *CCC) { 929 DeclarationNameInfo NameInfo(Name, NameLoc); 930 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 931 932 assert(NextToken.isNot(tok::coloncolon) && 933 "parse nested name specifiers before calling ClassifyName"); 934 if (getLangOpts().CPlusPlus && SS.isSet() && 935 isCurrentClassName(*Name, S, &SS)) { 936 // Per [class.qual]p2, this names the constructors of SS, not the 937 // injected-class-name. We don't have a classification for that. 938 // There's not much point caching this result, since the parser 939 // will reject it later. 940 return NameClassification::Unknown(); 941 } 942 943 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 944 LookupParsedName(Result, S, &SS, !CurMethod); 945 946 if (SS.isInvalid()) 947 return NameClassification::Error(); 948 949 // For unqualified lookup in a class template in MSVC mode, look into 950 // dependent base classes where the primary class template is known. 951 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 952 if (ParsedType TypeInBase = 953 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 954 return TypeInBase; 955 } 956 957 // Perform lookup for Objective-C instance variables (including automatically 958 // synthesized instance variables), if we're in an Objective-C method. 959 // FIXME: This lookup really, really needs to be folded in to the normal 960 // unqualified lookup mechanism. 961 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 962 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 963 if (Ivar.isInvalid()) 964 return NameClassification::Error(); 965 if (Ivar.isUsable()) 966 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 967 968 // We defer builtin creation until after ivar lookup inside ObjC methods. 969 if (Result.empty()) 970 LookupBuiltin(Result); 971 } 972 973 bool SecondTry = false; 974 bool IsFilteredTemplateName = false; 975 976 Corrected: 977 switch (Result.getResultKind()) { 978 case LookupResult::NotFound: 979 // If an unqualified-id is followed by a '(', then we have a function 980 // call. 981 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 982 // In C++, this is an ADL-only call. 983 // FIXME: Reference? 984 if (getLangOpts().CPlusPlus) 985 return NameClassification::UndeclaredNonType(); 986 987 // C90 6.3.2.2: 988 // If the expression that precedes the parenthesized argument list in a 989 // function call consists solely of an identifier, and if no 990 // declaration is visible for this identifier, the identifier is 991 // implicitly declared exactly as if, in the innermost block containing 992 // the function call, the declaration 993 // 994 // extern int identifier (); 995 // 996 // appeared. 997 // 998 // We also allow this in C99 as an extension. However, this is not 999 // allowed in all language modes as functions without prototypes may not 1000 // be supported. 1001 if (getLangOpts().implicitFunctionsAllowed()) { 1002 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 1003 return NameClassification::NonType(D); 1004 } 1005 } 1006 1007 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 1008 // In C++20 onwards, this could be an ADL-only call to a function 1009 // template, and we're required to assume that this is a template name. 1010 // 1011 // FIXME: Find a way to still do typo correction in this case. 1012 TemplateName Template = 1013 Context.getAssumedTemplateName(NameInfo.getName()); 1014 return NameClassification::UndeclaredTemplate(Template); 1015 } 1016 1017 // In C, we first see whether there is a tag type by the same name, in 1018 // which case it's likely that the user just forgot to write "enum", 1019 // "struct", or "union". 1020 if (!getLangOpts().CPlusPlus && !SecondTry && 1021 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1022 break; 1023 } 1024 1025 // Perform typo correction to determine if there is another name that is 1026 // close to this name. 1027 if (!SecondTry && CCC) { 1028 SecondTry = true; 1029 if (TypoCorrection Corrected = 1030 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 1031 &SS, *CCC, CTK_ErrorRecovery)) { 1032 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 1033 unsigned QualifiedDiag = diag::err_no_member_suggest; 1034 1035 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 1036 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 1037 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1038 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 1039 UnqualifiedDiag = diag::err_no_template_suggest; 1040 QualifiedDiag = diag::err_no_member_template_suggest; 1041 } else if (UnderlyingFirstDecl && 1042 (isa<TypeDecl>(UnderlyingFirstDecl) || 1043 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 1044 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 1045 UnqualifiedDiag = diag::err_unknown_typename_suggest; 1046 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 1047 } 1048 1049 if (SS.isEmpty()) { 1050 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 1051 } else {// FIXME: is this even reachable? Test it. 1052 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1053 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 1054 Name->getName().equals(CorrectedStr); 1055 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 1056 << Name << computeDeclContext(SS, false) 1057 << DroppedSpecifier << SS.getRange()); 1058 } 1059 1060 // Update the name, so that the caller has the new name. 1061 Name = Corrected.getCorrectionAsIdentifierInfo(); 1062 1063 // Typo correction corrected to a keyword. 1064 if (Corrected.isKeyword()) 1065 return Name; 1066 1067 // Also update the LookupResult... 1068 // FIXME: This should probably go away at some point 1069 Result.clear(); 1070 Result.setLookupName(Corrected.getCorrection()); 1071 if (FirstDecl) 1072 Result.addDecl(FirstDecl); 1073 1074 // If we found an Objective-C instance variable, let 1075 // LookupInObjCMethod build the appropriate expression to 1076 // reference the ivar. 1077 // FIXME: This is a gross hack. 1078 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1079 DeclResult R = 1080 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1081 if (R.isInvalid()) 1082 return NameClassification::Error(); 1083 if (R.isUsable()) 1084 return NameClassification::NonType(Ivar); 1085 } 1086 1087 goto Corrected; 1088 } 1089 } 1090 1091 // We failed to correct; just fall through and let the parser deal with it. 1092 Result.suppressDiagnostics(); 1093 return NameClassification::Unknown(); 1094 1095 case LookupResult::NotFoundInCurrentInstantiation: { 1096 // We performed name lookup into the current instantiation, and there were 1097 // dependent bases, so we treat this result the same way as any other 1098 // dependent nested-name-specifier. 1099 1100 // C++ [temp.res]p2: 1101 // A name used in a template declaration or definition and that is 1102 // dependent on a template-parameter is assumed not to name a type 1103 // unless the applicable name lookup finds a type name or the name is 1104 // qualified by the keyword typename. 1105 // 1106 // FIXME: If the next token is '<', we might want to ask the parser to 1107 // perform some heroics to see if we actually have a 1108 // template-argument-list, which would indicate a missing 'template' 1109 // keyword here. 1110 return NameClassification::DependentNonType(); 1111 } 1112 1113 case LookupResult::Found: 1114 case LookupResult::FoundOverloaded: 1115 case LookupResult::FoundUnresolvedValue: 1116 break; 1117 1118 case LookupResult::Ambiguous: 1119 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1120 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1121 /*AllowDependent=*/false)) { 1122 // C++ [temp.local]p3: 1123 // A lookup that finds an injected-class-name (10.2) can result in an 1124 // ambiguity in certain cases (for example, if it is found in more than 1125 // one base class). If all of the injected-class-names that are found 1126 // refer to specializations of the same class template, and if the name 1127 // is followed by a template-argument-list, the reference refers to the 1128 // class template itself and not a specialization thereof, and is not 1129 // ambiguous. 1130 // 1131 // This filtering can make an ambiguous result into an unambiguous one, 1132 // so try again after filtering out template names. 1133 FilterAcceptableTemplateNames(Result); 1134 if (!Result.isAmbiguous()) { 1135 IsFilteredTemplateName = true; 1136 break; 1137 } 1138 } 1139 1140 // Diagnose the ambiguity and return an error. 1141 return NameClassification::Error(); 1142 } 1143 1144 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1145 (IsFilteredTemplateName || 1146 hasAnyAcceptableTemplateNames( 1147 Result, /*AllowFunctionTemplates=*/true, 1148 /*AllowDependent=*/false, 1149 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1150 getLangOpts().CPlusPlus20))) { 1151 // C++ [temp.names]p3: 1152 // After name lookup (3.4) finds that a name is a template-name or that 1153 // an operator-function-id or a literal- operator-id refers to a set of 1154 // overloaded functions any member of which is a function template if 1155 // this is followed by a <, the < is always taken as the delimiter of a 1156 // template-argument-list and never as the less-than operator. 1157 // C++2a [temp.names]p2: 1158 // A name is also considered to refer to a template if it is an 1159 // unqualified-id followed by a < and name lookup finds either one 1160 // or more functions or finds nothing. 1161 if (!IsFilteredTemplateName) 1162 FilterAcceptableTemplateNames(Result); 1163 1164 bool IsFunctionTemplate; 1165 bool IsVarTemplate; 1166 TemplateName Template; 1167 if (Result.end() - Result.begin() > 1) { 1168 IsFunctionTemplate = true; 1169 Template = Context.getOverloadedTemplateName(Result.begin(), 1170 Result.end()); 1171 } else if (!Result.empty()) { 1172 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1173 *Result.begin(), /*AllowFunctionTemplates=*/true, 1174 /*AllowDependent=*/false)); 1175 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1176 IsVarTemplate = isa<VarTemplateDecl>(TD); 1177 1178 UsingShadowDecl *FoundUsingShadow = 1179 dyn_cast<UsingShadowDecl>(*Result.begin()); 1180 assert(!FoundUsingShadow || 1181 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); 1182 Template = 1183 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 1184 if (SS.isNotEmpty()) 1185 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1186 /*TemplateKeyword=*/false, 1187 Template); 1188 } else { 1189 // All results were non-template functions. This is a function template 1190 // name. 1191 IsFunctionTemplate = true; 1192 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1193 } 1194 1195 if (IsFunctionTemplate) { 1196 // Function templates always go through overload resolution, at which 1197 // point we'll perform the various checks (e.g., accessibility) we need 1198 // to based on which function we selected. 1199 Result.suppressDiagnostics(); 1200 1201 return NameClassification::FunctionTemplate(Template); 1202 } 1203 1204 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1205 : NameClassification::TypeTemplate(Template); 1206 } 1207 1208 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1209 QualType T = Context.getTypeDeclType(Type); 1210 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1211 T = Context.getUsingType(USD, T); 1212 return buildNamedType(*this, &SS, T, NameLoc); 1213 }; 1214 1215 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1216 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1217 DiagnoseUseOfDecl(Type, NameLoc); 1218 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1219 return BuildTypeFor(Type, *Result.begin()); 1220 } 1221 1222 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1223 if (!Class) { 1224 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1225 if (ObjCCompatibleAliasDecl *Alias = 1226 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1227 Class = Alias->getClassInterface(); 1228 } 1229 1230 if (Class) { 1231 DiagnoseUseOfDecl(Class, NameLoc); 1232 1233 if (NextToken.is(tok::period)) { 1234 // Interface. <something> is parsed as a property reference expression. 1235 // Just return "unknown" as a fall-through for now. 1236 Result.suppressDiagnostics(); 1237 return NameClassification::Unknown(); 1238 } 1239 1240 QualType T = Context.getObjCInterfaceType(Class); 1241 return ParsedType::make(T); 1242 } 1243 1244 if (isa<ConceptDecl>(FirstDecl)) 1245 return NameClassification::Concept( 1246 TemplateName(cast<TemplateDecl>(FirstDecl))); 1247 1248 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1249 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1250 return NameClassification::Error(); 1251 } 1252 1253 // We can have a type template here if we're classifying a template argument. 1254 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1255 !isa<VarTemplateDecl>(FirstDecl)) 1256 return NameClassification::TypeTemplate( 1257 TemplateName(cast<TemplateDecl>(FirstDecl))); 1258 1259 // Check for a tag type hidden by a non-type decl in a few cases where it 1260 // seems likely a type is wanted instead of the non-type that was found. 1261 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1262 if ((NextToken.is(tok::identifier) || 1263 (NextIsOp && 1264 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1265 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1266 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1267 DiagnoseUseOfDecl(Type, NameLoc); 1268 return BuildTypeFor(Type, *Result.begin()); 1269 } 1270 1271 // If we already know which single declaration is referenced, just annotate 1272 // that declaration directly. Defer resolving even non-overloaded class 1273 // member accesses, as we need to defer certain access checks until we know 1274 // the context. 1275 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1276 if (Result.isSingleResult() && !ADL && 1277 (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl))) 1278 return NameClassification::NonType(Result.getRepresentativeDecl()); 1279 1280 // Otherwise, this is an overload set that we will need to resolve later. 1281 Result.suppressDiagnostics(); 1282 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1283 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1284 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1285 Result.begin(), Result.end())); 1286 } 1287 1288 ExprResult 1289 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1290 SourceLocation NameLoc) { 1291 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1292 CXXScopeSpec SS; 1293 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1294 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1295 } 1296 1297 ExprResult 1298 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1299 IdentifierInfo *Name, 1300 SourceLocation NameLoc, 1301 bool IsAddressOfOperand) { 1302 DeclarationNameInfo NameInfo(Name, NameLoc); 1303 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1304 NameInfo, IsAddressOfOperand, 1305 /*TemplateArgs=*/nullptr); 1306 } 1307 1308 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1309 NamedDecl *Found, 1310 SourceLocation NameLoc, 1311 const Token &NextToken) { 1312 if (getCurMethodDecl() && SS.isEmpty()) 1313 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1314 return BuildIvarRefExpr(S, NameLoc, Ivar); 1315 1316 // Reconstruct the lookup result. 1317 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1318 Result.addDecl(Found); 1319 Result.resolveKind(); 1320 1321 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1322 return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true); 1323 } 1324 1325 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1326 // For an implicit class member access, transform the result into a member 1327 // access expression if necessary. 1328 auto *ULE = cast<UnresolvedLookupExpr>(E); 1329 if ((*ULE->decls_begin())->isCXXClassMember()) { 1330 CXXScopeSpec SS; 1331 SS.Adopt(ULE->getQualifierLoc()); 1332 1333 // Reconstruct the lookup result. 1334 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1335 LookupOrdinaryName); 1336 Result.setNamingClass(ULE->getNamingClass()); 1337 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1338 Result.addDecl(*I, I.getAccess()); 1339 Result.resolveKind(); 1340 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1341 nullptr, S); 1342 } 1343 1344 // Otherwise, this is already in the form we needed, and no further checks 1345 // are necessary. 1346 return ULE; 1347 } 1348 1349 Sema::TemplateNameKindForDiagnostics 1350 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1351 auto *TD = Name.getAsTemplateDecl(); 1352 if (!TD) 1353 return TemplateNameKindForDiagnostics::DependentTemplate; 1354 if (isa<ClassTemplateDecl>(TD)) 1355 return TemplateNameKindForDiagnostics::ClassTemplate; 1356 if (isa<FunctionTemplateDecl>(TD)) 1357 return TemplateNameKindForDiagnostics::FunctionTemplate; 1358 if (isa<VarTemplateDecl>(TD)) 1359 return TemplateNameKindForDiagnostics::VarTemplate; 1360 if (isa<TypeAliasTemplateDecl>(TD)) 1361 return TemplateNameKindForDiagnostics::AliasTemplate; 1362 if (isa<TemplateTemplateParmDecl>(TD)) 1363 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1364 if (isa<ConceptDecl>(TD)) 1365 return TemplateNameKindForDiagnostics::Concept; 1366 return TemplateNameKindForDiagnostics::DependentTemplate; 1367 } 1368 1369 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1370 assert(DC->getLexicalParent() == CurContext && 1371 "The next DeclContext should be lexically contained in the current one."); 1372 CurContext = DC; 1373 S->setEntity(DC); 1374 } 1375 1376 void Sema::PopDeclContext() { 1377 assert(CurContext && "DeclContext imbalance!"); 1378 1379 CurContext = CurContext->getLexicalParent(); 1380 assert(CurContext && "Popped translation unit!"); 1381 } 1382 1383 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1384 Decl *D) { 1385 // Unlike PushDeclContext, the context to which we return is not necessarily 1386 // the containing DC of TD, because the new context will be some pre-existing 1387 // TagDecl definition instead of a fresh one. 1388 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1389 CurContext = cast<TagDecl>(D)->getDefinition(); 1390 assert(CurContext && "skipping definition of undefined tag"); 1391 // Start lookups from the parent of the current context; we don't want to look 1392 // into the pre-existing complete definition. 1393 S->setEntity(CurContext->getLookupParent()); 1394 return Result; 1395 } 1396 1397 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1398 CurContext = static_cast<decltype(CurContext)>(Context); 1399 } 1400 1401 /// EnterDeclaratorContext - Used when we must lookup names in the context 1402 /// of a declarator's nested name specifier. 1403 /// 1404 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1405 // C++0x [basic.lookup.unqual]p13: 1406 // A name used in the definition of a static data member of class 1407 // X (after the qualified-id of the static member) is looked up as 1408 // if the name was used in a member function of X. 1409 // C++0x [basic.lookup.unqual]p14: 1410 // If a variable member of a namespace is defined outside of the 1411 // scope of its namespace then any name used in the definition of 1412 // the variable member (after the declarator-id) is looked up as 1413 // if the definition of the variable member occurred in its 1414 // namespace. 1415 // Both of these imply that we should push a scope whose context 1416 // is the semantic context of the declaration. We can't use 1417 // PushDeclContext here because that context is not necessarily 1418 // lexically contained in the current context. Fortunately, 1419 // the containing scope should have the appropriate information. 1420 1421 assert(!S->getEntity() && "scope already has entity"); 1422 1423 #ifndef NDEBUG 1424 Scope *Ancestor = S->getParent(); 1425 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1426 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1427 #endif 1428 1429 CurContext = DC; 1430 S->setEntity(DC); 1431 1432 if (S->getParent()->isTemplateParamScope()) { 1433 // Also set the corresponding entities for all immediately-enclosing 1434 // template parameter scopes. 1435 EnterTemplatedContext(S->getParent(), DC); 1436 } 1437 } 1438 1439 void Sema::ExitDeclaratorContext(Scope *S) { 1440 assert(S->getEntity() == CurContext && "Context imbalance!"); 1441 1442 // Switch back to the lexical context. The safety of this is 1443 // enforced by an assert in EnterDeclaratorContext. 1444 Scope *Ancestor = S->getParent(); 1445 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1446 CurContext = Ancestor->getEntity(); 1447 1448 // We don't need to do anything with the scope, which is going to 1449 // disappear. 1450 } 1451 1452 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1453 assert(S->isTemplateParamScope() && 1454 "expected to be initializing a template parameter scope"); 1455 1456 // C++20 [temp.local]p7: 1457 // In the definition of a member of a class template that appears outside 1458 // of the class template definition, the name of a member of the class 1459 // template hides the name of a template-parameter of any enclosing class 1460 // templates (but not a template-parameter of the member if the member is a 1461 // class or function template). 1462 // C++20 [temp.local]p9: 1463 // In the definition of a class template or in the definition of a member 1464 // of such a template that appears outside of the template definition, for 1465 // each non-dependent base class (13.8.2.1), if the name of the base class 1466 // or the name of a member of the base class is the same as the name of a 1467 // template-parameter, the base class name or member name hides the 1468 // template-parameter name (6.4.10). 1469 // 1470 // This means that a template parameter scope should be searched immediately 1471 // after searching the DeclContext for which it is a template parameter 1472 // scope. For example, for 1473 // template<typename T> template<typename U> template<typename V> 1474 // void N::A<T>::B<U>::f(...) 1475 // we search V then B<U> (and base classes) then U then A<T> (and base 1476 // classes) then T then N then ::. 1477 unsigned ScopeDepth = getTemplateDepth(S); 1478 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1479 DeclContext *SearchDCAfterScope = DC; 1480 for (; DC; DC = DC->getLookupParent()) { 1481 if (const TemplateParameterList *TPL = 1482 cast<Decl>(DC)->getDescribedTemplateParams()) { 1483 unsigned DCDepth = TPL->getDepth() + 1; 1484 if (DCDepth > ScopeDepth) 1485 continue; 1486 if (ScopeDepth == DCDepth) 1487 SearchDCAfterScope = DC = DC->getLookupParent(); 1488 break; 1489 } 1490 } 1491 S->setLookupEntity(SearchDCAfterScope); 1492 } 1493 } 1494 1495 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1496 // We assume that the caller has already called 1497 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1498 FunctionDecl *FD = D->getAsFunction(); 1499 if (!FD) 1500 return; 1501 1502 // Same implementation as PushDeclContext, but enters the context 1503 // from the lexical parent, rather than the top-level class. 1504 assert(CurContext == FD->getLexicalParent() && 1505 "The next DeclContext should be lexically contained in the current one."); 1506 CurContext = FD; 1507 S->setEntity(CurContext); 1508 1509 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1510 ParmVarDecl *Param = FD->getParamDecl(P); 1511 // If the parameter has an identifier, then add it to the scope 1512 if (Param->getIdentifier()) { 1513 S->AddDecl(Param); 1514 IdResolver.AddDecl(Param); 1515 } 1516 } 1517 } 1518 1519 void Sema::ActOnExitFunctionContext() { 1520 // Same implementation as PopDeclContext, but returns to the lexical parent, 1521 // rather than the top-level class. 1522 assert(CurContext && "DeclContext imbalance!"); 1523 CurContext = CurContext->getLexicalParent(); 1524 assert(CurContext && "Popped translation unit!"); 1525 } 1526 1527 /// Determine whether overloading is allowed for a new function 1528 /// declaration considering prior declarations of the same name. 1529 /// 1530 /// This routine determines whether overloading is possible, not 1531 /// whether a new declaration actually overloads a previous one. 1532 /// It will return true in C++ (where overloads are alway permitted) 1533 /// or, as a C extension, when either the new declaration or a 1534 /// previous one is declared with the 'overloadable' attribute. 1535 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1536 ASTContext &Context, 1537 const FunctionDecl *New) { 1538 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1539 return true; 1540 1541 // Multiversion function declarations are not overloads in the 1542 // usual sense of that term, but lookup will report that an 1543 // overload set was found if more than one multiversion function 1544 // declaration is present for the same name. It is therefore 1545 // inadequate to assume that some prior declaration(s) had 1546 // the overloadable attribute; checking is required. Since one 1547 // declaration is permitted to omit the attribute, it is necessary 1548 // to check at least two; hence the 'any_of' check below. Note that 1549 // the overloadable attribute is implicitly added to declarations 1550 // that were required to have it but did not. 1551 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1552 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1553 return ND->hasAttr<OverloadableAttr>(); 1554 }); 1555 } else if (Previous.getResultKind() == LookupResult::Found) 1556 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1557 1558 return false; 1559 } 1560 1561 /// Add this decl to the scope shadowed decl chains. 1562 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1563 // Move up the scope chain until we find the nearest enclosing 1564 // non-transparent context. The declaration will be introduced into this 1565 // scope. 1566 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1567 S = S->getParent(); 1568 1569 // Add scoped declarations into their context, so that they can be 1570 // found later. Declarations without a context won't be inserted 1571 // into any context. 1572 if (AddToContext) 1573 CurContext->addDecl(D); 1574 1575 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1576 // are function-local declarations. 1577 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1578 return; 1579 1580 // Template instantiations should also not be pushed into scope. 1581 if (isa<FunctionDecl>(D) && 1582 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1583 return; 1584 1585 // If this replaces anything in the current scope, 1586 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1587 IEnd = IdResolver.end(); 1588 for (; I != IEnd; ++I) { 1589 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1590 S->RemoveDecl(*I); 1591 IdResolver.RemoveDecl(*I); 1592 1593 // Should only need to replace one decl. 1594 break; 1595 } 1596 } 1597 1598 S->AddDecl(D); 1599 1600 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1601 // Implicitly-generated labels may end up getting generated in an order that 1602 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1603 // the label at the appropriate place in the identifier chain. 1604 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1605 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1606 if (IDC == CurContext) { 1607 if (!S->isDeclScope(*I)) 1608 continue; 1609 } else if (IDC->Encloses(CurContext)) 1610 break; 1611 } 1612 1613 IdResolver.InsertDeclAfter(I, D); 1614 } else { 1615 IdResolver.AddDecl(D); 1616 } 1617 warnOnReservedIdentifier(D); 1618 } 1619 1620 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1621 bool AllowInlineNamespace) const { 1622 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1623 } 1624 1625 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1626 DeclContext *TargetDC = DC->getPrimaryContext(); 1627 do { 1628 if (DeclContext *ScopeDC = S->getEntity()) 1629 if (ScopeDC->getPrimaryContext() == TargetDC) 1630 return S; 1631 } while ((S = S->getParent())); 1632 1633 return nullptr; 1634 } 1635 1636 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1637 DeclContext*, 1638 ASTContext&); 1639 1640 /// Filters out lookup results that don't fall within the given scope 1641 /// as determined by isDeclInScope. 1642 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1643 bool ConsiderLinkage, 1644 bool AllowInlineNamespace) { 1645 LookupResult::Filter F = R.makeFilter(); 1646 while (F.hasNext()) { 1647 NamedDecl *D = F.next(); 1648 1649 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1650 continue; 1651 1652 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1653 continue; 1654 1655 F.erase(); 1656 } 1657 1658 F.done(); 1659 } 1660 1661 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1662 /// have compatible owning modules. 1663 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1664 // [module.interface]p7: 1665 // A declaration is attached to a module as follows: 1666 // - If the declaration is a non-dependent friend declaration that nominates a 1667 // function with a declarator-id that is a qualified-id or template-id or that 1668 // nominates a class other than with an elaborated-type-specifier with neither 1669 // a nested-name-specifier nor a simple-template-id, it is attached to the 1670 // module to which the friend is attached ([basic.link]). 1671 if (New->getFriendObjectKind() && 1672 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1673 New->setLocalOwningModule(Old->getOwningModule()); 1674 makeMergedDefinitionVisible(New); 1675 return false; 1676 } 1677 1678 Module *NewM = New->getOwningModule(); 1679 Module *OldM = Old->getOwningModule(); 1680 1681 if (NewM && NewM->isPrivateModule()) 1682 NewM = NewM->Parent; 1683 if (OldM && OldM->isPrivateModule()) 1684 OldM = OldM->Parent; 1685 1686 if (NewM == OldM) 1687 return false; 1688 1689 if (NewM && OldM) { 1690 // A module implementation unit has visibility of the decls in its 1691 // implicitly imported interface. 1692 if (NewM->isModuleImplementation() && OldM == ThePrimaryInterface) 1693 return false; 1694 1695 // Partitions are part of the module, but a partition could import another 1696 // module, so verify that the PMIs agree. 1697 if ((NewM->isModulePartition() || OldM->isModulePartition()) && 1698 NewM->getPrimaryModuleInterfaceName() == 1699 OldM->getPrimaryModuleInterfaceName()) 1700 return false; 1701 } 1702 1703 bool NewIsModuleInterface = NewM && NewM->isNamedModule(); 1704 bool OldIsModuleInterface = OldM && OldM->isNamedModule(); 1705 if (NewIsModuleInterface || OldIsModuleInterface) { 1706 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1707 // if a declaration of D [...] appears in the purview of a module, all 1708 // other such declarations shall appear in the purview of the same module 1709 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1710 << New 1711 << NewIsModuleInterface 1712 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1713 << OldIsModuleInterface 1714 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1715 Diag(Old->getLocation(), diag::note_previous_declaration); 1716 New->setInvalidDecl(); 1717 return true; 1718 } 1719 1720 return false; 1721 } 1722 1723 // [module.interface]p6: 1724 // A redeclaration of an entity X is implicitly exported if X was introduced by 1725 // an exported declaration; otherwise it shall not be exported. 1726 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1727 // [module.interface]p1: 1728 // An export-declaration shall inhabit a namespace scope. 1729 // 1730 // So it is meaningless to talk about redeclaration which is not at namespace 1731 // scope. 1732 if (!New->getLexicalDeclContext() 1733 ->getNonTransparentContext() 1734 ->isFileContext() || 1735 !Old->getLexicalDeclContext() 1736 ->getNonTransparentContext() 1737 ->isFileContext()) 1738 return false; 1739 1740 bool IsNewExported = New->isInExportDeclContext(); 1741 bool IsOldExported = Old->isInExportDeclContext(); 1742 1743 // It should be irrevelant if both of them are not exported. 1744 if (!IsNewExported && !IsOldExported) 1745 return false; 1746 1747 if (IsOldExported) 1748 return false; 1749 1750 assert(IsNewExported); 1751 1752 auto Lk = Old->getFormalLinkage(); 1753 int S = 0; 1754 if (Lk == Linkage::Internal) 1755 S = 1; 1756 else if (Lk == Linkage::Module) 1757 S = 2; 1758 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1759 Diag(Old->getLocation(), diag::note_previous_declaration); 1760 return true; 1761 } 1762 1763 // A wrapper function for checking the semantic restrictions of 1764 // a redeclaration within a module. 1765 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1766 if (CheckRedeclarationModuleOwnership(New, Old)) 1767 return true; 1768 1769 if (CheckRedeclarationExported(New, Old)) 1770 return true; 1771 1772 return false; 1773 } 1774 1775 // Check the redefinition in C++20 Modules. 1776 // 1777 // [basic.def.odr]p14: 1778 // For any definable item D with definitions in multiple translation units, 1779 // - if D is a non-inline non-templated function or variable, or 1780 // - if the definitions in different translation units do not satisfy the 1781 // following requirements, 1782 // the program is ill-formed; a diagnostic is required only if the definable 1783 // item is attached to a named module and a prior definition is reachable at 1784 // the point where a later definition occurs. 1785 // - Each such definition shall not be attached to a named module 1786 // ([module.unit]). 1787 // - Each such definition shall consist of the same sequence of tokens, ... 1788 // ... 1789 // 1790 // Return true if the redefinition is not allowed. Return false otherwise. 1791 bool Sema::IsRedefinitionInModule(const NamedDecl *New, 1792 const NamedDecl *Old) const { 1793 assert(getASTContext().isSameEntity(New, Old) && 1794 "New and Old are not the same definition, we should diagnostic it " 1795 "immediately instead of checking it."); 1796 assert(const_cast<Sema *>(this)->isReachable(New) && 1797 const_cast<Sema *>(this)->isReachable(Old) && 1798 "We shouldn't see unreachable definitions here."); 1799 1800 Module *NewM = New->getOwningModule(); 1801 Module *OldM = Old->getOwningModule(); 1802 1803 // We only checks for named modules here. The header like modules is skipped. 1804 // FIXME: This is not right if we import the header like modules in the module 1805 // purview. 1806 // 1807 // For example, assuming "header.h" provides definition for `D`. 1808 // ```C++ 1809 // //--- M.cppm 1810 // export module M; 1811 // import "header.h"; // or #include "header.h" but import it by clang modules 1812 // actually. 1813 // 1814 // //--- Use.cpp 1815 // import M; 1816 // import "header.h"; // or uses clang modules. 1817 // ``` 1818 // 1819 // In this case, `D` has multiple definitions in multiple TU (M.cppm and 1820 // Use.cpp) and `D` is attached to a named module `M`. The compiler should 1821 // reject it. But the current implementation couldn't detect the case since we 1822 // don't record the information about the importee modules. 1823 // 1824 // But this might not be painful in practice. Since the design of C++20 Named 1825 // Modules suggests us to use headers in global module fragment instead of 1826 // module purview. 1827 if (NewM && NewM->isHeaderLikeModule()) 1828 NewM = nullptr; 1829 if (OldM && OldM->isHeaderLikeModule()) 1830 OldM = nullptr; 1831 1832 if (!NewM && !OldM) 1833 return true; 1834 1835 // [basic.def.odr]p14.3 1836 // Each such definition shall not be attached to a named module 1837 // ([module.unit]). 1838 if ((NewM && NewM->isNamedModule()) || (OldM && OldM->isNamedModule())) 1839 return true; 1840 1841 // Then New and Old lives in the same TU if their share one same module unit. 1842 if (NewM) 1843 NewM = NewM->getTopLevelModule(); 1844 if (OldM) 1845 OldM = OldM->getTopLevelModule(); 1846 return OldM == NewM; 1847 } 1848 1849 static bool isUsingDeclNotAtClassScope(NamedDecl *D) { 1850 if (D->getDeclContext()->isFileContext()) 1851 return false; 1852 1853 return isa<UsingShadowDecl>(D) || 1854 isa<UnresolvedUsingTypenameDecl>(D) || 1855 isa<UnresolvedUsingValueDecl>(D); 1856 } 1857 1858 /// Removes using shadow declarations not at class scope from the lookup 1859 /// results. 1860 static void RemoveUsingDecls(LookupResult &R) { 1861 LookupResult::Filter F = R.makeFilter(); 1862 while (F.hasNext()) 1863 if (isUsingDeclNotAtClassScope(F.next())) 1864 F.erase(); 1865 1866 F.done(); 1867 } 1868 1869 /// Check for this common pattern: 1870 /// @code 1871 /// class S { 1872 /// S(const S&); // DO NOT IMPLEMENT 1873 /// void operator=(const S&); // DO NOT IMPLEMENT 1874 /// }; 1875 /// @endcode 1876 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1877 // FIXME: Should check for private access too but access is set after we get 1878 // the decl here. 1879 if (D->doesThisDeclarationHaveABody()) 1880 return false; 1881 1882 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1883 return CD->isCopyConstructor(); 1884 return D->isCopyAssignmentOperator(); 1885 } 1886 1887 // We need this to handle 1888 // 1889 // typedef struct { 1890 // void *foo() { return 0; } 1891 // } A; 1892 // 1893 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1894 // for example. If 'A', foo will have external linkage. If we have '*A', 1895 // foo will have no linkage. Since we can't know until we get to the end 1896 // of the typedef, this function finds out if D might have non-external linkage. 1897 // Callers should verify at the end of the TU if it D has external linkage or 1898 // not. 1899 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1900 const DeclContext *DC = D->getDeclContext(); 1901 while (!DC->isTranslationUnit()) { 1902 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1903 if (!RD->hasNameForLinkage()) 1904 return true; 1905 } 1906 DC = DC->getParent(); 1907 } 1908 1909 return !D->isExternallyVisible(); 1910 } 1911 1912 // FIXME: This needs to be refactored; some other isInMainFile users want 1913 // these semantics. 1914 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1915 if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile) 1916 return false; 1917 return S.SourceMgr.isInMainFile(Loc); 1918 } 1919 1920 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1921 assert(D); 1922 1923 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1924 return false; 1925 1926 // Ignore all entities declared within templates, and out-of-line definitions 1927 // of members of class templates. 1928 if (D->getDeclContext()->isDependentContext() || 1929 D->getLexicalDeclContext()->isDependentContext()) 1930 return false; 1931 1932 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1933 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1934 return false; 1935 // A non-out-of-line declaration of a member specialization was implicitly 1936 // instantiated; it's the out-of-line declaration that we're interested in. 1937 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1938 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1939 return false; 1940 1941 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1942 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1943 return false; 1944 } else { 1945 // 'static inline' functions are defined in headers; don't warn. 1946 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1947 return false; 1948 } 1949 1950 if (FD->doesThisDeclarationHaveABody() && 1951 Context.DeclMustBeEmitted(FD)) 1952 return false; 1953 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1954 // Constants and utility variables are defined in headers with internal 1955 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1956 // like "inline".) 1957 if (!isMainFileLoc(*this, VD->getLocation())) 1958 return false; 1959 1960 if (Context.DeclMustBeEmitted(VD)) 1961 return false; 1962 1963 if (VD->isStaticDataMember() && 1964 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1965 return false; 1966 if (VD->isStaticDataMember() && 1967 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1968 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1969 return false; 1970 1971 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1972 return false; 1973 } else { 1974 return false; 1975 } 1976 1977 // Only warn for unused decls internal to the translation unit. 1978 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1979 // for inline functions defined in the main source file, for instance. 1980 return mightHaveNonExternalLinkage(D); 1981 } 1982 1983 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1984 if (!D) 1985 return; 1986 1987 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1988 const FunctionDecl *First = FD->getFirstDecl(); 1989 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1990 return; // First should already be in the vector. 1991 } 1992 1993 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1994 const VarDecl *First = VD->getFirstDecl(); 1995 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1996 return; // First should already be in the vector. 1997 } 1998 1999 if (ShouldWarnIfUnusedFileScopedDecl(D)) 2000 UnusedFileScopedDecls.push_back(D); 2001 } 2002 2003 static bool ShouldDiagnoseUnusedDecl(const LangOptions &LangOpts, 2004 const NamedDecl *D) { 2005 if (D->isInvalidDecl()) 2006 return false; 2007 2008 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) { 2009 // For a decomposition declaration, warn if none of the bindings are 2010 // referenced, instead of if the variable itself is referenced (which 2011 // it is, by the bindings' expressions). 2012 bool IsAllPlaceholders = true; 2013 for (const auto *BD : DD->bindings()) { 2014 if (BD->isReferenced()) 2015 return false; 2016 IsAllPlaceholders = IsAllPlaceholders && BD->isPlaceholderVar(LangOpts); 2017 } 2018 if (IsAllPlaceholders) 2019 return false; 2020 } else if (!D->getDeclName()) { 2021 return false; 2022 } else if (D->isReferenced() || D->isUsed()) { 2023 return false; 2024 } 2025 2026 if (D->isPlaceholderVar(LangOpts)) 2027 return false; 2028 2029 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>() || 2030 D->hasAttr<CleanupAttr>()) 2031 return false; 2032 2033 if (isa<LabelDecl>(D)) 2034 return true; 2035 2036 // Except for labels, we only care about unused decls that are local to 2037 // functions. 2038 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 2039 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 2040 // For dependent types, the diagnostic is deferred. 2041 WithinFunction = 2042 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 2043 if (!WithinFunction) 2044 return false; 2045 2046 if (isa<TypedefNameDecl>(D)) 2047 return true; 2048 2049 // White-list anything that isn't a local variable. 2050 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 2051 return false; 2052 2053 // Types of valid local variables should be complete, so this should succeed. 2054 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2055 2056 const Expr *Init = VD->getInit(); 2057 if (const auto *Cleanups = dyn_cast_if_present<ExprWithCleanups>(Init)) 2058 Init = Cleanups->getSubExpr(); 2059 2060 const auto *Ty = VD->getType().getTypePtr(); 2061 2062 // Only look at the outermost level of typedef. 2063 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 2064 // Allow anything marked with __attribute__((unused)). 2065 if (TT->getDecl()->hasAttr<UnusedAttr>()) 2066 return false; 2067 } 2068 2069 // Warn for reference variables whose initializtion performs lifetime 2070 // extension. 2071 if (const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(Init); 2072 MTE && MTE->getExtendingDecl()) { 2073 Ty = VD->getType().getNonReferenceType().getTypePtr(); 2074 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 2075 } 2076 2077 // If we failed to complete the type for some reason, or if the type is 2078 // dependent, don't diagnose the variable. 2079 if (Ty->isIncompleteType() || Ty->isDependentType()) 2080 return false; 2081 2082 // Look at the element type to ensure that the warning behaviour is 2083 // consistent for both scalars and arrays. 2084 Ty = Ty->getBaseElementTypeUnsafe(); 2085 2086 if (const TagType *TT = Ty->getAs<TagType>()) { 2087 const TagDecl *Tag = TT->getDecl(); 2088 if (Tag->hasAttr<UnusedAttr>()) 2089 return false; 2090 2091 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2092 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 2093 return false; 2094 2095 if (Init) { 2096 const auto *Construct = dyn_cast<CXXConstructExpr>(Init); 2097 if (Construct && !Construct->isElidable()) { 2098 const CXXConstructorDecl *CD = Construct->getConstructor(); 2099 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 2100 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 2101 return false; 2102 } 2103 2104 // Suppress the warning if we don't know how this is constructed, and 2105 // it could possibly be non-trivial constructor. 2106 if (Init->isTypeDependent()) { 2107 for (const CXXConstructorDecl *Ctor : RD->ctors()) 2108 if (!Ctor->isTrivial()) 2109 return false; 2110 } 2111 2112 // Suppress the warning if the constructor is unresolved because 2113 // its arguments are dependent. 2114 if (isa<CXXUnresolvedConstructExpr>(Init)) 2115 return false; 2116 } 2117 } 2118 } 2119 2120 // TODO: __attribute__((unused)) templates? 2121 } 2122 2123 return true; 2124 } 2125 2126 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 2127 FixItHint &Hint) { 2128 if (isa<LabelDecl>(D)) { 2129 SourceLocation AfterColon = Lexer::findLocationAfterToken( 2130 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 2131 /*SkipTrailingWhitespaceAndNewline=*/false); 2132 if (AfterColon.isInvalid()) 2133 return; 2134 Hint = FixItHint::CreateRemoval( 2135 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 2136 } 2137 } 2138 2139 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 2140 DiagnoseUnusedNestedTypedefs( 2141 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); 2142 } 2143 2144 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D, 2145 DiagReceiverTy DiagReceiver) { 2146 if (D->getTypeForDecl()->isDependentType()) 2147 return; 2148 2149 for (auto *TmpD : D->decls()) { 2150 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 2151 DiagnoseUnusedDecl(T, DiagReceiver); 2152 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 2153 DiagnoseUnusedNestedTypedefs(R, DiagReceiver); 2154 } 2155 } 2156 2157 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 2158 DiagnoseUnusedDecl( 2159 D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); }); 2160 } 2161 2162 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 2163 /// unless they are marked attr(unused). 2164 void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) { 2165 if (!ShouldDiagnoseUnusedDecl(getLangOpts(), D)) 2166 return; 2167 2168 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2169 // typedefs can be referenced later on, so the diagnostics are emitted 2170 // at end-of-translation-unit. 2171 UnusedLocalTypedefNameCandidates.insert(TD); 2172 return; 2173 } 2174 2175 FixItHint Hint; 2176 GenerateFixForUnusedDecl(D, Context, Hint); 2177 2178 unsigned DiagID; 2179 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2180 DiagID = diag::warn_unused_exception_param; 2181 else if (isa<LabelDecl>(D)) 2182 DiagID = diag::warn_unused_label; 2183 else 2184 DiagID = diag::warn_unused_variable; 2185 2186 SourceLocation DiagLoc = D->getLocation(); 2187 DiagReceiver(DiagLoc, PDiag(DiagID) << D << Hint << SourceRange(DiagLoc)); 2188 } 2189 2190 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD, 2191 DiagReceiverTy DiagReceiver) { 2192 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2193 // it's not really unused. 2194 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<CleanupAttr>()) 2195 return; 2196 2197 // In C++, `_` variables behave as if they were maybe_unused 2198 if (VD->hasAttr<UnusedAttr>() || VD->isPlaceholderVar(getLangOpts())) 2199 return; 2200 2201 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2202 2203 if (Ty->isReferenceType() || Ty->isDependentType()) 2204 return; 2205 2206 if (const TagType *TT = Ty->getAs<TagType>()) { 2207 const TagDecl *Tag = TT->getDecl(); 2208 if (Tag->hasAttr<UnusedAttr>()) 2209 return; 2210 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2211 // mimic gcc's behavior. 2212 if (const auto *RD = dyn_cast<CXXRecordDecl>(Tag); 2213 RD && !RD->hasAttr<WarnUnusedAttr>()) 2214 return; 2215 } 2216 2217 // Don't warn about __block Objective-C pointer variables, as they might 2218 // be assigned in the block but not used elsewhere for the purpose of lifetime 2219 // extension. 2220 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2221 return; 2222 2223 // Don't warn about Objective-C pointer variables with precise lifetime 2224 // semantics; they can be used to ensure ARC releases the object at a known 2225 // time, which may mean assignment but no other references. 2226 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2227 return; 2228 2229 auto iter = RefsMinusAssignments.find(VD); 2230 if (iter == RefsMinusAssignments.end()) 2231 return; 2232 2233 assert(iter->getSecond() >= 0 && 2234 "Found a negative number of references to a VarDecl"); 2235 if (iter->getSecond() != 0) 2236 return; 2237 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2238 : diag::warn_unused_but_set_variable; 2239 DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD); 2240 } 2241 2242 static void CheckPoppedLabel(LabelDecl *L, Sema &S, 2243 Sema::DiagReceiverTy DiagReceiver) { 2244 // Verify that we have no forward references left. If so, there was a goto 2245 // or address of a label taken, but no definition of it. Label fwd 2246 // definitions are indicated with a null substmt which is also not a resolved 2247 // MS inline assembly label name. 2248 bool Diagnose = false; 2249 if (L->isMSAsmLabel()) 2250 Diagnose = !L->isResolvedMSAsmLabel(); 2251 else 2252 Diagnose = L->getStmt() == nullptr; 2253 if (Diagnose) 2254 DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use) 2255 << L); 2256 } 2257 2258 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2259 S->applyNRVO(); 2260 2261 if (S->decl_empty()) return; 2262 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2263 "Scope shouldn't contain decls!"); 2264 2265 /// We visit the decls in non-deterministic order, but we want diagnostics 2266 /// emitted in deterministic order. Collect any diagnostic that may be emitted 2267 /// and sort the diagnostics before emitting them, after we visited all decls. 2268 struct LocAndDiag { 2269 SourceLocation Loc; 2270 std::optional<SourceLocation> PreviousDeclLoc; 2271 PartialDiagnostic PD; 2272 }; 2273 SmallVector<LocAndDiag, 16> DeclDiags; 2274 auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) { 2275 DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)}); 2276 }; 2277 auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc, 2278 SourceLocation PreviousDeclLoc, 2279 PartialDiagnostic PD) { 2280 DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)}); 2281 }; 2282 2283 for (auto *TmpD : S->decls()) { 2284 assert(TmpD && "This decl didn't get pushed??"); 2285 2286 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2287 NamedDecl *D = cast<NamedDecl>(TmpD); 2288 2289 // Diagnose unused variables in this scope. 2290 if (!S->hasUnrecoverableErrorOccurred()) { 2291 DiagnoseUnusedDecl(D, addDiag); 2292 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2293 DiagnoseUnusedNestedTypedefs(RD, addDiag); 2294 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2295 DiagnoseUnusedButSetDecl(VD, addDiag); 2296 RefsMinusAssignments.erase(VD); 2297 } 2298 } 2299 2300 if (!D->getDeclName()) continue; 2301 2302 // If this was a forward reference to a label, verify it was defined. 2303 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2304 CheckPoppedLabel(LD, *this, addDiag); 2305 2306 // Remove this name from our lexical scope, and warn on it if we haven't 2307 // already. 2308 IdResolver.RemoveDecl(D); 2309 auto ShadowI = ShadowingDecls.find(D); 2310 if (ShadowI != ShadowingDecls.end()) { 2311 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2312 addDiagWithPrev(D->getLocation(), FD->getLocation(), 2313 PDiag(diag::warn_ctor_parm_shadows_field) 2314 << D << FD << FD->getParent()); 2315 } 2316 ShadowingDecls.erase(ShadowI); 2317 } 2318 2319 if (!getLangOpts().CPlusPlus && S->isClassScope()) { 2320 if (auto *FD = dyn_cast<FieldDecl>(TmpD); 2321 FD && FD->hasAttr<CountedByAttr>()) 2322 CheckCountedByAttr(S, FD); 2323 } 2324 } 2325 2326 llvm::sort(DeclDiags, 2327 [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool { 2328 // The particular order for diagnostics is not important, as long 2329 // as the order is deterministic. Using the raw location is going 2330 // to generally be in source order unless there are macro 2331 // expansions involved. 2332 return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding(); 2333 }); 2334 for (const LocAndDiag &D : DeclDiags) { 2335 Diag(D.Loc, D.PD); 2336 if (D.PreviousDeclLoc) 2337 Diag(*D.PreviousDeclLoc, diag::note_previous_declaration); 2338 } 2339 } 2340 2341 /// Look for an Objective-C class in the translation unit. 2342 /// 2343 /// \param Id The name of the Objective-C class we're looking for. If 2344 /// typo-correction fixes this name, the Id will be updated 2345 /// to the fixed name. 2346 /// 2347 /// \param IdLoc The location of the name in the translation unit. 2348 /// 2349 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2350 /// if there is no class with the given name. 2351 /// 2352 /// \returns The declaration of the named Objective-C class, or NULL if the 2353 /// class could not be found. 2354 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2355 SourceLocation IdLoc, 2356 bool DoTypoCorrection) { 2357 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2358 // creation from this context. 2359 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2360 2361 if (!IDecl && DoTypoCorrection) { 2362 // Perform typo correction at the given location, but only if we 2363 // find an Objective-C class name. 2364 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2365 if (TypoCorrection C = 2366 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2367 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2368 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2369 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2370 Id = IDecl->getIdentifier(); 2371 } 2372 } 2373 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2374 // This routine must always return a class definition, if any. 2375 if (Def && Def->getDefinition()) 2376 Def = Def->getDefinition(); 2377 return Def; 2378 } 2379 2380 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2381 /// from S, where a non-field would be declared. This routine copes 2382 /// with the difference between C and C++ scoping rules in structs and 2383 /// unions. For example, the following code is well-formed in C but 2384 /// ill-formed in C++: 2385 /// @code 2386 /// struct S6 { 2387 /// enum { BAR } e; 2388 /// }; 2389 /// 2390 /// void test_S6() { 2391 /// struct S6 a; 2392 /// a.e = BAR; 2393 /// } 2394 /// @endcode 2395 /// For the declaration of BAR, this routine will return a different 2396 /// scope. The scope S will be the scope of the unnamed enumeration 2397 /// within S6. In C++, this routine will return the scope associated 2398 /// with S6, because the enumeration's scope is a transparent 2399 /// context but structures can contain non-field names. In C, this 2400 /// routine will return the translation unit scope, since the 2401 /// enumeration's scope is a transparent context and structures cannot 2402 /// contain non-field names. 2403 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2404 while (((S->getFlags() & Scope::DeclScope) == 0) || 2405 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2406 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2407 S = S->getParent(); 2408 return S; 2409 } 2410 2411 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2412 ASTContext::GetBuiltinTypeError Error) { 2413 switch (Error) { 2414 case ASTContext::GE_None: 2415 return ""; 2416 case ASTContext::GE_Missing_type: 2417 return BuiltinInfo.getHeaderName(ID); 2418 case ASTContext::GE_Missing_stdio: 2419 return "stdio.h"; 2420 case ASTContext::GE_Missing_setjmp: 2421 return "setjmp.h"; 2422 case ASTContext::GE_Missing_ucontext: 2423 return "ucontext.h"; 2424 } 2425 llvm_unreachable("unhandled error kind"); 2426 } 2427 2428 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2429 unsigned ID, SourceLocation Loc) { 2430 DeclContext *Parent = Context.getTranslationUnitDecl(); 2431 2432 if (getLangOpts().CPlusPlus) { 2433 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2434 Context, Parent, Loc, Loc, LinkageSpecLanguageIDs::C, false); 2435 CLinkageDecl->setImplicit(); 2436 Parent->addDecl(CLinkageDecl); 2437 Parent = CLinkageDecl; 2438 } 2439 2440 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2441 /*TInfo=*/nullptr, SC_Extern, 2442 getCurFPFeatures().isFPConstrained(), 2443 false, Type->isFunctionProtoType()); 2444 New->setImplicit(); 2445 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2446 2447 // Create Decl objects for each parameter, adding them to the 2448 // FunctionDecl. 2449 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2450 SmallVector<ParmVarDecl *, 16> Params; 2451 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2452 ParmVarDecl *parm = ParmVarDecl::Create( 2453 Context, New, SourceLocation(), SourceLocation(), nullptr, 2454 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2455 parm->setScopeInfo(0, i); 2456 Params.push_back(parm); 2457 } 2458 New->setParams(Params); 2459 } 2460 2461 AddKnownFunctionAttributes(New); 2462 return New; 2463 } 2464 2465 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2466 /// file scope. lazily create a decl for it. ForRedeclaration is true 2467 /// if we're creating this built-in in anticipation of redeclaring the 2468 /// built-in. 2469 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2470 Scope *S, bool ForRedeclaration, 2471 SourceLocation Loc) { 2472 LookupNecessaryTypesForBuiltin(S, ID); 2473 2474 ASTContext::GetBuiltinTypeError Error; 2475 QualType R = Context.GetBuiltinType(ID, Error); 2476 if (Error) { 2477 if (!ForRedeclaration) 2478 return nullptr; 2479 2480 // If we have a builtin without an associated type we should not emit a 2481 // warning when we were not able to find a type for it. 2482 if (Error == ASTContext::GE_Missing_type || 2483 Context.BuiltinInfo.allowTypeMismatch(ID)) 2484 return nullptr; 2485 2486 // If we could not find a type for setjmp it is because the jmp_buf type was 2487 // not defined prior to the setjmp declaration. 2488 if (Error == ASTContext::GE_Missing_setjmp) { 2489 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2490 << Context.BuiltinInfo.getName(ID); 2491 return nullptr; 2492 } 2493 2494 // Generally, we emit a warning that the declaration requires the 2495 // appropriate header. 2496 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2497 << getHeaderName(Context.BuiltinInfo, ID, Error) 2498 << Context.BuiltinInfo.getName(ID); 2499 return nullptr; 2500 } 2501 2502 if (!ForRedeclaration && 2503 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2504 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2505 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2506 : diag::ext_implicit_lib_function_decl) 2507 << Context.BuiltinInfo.getName(ID) << R; 2508 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2509 Diag(Loc, diag::note_include_header_or_declare) 2510 << Header << Context.BuiltinInfo.getName(ID); 2511 } 2512 2513 if (R.isNull()) 2514 return nullptr; 2515 2516 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2517 RegisterLocallyScopedExternCDecl(New, S); 2518 2519 // TUScope is the translation-unit scope to insert this function into. 2520 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2521 // relate Scopes to DeclContexts, and probably eliminate CurContext 2522 // entirely, but we're not there yet. 2523 DeclContext *SavedContext = CurContext; 2524 CurContext = New->getDeclContext(); 2525 PushOnScopeChains(New, TUScope); 2526 CurContext = SavedContext; 2527 return New; 2528 } 2529 2530 /// Typedef declarations don't have linkage, but they still denote the same 2531 /// entity if their types are the same. 2532 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2533 /// isSameEntity. 2534 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2535 TypedefNameDecl *Decl, 2536 LookupResult &Previous) { 2537 // This is only interesting when modules are enabled. 2538 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2539 return; 2540 2541 // Empty sets are uninteresting. 2542 if (Previous.empty()) 2543 return; 2544 2545 LookupResult::Filter Filter = Previous.makeFilter(); 2546 while (Filter.hasNext()) { 2547 NamedDecl *Old = Filter.next(); 2548 2549 // Non-hidden declarations are never ignored. 2550 if (S.isVisible(Old)) 2551 continue; 2552 2553 // Declarations of the same entity are not ignored, even if they have 2554 // different linkages. 2555 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2556 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2557 Decl->getUnderlyingType())) 2558 continue; 2559 2560 // If both declarations give a tag declaration a typedef name for linkage 2561 // purposes, then they declare the same entity. 2562 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2563 Decl->getAnonDeclWithTypedefName()) 2564 continue; 2565 } 2566 2567 Filter.erase(); 2568 } 2569 2570 Filter.done(); 2571 } 2572 2573 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2574 QualType OldType; 2575 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2576 OldType = OldTypedef->getUnderlyingType(); 2577 else 2578 OldType = Context.getTypeDeclType(Old); 2579 QualType NewType = New->getUnderlyingType(); 2580 2581 if (NewType->isVariablyModifiedType()) { 2582 // Must not redefine a typedef with a variably-modified type. 2583 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2584 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2585 << Kind << NewType; 2586 if (Old->getLocation().isValid()) 2587 notePreviousDefinition(Old, New->getLocation()); 2588 New->setInvalidDecl(); 2589 return true; 2590 } 2591 2592 if (OldType != NewType && 2593 !OldType->isDependentType() && 2594 !NewType->isDependentType() && 2595 !Context.hasSameType(OldType, NewType)) { 2596 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2597 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2598 << Kind << NewType << OldType; 2599 if (Old->getLocation().isValid()) 2600 notePreviousDefinition(Old, New->getLocation()); 2601 New->setInvalidDecl(); 2602 return true; 2603 } 2604 return false; 2605 } 2606 2607 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2608 /// same name and scope as a previous declaration 'Old'. Figure out 2609 /// how to resolve this situation, merging decls or emitting 2610 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2611 /// 2612 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2613 LookupResult &OldDecls) { 2614 // If the new decl is known invalid already, don't bother doing any 2615 // merging checks. 2616 if (New->isInvalidDecl()) return; 2617 2618 // Allow multiple definitions for ObjC built-in typedefs. 2619 // FIXME: Verify the underlying types are equivalent! 2620 if (getLangOpts().ObjC) { 2621 const IdentifierInfo *TypeID = New->getIdentifier(); 2622 switch (TypeID->getLength()) { 2623 default: break; 2624 case 2: 2625 { 2626 if (!TypeID->isStr("id")) 2627 break; 2628 QualType T = New->getUnderlyingType(); 2629 if (!T->isPointerType()) 2630 break; 2631 if (!T->isVoidPointerType()) { 2632 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2633 if (!PT->isStructureType()) 2634 break; 2635 } 2636 Context.setObjCIdRedefinitionType(T); 2637 // Install the built-in type for 'id', ignoring the current definition. 2638 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2639 return; 2640 } 2641 case 5: 2642 if (!TypeID->isStr("Class")) 2643 break; 2644 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2645 // Install the built-in type for 'Class', ignoring the current definition. 2646 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2647 return; 2648 case 3: 2649 if (!TypeID->isStr("SEL")) 2650 break; 2651 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2652 // Install the built-in type for 'SEL', ignoring the current definition. 2653 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2654 return; 2655 } 2656 // Fall through - the typedef name was not a builtin type. 2657 } 2658 2659 // Verify the old decl was also a type. 2660 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2661 if (!Old) { 2662 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2663 << New->getDeclName(); 2664 2665 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2666 if (OldD->getLocation().isValid()) 2667 notePreviousDefinition(OldD, New->getLocation()); 2668 2669 return New->setInvalidDecl(); 2670 } 2671 2672 // If the old declaration is invalid, just give up here. 2673 if (Old->isInvalidDecl()) 2674 return New->setInvalidDecl(); 2675 2676 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2677 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2678 auto *NewTag = New->getAnonDeclWithTypedefName(); 2679 NamedDecl *Hidden = nullptr; 2680 if (OldTag && NewTag && 2681 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2682 !hasVisibleDefinition(OldTag, &Hidden)) { 2683 // There is a definition of this tag, but it is not visible. Use it 2684 // instead of our tag. 2685 New->setTypeForDecl(OldTD->getTypeForDecl()); 2686 if (OldTD->isModed()) 2687 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2688 OldTD->getUnderlyingType()); 2689 else 2690 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2691 2692 // Make the old tag definition visible. 2693 makeMergedDefinitionVisible(Hidden); 2694 2695 // If this was an unscoped enumeration, yank all of its enumerators 2696 // out of the scope. 2697 if (isa<EnumDecl>(NewTag)) { 2698 Scope *EnumScope = getNonFieldDeclScope(S); 2699 for (auto *D : NewTag->decls()) { 2700 auto *ED = cast<EnumConstantDecl>(D); 2701 assert(EnumScope->isDeclScope(ED)); 2702 EnumScope->RemoveDecl(ED); 2703 IdResolver.RemoveDecl(ED); 2704 ED->getLexicalDeclContext()->removeDecl(ED); 2705 } 2706 } 2707 } 2708 } 2709 2710 // If the typedef types are not identical, reject them in all languages and 2711 // with any extensions enabled. 2712 if (isIncompatibleTypedef(Old, New)) 2713 return; 2714 2715 // The types match. Link up the redeclaration chain and merge attributes if 2716 // the old declaration was a typedef. 2717 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2718 New->setPreviousDecl(Typedef); 2719 mergeDeclAttributes(New, Old); 2720 } 2721 2722 if (getLangOpts().MicrosoftExt) 2723 return; 2724 2725 if (getLangOpts().CPlusPlus) { 2726 // C++ [dcl.typedef]p2: 2727 // In a given non-class scope, a typedef specifier can be used to 2728 // redefine the name of any type declared in that scope to refer 2729 // to the type to which it already refers. 2730 if (!isa<CXXRecordDecl>(CurContext)) 2731 return; 2732 2733 // C++0x [dcl.typedef]p4: 2734 // In a given class scope, a typedef specifier can be used to redefine 2735 // any class-name declared in that scope that is not also a typedef-name 2736 // to refer to the type to which it already refers. 2737 // 2738 // This wording came in via DR424, which was a correction to the 2739 // wording in DR56, which accidentally banned code like: 2740 // 2741 // struct S { 2742 // typedef struct A { } A; 2743 // }; 2744 // 2745 // in the C++03 standard. We implement the C++0x semantics, which 2746 // allow the above but disallow 2747 // 2748 // struct S { 2749 // typedef int I; 2750 // typedef int I; 2751 // }; 2752 // 2753 // since that was the intent of DR56. 2754 if (!isa<TypedefNameDecl>(Old)) 2755 return; 2756 2757 Diag(New->getLocation(), diag::err_redefinition) 2758 << New->getDeclName(); 2759 notePreviousDefinition(Old, New->getLocation()); 2760 return New->setInvalidDecl(); 2761 } 2762 2763 // Modules always permit redefinition of typedefs, as does C11. 2764 if (getLangOpts().Modules || getLangOpts().C11) 2765 return; 2766 2767 // If we have a redefinition of a typedef in C, emit a warning. This warning 2768 // is normally mapped to an error, but can be controlled with 2769 // -Wtypedef-redefinition. If either the original or the redefinition is 2770 // in a system header, don't emit this for compatibility with GCC. 2771 if (getDiagnostics().getSuppressSystemWarnings() && 2772 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2773 (Old->isImplicit() || 2774 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2775 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2776 return; 2777 2778 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2779 << New->getDeclName(); 2780 notePreviousDefinition(Old, New->getLocation()); 2781 } 2782 2783 /// DeclhasAttr - returns true if decl Declaration already has the target 2784 /// attribute. 2785 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2786 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2787 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2788 for (const auto *i : D->attrs()) 2789 if (i->getKind() == A->getKind()) { 2790 if (Ann) { 2791 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2792 return true; 2793 continue; 2794 } 2795 // FIXME: Don't hardcode this check 2796 if (OA && isa<OwnershipAttr>(i)) 2797 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2798 return true; 2799 } 2800 2801 return false; 2802 } 2803 2804 static bool isAttributeTargetADefinition(Decl *D) { 2805 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2806 return VD->isThisDeclarationADefinition(); 2807 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2808 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2809 return true; 2810 } 2811 2812 /// Merge alignment attributes from \p Old to \p New, taking into account the 2813 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2814 /// 2815 /// \return \c true if any attributes were added to \p New. 2816 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2817 // Look for alignas attributes on Old, and pick out whichever attribute 2818 // specifies the strictest alignment requirement. 2819 AlignedAttr *OldAlignasAttr = nullptr; 2820 AlignedAttr *OldStrictestAlignAttr = nullptr; 2821 unsigned OldAlign = 0; 2822 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2823 // FIXME: We have no way of representing inherited dependent alignments 2824 // in a case like: 2825 // template<int A, int B> struct alignas(A) X; 2826 // template<int A, int B> struct alignas(B) X {}; 2827 // For now, we just ignore any alignas attributes which are not on the 2828 // definition in such a case. 2829 if (I->isAlignmentDependent()) 2830 return false; 2831 2832 if (I->isAlignas()) 2833 OldAlignasAttr = I; 2834 2835 unsigned Align = I->getAlignment(S.Context); 2836 if (Align > OldAlign) { 2837 OldAlign = Align; 2838 OldStrictestAlignAttr = I; 2839 } 2840 } 2841 2842 // Look for alignas attributes on New. 2843 AlignedAttr *NewAlignasAttr = nullptr; 2844 unsigned NewAlign = 0; 2845 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2846 if (I->isAlignmentDependent()) 2847 return false; 2848 2849 if (I->isAlignas()) 2850 NewAlignasAttr = I; 2851 2852 unsigned Align = I->getAlignment(S.Context); 2853 if (Align > NewAlign) 2854 NewAlign = Align; 2855 } 2856 2857 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2858 // Both declarations have 'alignas' attributes. We require them to match. 2859 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2860 // fall short. (If two declarations both have alignas, they must both match 2861 // every definition, and so must match each other if there is a definition.) 2862 2863 // If either declaration only contains 'alignas(0)' specifiers, then it 2864 // specifies the natural alignment for the type. 2865 if (OldAlign == 0 || NewAlign == 0) { 2866 QualType Ty; 2867 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2868 Ty = VD->getType(); 2869 else 2870 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2871 2872 if (OldAlign == 0) 2873 OldAlign = S.Context.getTypeAlign(Ty); 2874 if (NewAlign == 0) 2875 NewAlign = S.Context.getTypeAlign(Ty); 2876 } 2877 2878 if (OldAlign != NewAlign) { 2879 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2880 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2881 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2882 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2883 } 2884 } 2885 2886 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2887 // C++11 [dcl.align]p6: 2888 // if any declaration of an entity has an alignment-specifier, 2889 // every defining declaration of that entity shall specify an 2890 // equivalent alignment. 2891 // C11 6.7.5/7: 2892 // If the definition of an object does not have an alignment 2893 // specifier, any other declaration of that object shall also 2894 // have no alignment specifier. 2895 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2896 << OldAlignasAttr; 2897 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2898 << OldAlignasAttr; 2899 } 2900 2901 bool AnyAdded = false; 2902 2903 // Ensure we have an attribute representing the strictest alignment. 2904 if (OldAlign > NewAlign) { 2905 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2906 Clone->setInherited(true); 2907 New->addAttr(Clone); 2908 AnyAdded = true; 2909 } 2910 2911 // Ensure we have an alignas attribute if the old declaration had one. 2912 if (OldAlignasAttr && !NewAlignasAttr && 2913 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2914 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2915 Clone->setInherited(true); 2916 New->addAttr(Clone); 2917 AnyAdded = true; 2918 } 2919 2920 return AnyAdded; 2921 } 2922 2923 #define WANT_DECL_MERGE_LOGIC 2924 #include "clang/Sema/AttrParsedAttrImpl.inc" 2925 #undef WANT_DECL_MERGE_LOGIC 2926 2927 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2928 const InheritableAttr *Attr, 2929 Sema::AvailabilityMergeKind AMK) { 2930 // Diagnose any mutual exclusions between the attribute that we want to add 2931 // and attributes that already exist on the declaration. 2932 if (!DiagnoseMutualExclusions(S, D, Attr)) 2933 return false; 2934 2935 // This function copies an attribute Attr from a previous declaration to the 2936 // new declaration D if the new declaration doesn't itself have that attribute 2937 // yet or if that attribute allows duplicates. 2938 // If you're adding a new attribute that requires logic different from 2939 // "use explicit attribute on decl if present, else use attribute from 2940 // previous decl", for example if the attribute needs to be consistent 2941 // between redeclarations, you need to call a custom merge function here. 2942 InheritableAttr *NewAttr = nullptr; 2943 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2944 NewAttr = S.mergeAvailabilityAttr( 2945 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2946 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2947 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2948 AA->getPriority()); 2949 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2950 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2951 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2952 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2953 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2954 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2955 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2956 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2957 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2958 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2959 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2960 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2961 FA->getFirstArg()); 2962 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2963 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2964 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2965 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2966 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2967 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2968 IA->getInheritanceModel()); 2969 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2970 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2971 &S.Context.Idents.get(AA->getSpelling())); 2972 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2973 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2974 isa<CUDAGlobalAttr>(Attr))) { 2975 // CUDA target attributes are part of function signature for 2976 // overloading purposes and must not be merged. 2977 return false; 2978 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2979 NewAttr = S.mergeMinSizeAttr(D, *MA); 2980 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2981 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2982 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2983 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2984 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2985 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2986 else if (isa<AlignedAttr>(Attr)) 2987 // AlignedAttrs are handled separately, because we need to handle all 2988 // such attributes on a declaration at the same time. 2989 NewAttr = nullptr; 2990 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2991 (AMK == Sema::AMK_Override || 2992 AMK == Sema::AMK_ProtocolImplementation || 2993 AMK == Sema::AMK_OptionalProtocolImplementation)) 2994 NewAttr = nullptr; 2995 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2996 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2997 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2998 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2999 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 3000 NewAttr = S.mergeImportNameAttr(D, *INA); 3001 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 3002 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 3003 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 3004 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 3005 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 3006 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 3007 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 3008 NewAttr = 3009 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 3010 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr)) 3011 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType()); 3012 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 3013 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 3014 3015 if (NewAttr) { 3016 NewAttr->setInherited(true); 3017 D->addAttr(NewAttr); 3018 if (isa<MSInheritanceAttr>(NewAttr)) 3019 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 3020 return true; 3021 } 3022 3023 return false; 3024 } 3025 3026 static const NamedDecl *getDefinition(const Decl *D) { 3027 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 3028 return TD->getDefinition(); 3029 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 3030 const VarDecl *Def = VD->getDefinition(); 3031 if (Def) 3032 return Def; 3033 return VD->getActingDefinition(); 3034 } 3035 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 3036 const FunctionDecl *Def = nullptr; 3037 if (FD->isDefined(Def, true)) 3038 return Def; 3039 } 3040 return nullptr; 3041 } 3042 3043 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 3044 for (const auto *Attribute : D->attrs()) 3045 if (Attribute->getKind() == Kind) 3046 return true; 3047 return false; 3048 } 3049 3050 /// checkNewAttributesAfterDef - If we already have a definition, check that 3051 /// there are no new attributes in this declaration. 3052 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 3053 if (!New->hasAttrs()) 3054 return; 3055 3056 const NamedDecl *Def = getDefinition(Old); 3057 if (!Def || Def == New) 3058 return; 3059 3060 AttrVec &NewAttributes = New->getAttrs(); 3061 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 3062 const Attr *NewAttribute = NewAttributes[I]; 3063 3064 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 3065 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 3066 Sema::SkipBodyInfo SkipBody; 3067 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 3068 3069 // If we're skipping this definition, drop the "alias" attribute. 3070 if (SkipBody.ShouldSkip) { 3071 NewAttributes.erase(NewAttributes.begin() + I); 3072 --E; 3073 continue; 3074 } 3075 } else { 3076 VarDecl *VD = cast<VarDecl>(New); 3077 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 3078 VarDecl::TentativeDefinition 3079 ? diag::err_alias_after_tentative 3080 : diag::err_redefinition; 3081 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 3082 if (Diag == diag::err_redefinition) 3083 S.notePreviousDefinition(Def, VD->getLocation()); 3084 else 3085 S.Diag(Def->getLocation(), diag::note_previous_definition); 3086 VD->setInvalidDecl(); 3087 } 3088 ++I; 3089 continue; 3090 } 3091 3092 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 3093 // Tentative definitions are only interesting for the alias check above. 3094 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 3095 ++I; 3096 continue; 3097 } 3098 } 3099 3100 if (hasAttribute(Def, NewAttribute->getKind())) { 3101 ++I; 3102 continue; // regular attr merging will take care of validating this. 3103 } 3104 3105 if (isa<C11NoReturnAttr>(NewAttribute)) { 3106 // C's _Noreturn is allowed to be added to a function after it is defined. 3107 ++I; 3108 continue; 3109 } else if (isa<UuidAttr>(NewAttribute)) { 3110 // msvc will allow a subsequent definition to add an uuid to a class 3111 ++I; 3112 continue; 3113 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 3114 if (AA->isAlignas()) { 3115 // C++11 [dcl.align]p6: 3116 // if any declaration of an entity has an alignment-specifier, 3117 // every defining declaration of that entity shall specify an 3118 // equivalent alignment. 3119 // C11 6.7.5/7: 3120 // If the definition of an object does not have an alignment 3121 // specifier, any other declaration of that object shall also 3122 // have no alignment specifier. 3123 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 3124 << AA; 3125 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 3126 << AA; 3127 NewAttributes.erase(NewAttributes.begin() + I); 3128 --E; 3129 continue; 3130 } 3131 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 3132 // If there is a C definition followed by a redeclaration with this 3133 // attribute then there are two different definitions. In C++, prefer the 3134 // standard diagnostics. 3135 if (!S.getLangOpts().CPlusPlus) { 3136 S.Diag(NewAttribute->getLocation(), 3137 diag::err_loader_uninitialized_redeclaration); 3138 S.Diag(Def->getLocation(), diag::note_previous_definition); 3139 NewAttributes.erase(NewAttributes.begin() + I); 3140 --E; 3141 continue; 3142 } 3143 } else if (isa<SelectAnyAttr>(NewAttribute) && 3144 cast<VarDecl>(New)->isInline() && 3145 !cast<VarDecl>(New)->isInlineSpecified()) { 3146 // Don't warn about applying selectany to implicitly inline variables. 3147 // Older compilers and language modes would require the use of selectany 3148 // to make such variables inline, and it would have no effect if we 3149 // honored it. 3150 ++I; 3151 continue; 3152 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 3153 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 3154 // declarations after definitions. 3155 ++I; 3156 continue; 3157 } 3158 3159 S.Diag(NewAttribute->getLocation(), 3160 diag::warn_attribute_precede_definition); 3161 S.Diag(Def->getLocation(), diag::note_previous_definition); 3162 NewAttributes.erase(NewAttributes.begin() + I); 3163 --E; 3164 } 3165 } 3166 3167 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 3168 const ConstInitAttr *CIAttr, 3169 bool AttrBeforeInit) { 3170 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 3171 3172 // Figure out a good way to write this specifier on the old declaration. 3173 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 3174 // enough of the attribute list spelling information to extract that without 3175 // heroics. 3176 std::string SuitableSpelling; 3177 if (S.getLangOpts().CPlusPlus20) 3178 SuitableSpelling = std::string( 3179 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 3180 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3181 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3182 InsertLoc, {tok::l_square, tok::l_square, 3183 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 3184 S.PP.getIdentifierInfo("require_constant_initialization"), 3185 tok::r_square, tok::r_square})); 3186 if (SuitableSpelling.empty()) 3187 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 3188 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 3189 S.PP.getIdentifierInfo("require_constant_initialization"), 3190 tok::r_paren, tok::r_paren})); 3191 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 3192 SuitableSpelling = "constinit"; 3193 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 3194 SuitableSpelling = "[[clang::require_constant_initialization]]"; 3195 if (SuitableSpelling.empty()) 3196 SuitableSpelling = "__attribute__((require_constant_initialization))"; 3197 SuitableSpelling += " "; 3198 3199 if (AttrBeforeInit) { 3200 // extern constinit int a; 3201 // int a = 0; // error (missing 'constinit'), accepted as extension 3202 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3203 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3204 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3205 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3206 } else { 3207 // int a = 0; 3208 // constinit extern int a; // error (missing 'constinit') 3209 S.Diag(CIAttr->getLocation(), 3210 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3211 : diag::warn_require_const_init_added_too_late) 3212 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3213 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3214 << CIAttr->isConstinit() 3215 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3216 } 3217 } 3218 3219 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3220 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3221 AvailabilityMergeKind AMK) { 3222 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3223 UsedAttr *NewAttr = OldAttr->clone(Context); 3224 NewAttr->setInherited(true); 3225 New->addAttr(NewAttr); 3226 } 3227 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3228 RetainAttr *NewAttr = OldAttr->clone(Context); 3229 NewAttr->setInherited(true); 3230 New->addAttr(NewAttr); 3231 } 3232 3233 if (!Old->hasAttrs() && !New->hasAttrs()) 3234 return; 3235 3236 // [dcl.constinit]p1: 3237 // If the [constinit] specifier is applied to any declaration of a 3238 // variable, it shall be applied to the initializing declaration. 3239 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3240 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3241 if (bool(OldConstInit) != bool(NewConstInit)) { 3242 const auto *OldVD = cast<VarDecl>(Old); 3243 auto *NewVD = cast<VarDecl>(New); 3244 3245 // Find the initializing declaration. Note that we might not have linked 3246 // the new declaration into the redeclaration chain yet. 3247 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3248 if (!InitDecl && 3249 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3250 InitDecl = NewVD; 3251 3252 if (InitDecl == NewVD) { 3253 // This is the initializing declaration. If it would inherit 'constinit', 3254 // that's ill-formed. (Note that we do not apply this to the attribute 3255 // form). 3256 if (OldConstInit && OldConstInit->isConstinit()) 3257 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3258 /*AttrBeforeInit=*/true); 3259 } else if (NewConstInit) { 3260 // This is the first time we've been told that this declaration should 3261 // have a constant initializer. If we already saw the initializing 3262 // declaration, this is too late. 3263 if (InitDecl && InitDecl != NewVD) { 3264 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3265 /*AttrBeforeInit=*/false); 3266 NewVD->dropAttr<ConstInitAttr>(); 3267 } 3268 } 3269 } 3270 3271 // Attributes declared post-definition are currently ignored. 3272 checkNewAttributesAfterDef(*this, New, Old); 3273 3274 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3275 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3276 if (!OldA->isEquivalent(NewA)) { 3277 // This redeclaration changes __asm__ label. 3278 Diag(New->getLocation(), diag::err_different_asm_label); 3279 Diag(OldA->getLocation(), diag::note_previous_declaration); 3280 } 3281 } else if (Old->isUsed()) { 3282 // This redeclaration adds an __asm__ label to a declaration that has 3283 // already been ODR-used. 3284 Diag(New->getLocation(), diag::err_late_asm_label_name) 3285 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3286 } 3287 } 3288 3289 // Re-declaration cannot add abi_tag's. 3290 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3291 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3292 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3293 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3294 Diag(NewAbiTagAttr->getLocation(), 3295 diag::err_new_abi_tag_on_redeclaration) 3296 << NewTag; 3297 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3298 } 3299 } 3300 } else { 3301 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3302 Diag(Old->getLocation(), diag::note_previous_declaration); 3303 } 3304 } 3305 3306 // This redeclaration adds a section attribute. 3307 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3308 if (auto *VD = dyn_cast<VarDecl>(New)) { 3309 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3310 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3311 Diag(Old->getLocation(), diag::note_previous_declaration); 3312 } 3313 } 3314 } 3315 3316 // Redeclaration adds code-seg attribute. 3317 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3318 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3319 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3320 Diag(New->getLocation(), diag::warn_mismatched_section) 3321 << 0 /*codeseg*/; 3322 Diag(Old->getLocation(), diag::note_previous_declaration); 3323 } 3324 3325 if (!Old->hasAttrs()) 3326 return; 3327 3328 bool foundAny = New->hasAttrs(); 3329 3330 // Ensure that any moving of objects within the allocated map is done before 3331 // we process them. 3332 if (!foundAny) New->setAttrs(AttrVec()); 3333 3334 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3335 // Ignore deprecated/unavailable/availability attributes if requested. 3336 AvailabilityMergeKind LocalAMK = AMK_None; 3337 if (isa<DeprecatedAttr>(I) || 3338 isa<UnavailableAttr>(I) || 3339 isa<AvailabilityAttr>(I)) { 3340 switch (AMK) { 3341 case AMK_None: 3342 continue; 3343 3344 case AMK_Redeclaration: 3345 case AMK_Override: 3346 case AMK_ProtocolImplementation: 3347 case AMK_OptionalProtocolImplementation: 3348 LocalAMK = AMK; 3349 break; 3350 } 3351 } 3352 3353 // Already handled. 3354 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3355 continue; 3356 3357 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3358 foundAny = true; 3359 } 3360 3361 if (mergeAlignedAttrs(*this, New, Old)) 3362 foundAny = true; 3363 3364 if (!foundAny) New->dropAttrs(); 3365 } 3366 3367 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3368 /// to the new one. 3369 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3370 const ParmVarDecl *oldDecl, 3371 Sema &S) { 3372 // C++11 [dcl.attr.depend]p2: 3373 // The first declaration of a function shall specify the 3374 // carries_dependency attribute for its declarator-id if any declaration 3375 // of the function specifies the carries_dependency attribute. 3376 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3377 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3378 S.Diag(CDA->getLocation(), 3379 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3380 // Find the first declaration of the parameter. 3381 // FIXME: Should we build redeclaration chains for function parameters? 3382 const FunctionDecl *FirstFD = 3383 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3384 const ParmVarDecl *FirstVD = 3385 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3386 S.Diag(FirstVD->getLocation(), 3387 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3388 } 3389 3390 // HLSL parameter declarations for inout and out must match between 3391 // declarations. In HLSL inout and out are ambiguous at the call site, but 3392 // have different calling behavior, so you cannot overload a method based on a 3393 // difference between inout and out annotations. 3394 if (S.getLangOpts().HLSL) { 3395 const auto *NDAttr = newDecl->getAttr<HLSLParamModifierAttr>(); 3396 const auto *ODAttr = oldDecl->getAttr<HLSLParamModifierAttr>(); 3397 // We don't need to cover the case where one declaration doesn't have an 3398 // attribute. The only possible case there is if one declaration has an `in` 3399 // attribute and the other declaration has no attribute. This case is 3400 // allowed since parameters are `in` by default. 3401 if (NDAttr && ODAttr && 3402 NDAttr->getSpellingListIndex() != ODAttr->getSpellingListIndex()) { 3403 S.Diag(newDecl->getLocation(), diag::err_hlsl_param_qualifier_mismatch) 3404 << NDAttr << newDecl; 3405 S.Diag(oldDecl->getLocation(), diag::note_previous_declaration_as) 3406 << ODAttr; 3407 } 3408 } 3409 3410 if (!oldDecl->hasAttrs()) 3411 return; 3412 3413 bool foundAny = newDecl->hasAttrs(); 3414 3415 // Ensure that any moving of objects within the allocated map is 3416 // done before we process them. 3417 if (!foundAny) newDecl->setAttrs(AttrVec()); 3418 3419 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3420 if (!DeclHasAttr(newDecl, I)) { 3421 InheritableAttr *newAttr = 3422 cast<InheritableParamAttr>(I->clone(S.Context)); 3423 newAttr->setInherited(true); 3424 newDecl->addAttr(newAttr); 3425 foundAny = true; 3426 } 3427 } 3428 3429 if (!foundAny) newDecl->dropAttrs(); 3430 } 3431 3432 static bool EquivalentArrayTypes(QualType Old, QualType New, 3433 const ASTContext &Ctx) { 3434 3435 auto NoSizeInfo = [&Ctx](QualType Ty) { 3436 if (Ty->isIncompleteArrayType() || Ty->isPointerType()) 3437 return true; 3438 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) 3439 return VAT->getSizeModifier() == ArraySizeModifier::Star; 3440 return false; 3441 }; 3442 3443 // `type[]` is equivalent to `type *` and `type[*]`. 3444 if (NoSizeInfo(Old) && NoSizeInfo(New)) 3445 return true; 3446 3447 // Don't try to compare VLA sizes, unless one of them has the star modifier. 3448 if (Old->isVariableArrayType() && New->isVariableArrayType()) { 3449 const auto *OldVAT = Ctx.getAsVariableArrayType(Old); 3450 const auto *NewVAT = Ctx.getAsVariableArrayType(New); 3451 if ((OldVAT->getSizeModifier() == ArraySizeModifier::Star) ^ 3452 (NewVAT->getSizeModifier() == ArraySizeModifier::Star)) 3453 return false; 3454 return true; 3455 } 3456 3457 // Only compare size, ignore Size modifiers and CVR. 3458 if (Old->isConstantArrayType() && New->isConstantArrayType()) { 3459 return Ctx.getAsConstantArrayType(Old)->getSize() == 3460 Ctx.getAsConstantArrayType(New)->getSize(); 3461 } 3462 3463 // Don't try to compare dependent sized array 3464 if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) { 3465 return true; 3466 } 3467 3468 return Old == New; 3469 } 3470 3471 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3472 const ParmVarDecl *OldParam, 3473 Sema &S) { 3474 if (auto Oldnullability = OldParam->getType()->getNullability()) { 3475 if (auto Newnullability = NewParam->getType()->getNullability()) { 3476 if (*Oldnullability != *Newnullability) { 3477 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3478 << DiagNullabilityKind( 3479 *Newnullability, 3480 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3481 != 0)) 3482 << DiagNullabilityKind( 3483 *Oldnullability, 3484 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3485 != 0)); 3486 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3487 } 3488 } else { 3489 QualType NewT = NewParam->getType(); 3490 NewT = S.Context.getAttributedType( 3491 AttributedType::getNullabilityAttrKind(*Oldnullability), 3492 NewT, NewT); 3493 NewParam->setType(NewT); 3494 } 3495 } 3496 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType()); 3497 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType()); 3498 if (OldParamDT && NewParamDT && 3499 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { 3500 QualType OldParamOT = OldParamDT->getOriginalType(); 3501 QualType NewParamOT = NewParamDT->getOriginalType(); 3502 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { 3503 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) 3504 << NewParam << NewParamOT; 3505 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) 3506 << OldParamOT; 3507 } 3508 } 3509 } 3510 3511 namespace { 3512 3513 /// Used in MergeFunctionDecl to keep track of function parameters in 3514 /// C. 3515 struct GNUCompatibleParamWarning { 3516 ParmVarDecl *OldParm; 3517 ParmVarDecl *NewParm; 3518 QualType PromotedType; 3519 }; 3520 3521 } // end anonymous namespace 3522 3523 // Determine whether the previous declaration was a definition, implicit 3524 // declaration, or a declaration. 3525 template <typename T> 3526 static std::pair<diag::kind, SourceLocation> 3527 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3528 diag::kind PrevDiag; 3529 SourceLocation OldLocation = Old->getLocation(); 3530 if (Old->isThisDeclarationADefinition()) 3531 PrevDiag = diag::note_previous_definition; 3532 else if (Old->isImplicit()) { 3533 PrevDiag = diag::note_previous_implicit_declaration; 3534 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3535 if (FD->getBuiltinID()) 3536 PrevDiag = diag::note_previous_builtin_declaration; 3537 } 3538 if (OldLocation.isInvalid()) 3539 OldLocation = New->getLocation(); 3540 } else 3541 PrevDiag = diag::note_previous_declaration; 3542 return std::make_pair(PrevDiag, OldLocation); 3543 } 3544 3545 /// canRedefineFunction - checks if a function can be redefined. Currently, 3546 /// only extern inline functions can be redefined, and even then only in 3547 /// GNU89 mode. 3548 static bool canRedefineFunction(const FunctionDecl *FD, 3549 const LangOptions& LangOpts) { 3550 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3551 !LangOpts.CPlusPlus && 3552 FD->isInlineSpecified() && 3553 FD->getStorageClass() == SC_Extern); 3554 } 3555 3556 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3557 const AttributedType *AT = T->getAs<AttributedType>(); 3558 while (AT && !AT->isCallingConv()) 3559 AT = AT->getModifiedType()->getAs<AttributedType>(); 3560 return AT; 3561 } 3562 3563 template <typename T> 3564 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3565 const DeclContext *DC = Old->getDeclContext(); 3566 if (DC->isRecord()) 3567 return false; 3568 3569 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3570 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3571 return true; 3572 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3573 return true; 3574 return false; 3575 } 3576 3577 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3578 static bool isExternC(VarTemplateDecl *) { return false; } 3579 static bool isExternC(FunctionTemplateDecl *) { return false; } 3580 3581 /// Check whether a redeclaration of an entity introduced by a 3582 /// using-declaration is valid, given that we know it's not an overload 3583 /// (nor a hidden tag declaration). 3584 template<typename ExpectedDecl> 3585 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3586 ExpectedDecl *New) { 3587 // C++11 [basic.scope.declarative]p4: 3588 // Given a set of declarations in a single declarative region, each of 3589 // which specifies the same unqualified name, 3590 // -- they shall all refer to the same entity, or all refer to functions 3591 // and function templates; or 3592 // -- exactly one declaration shall declare a class name or enumeration 3593 // name that is not a typedef name and the other declarations shall all 3594 // refer to the same variable or enumerator, or all refer to functions 3595 // and function templates; in this case the class name or enumeration 3596 // name is hidden (3.3.10). 3597 3598 // C++11 [namespace.udecl]p14: 3599 // If a function declaration in namespace scope or block scope has the 3600 // same name and the same parameter-type-list as a function introduced 3601 // by a using-declaration, and the declarations do not declare the same 3602 // function, the program is ill-formed. 3603 3604 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3605 if (Old && 3606 !Old->getDeclContext()->getRedeclContext()->Equals( 3607 New->getDeclContext()->getRedeclContext()) && 3608 !(isExternC(Old) && isExternC(New))) 3609 Old = nullptr; 3610 3611 if (!Old) { 3612 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3613 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3614 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3615 return true; 3616 } 3617 return false; 3618 } 3619 3620 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3621 const FunctionDecl *B) { 3622 assert(A->getNumParams() == B->getNumParams()); 3623 3624 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3625 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3626 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3627 if (AttrA == AttrB) 3628 return true; 3629 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3630 AttrA->isDynamic() == AttrB->isDynamic(); 3631 }; 3632 3633 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3634 } 3635 3636 /// If necessary, adjust the semantic declaration context for a qualified 3637 /// declaration to name the correct inline namespace within the qualifier. 3638 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3639 DeclaratorDecl *OldD) { 3640 // The only case where we need to update the DeclContext is when 3641 // redeclaration lookup for a qualified name finds a declaration 3642 // in an inline namespace within the context named by the qualifier: 3643 // 3644 // inline namespace N { int f(); } 3645 // int ::f(); // Sema DC needs adjusting from :: to N::. 3646 // 3647 // For unqualified declarations, the semantic context *can* change 3648 // along the redeclaration chain (for local extern declarations, 3649 // extern "C" declarations, and friend declarations in particular). 3650 if (!NewD->getQualifier()) 3651 return; 3652 3653 // NewD is probably already in the right context. 3654 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3655 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3656 if (NamedDC->Equals(SemaDC)) 3657 return; 3658 3659 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3660 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3661 "unexpected context for redeclaration"); 3662 3663 auto *LexDC = NewD->getLexicalDeclContext(); 3664 auto FixSemaDC = [=](NamedDecl *D) { 3665 if (!D) 3666 return; 3667 D->setDeclContext(SemaDC); 3668 D->setLexicalDeclContext(LexDC); 3669 }; 3670 3671 FixSemaDC(NewD); 3672 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3673 FixSemaDC(FD->getDescribedFunctionTemplate()); 3674 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3675 FixSemaDC(VD->getDescribedVarTemplate()); 3676 } 3677 3678 /// MergeFunctionDecl - We just parsed a function 'New' from 3679 /// declarator D which has the same name and scope as a previous 3680 /// declaration 'Old'. Figure out how to resolve this situation, 3681 /// merging decls or emitting diagnostics as appropriate. 3682 /// 3683 /// In C++, New and Old must be declarations that are not 3684 /// overloaded. Use IsOverload to determine whether New and Old are 3685 /// overloaded, and to select the Old declaration that New should be 3686 /// merged with. 3687 /// 3688 /// Returns true if there was an error, false otherwise. 3689 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3690 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3691 // Verify the old decl was also a function. 3692 FunctionDecl *Old = OldD->getAsFunction(); 3693 if (!Old) { 3694 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3695 if (New->getFriendObjectKind()) { 3696 Diag(New->getLocation(), diag::err_using_decl_friend); 3697 Diag(Shadow->getTargetDecl()->getLocation(), 3698 diag::note_using_decl_target); 3699 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3700 << 0; 3701 return true; 3702 } 3703 3704 // Check whether the two declarations might declare the same function or 3705 // function template. 3706 if (FunctionTemplateDecl *NewTemplate = 3707 New->getDescribedFunctionTemplate()) { 3708 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3709 NewTemplate)) 3710 return true; 3711 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3712 ->getAsFunction(); 3713 } else { 3714 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3715 return true; 3716 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3717 } 3718 } else { 3719 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3720 << New->getDeclName(); 3721 notePreviousDefinition(OldD, New->getLocation()); 3722 return true; 3723 } 3724 } 3725 3726 // If the old declaration was found in an inline namespace and the new 3727 // declaration was qualified, update the DeclContext to match. 3728 adjustDeclContextForDeclaratorDecl(New, Old); 3729 3730 // If the old declaration is invalid, just give up here. 3731 if (Old->isInvalidDecl()) 3732 return true; 3733 3734 // Disallow redeclaration of some builtins. 3735 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3736 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3737 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3738 << Old << Old->getType(); 3739 return true; 3740 } 3741 3742 diag::kind PrevDiag; 3743 SourceLocation OldLocation; 3744 std::tie(PrevDiag, OldLocation) = 3745 getNoteDiagForInvalidRedeclaration(Old, New); 3746 3747 // Don't complain about this if we're in GNU89 mode and the old function 3748 // is an extern inline function. 3749 // Don't complain about specializations. They are not supposed to have 3750 // storage classes. 3751 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3752 New->getStorageClass() == SC_Static && 3753 Old->hasExternalFormalLinkage() && 3754 !New->getTemplateSpecializationInfo() && 3755 !canRedefineFunction(Old, getLangOpts())) { 3756 if (getLangOpts().MicrosoftExt) { 3757 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3758 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3759 } else { 3760 Diag(New->getLocation(), diag::err_static_non_static) << New; 3761 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3762 return true; 3763 } 3764 } 3765 3766 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3767 if (!Old->hasAttr<InternalLinkageAttr>()) { 3768 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3769 << ILA; 3770 Diag(Old->getLocation(), diag::note_previous_declaration); 3771 New->dropAttr<InternalLinkageAttr>(); 3772 } 3773 3774 if (auto *EA = New->getAttr<ErrorAttr>()) { 3775 if (!Old->hasAttr<ErrorAttr>()) { 3776 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3777 Diag(Old->getLocation(), diag::note_previous_declaration); 3778 New->dropAttr<ErrorAttr>(); 3779 } 3780 } 3781 3782 if (CheckRedeclarationInModule(New, Old)) 3783 return true; 3784 3785 if (!getLangOpts().CPlusPlus) { 3786 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3787 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3788 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3789 << New << OldOvl; 3790 3791 // Try our best to find a decl that actually has the overloadable 3792 // attribute for the note. In most cases (e.g. programs with only one 3793 // broken declaration/definition), this won't matter. 3794 // 3795 // FIXME: We could do this if we juggled some extra state in 3796 // OverloadableAttr, rather than just removing it. 3797 const Decl *DiagOld = Old; 3798 if (OldOvl) { 3799 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3800 const auto *A = D->getAttr<OverloadableAttr>(); 3801 return A && !A->isImplicit(); 3802 }); 3803 // If we've implicitly added *all* of the overloadable attrs to this 3804 // chain, emitting a "previous redecl" note is pointless. 3805 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3806 } 3807 3808 if (DiagOld) 3809 Diag(DiagOld->getLocation(), 3810 diag::note_attribute_overloadable_prev_overload) 3811 << OldOvl; 3812 3813 if (OldOvl) 3814 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3815 else 3816 New->dropAttr<OverloadableAttr>(); 3817 } 3818 } 3819 3820 // It is not permitted to redeclare an SME function with different SME 3821 // attributes. 3822 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) { 3823 Diag(New->getLocation(), diag::err_sme_attr_mismatch) 3824 << New->getType() << Old->getType(); 3825 Diag(OldLocation, diag::note_previous_declaration); 3826 return true; 3827 } 3828 3829 // If a function is first declared with a calling convention, but is later 3830 // declared or defined without one, all following decls assume the calling 3831 // convention of the first. 3832 // 3833 // It's OK if a function is first declared without a calling convention, 3834 // but is later declared or defined with the default calling convention. 3835 // 3836 // To test if either decl has an explicit calling convention, we look for 3837 // AttributedType sugar nodes on the type as written. If they are missing or 3838 // were canonicalized away, we assume the calling convention was implicit. 3839 // 3840 // Note also that we DO NOT return at this point, because we still have 3841 // other tests to run. 3842 QualType OldQType = Context.getCanonicalType(Old->getType()); 3843 QualType NewQType = Context.getCanonicalType(New->getType()); 3844 const FunctionType *OldType = cast<FunctionType>(OldQType); 3845 const FunctionType *NewType = cast<FunctionType>(NewQType); 3846 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3847 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3848 bool RequiresAdjustment = false; 3849 3850 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3851 FunctionDecl *First = Old->getFirstDecl(); 3852 const FunctionType *FT = 3853 First->getType().getCanonicalType()->castAs<FunctionType>(); 3854 FunctionType::ExtInfo FI = FT->getExtInfo(); 3855 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3856 if (!NewCCExplicit) { 3857 // Inherit the CC from the previous declaration if it was specified 3858 // there but not here. 3859 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3860 RequiresAdjustment = true; 3861 } else if (Old->getBuiltinID()) { 3862 // Builtin attribute isn't propagated to the new one yet at this point, 3863 // so we check if the old one is a builtin. 3864 3865 // Calling Conventions on a Builtin aren't really useful and setting a 3866 // default calling convention and cdecl'ing some builtin redeclarations is 3867 // common, so warn and ignore the calling convention on the redeclaration. 3868 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3869 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3870 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3871 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3872 RequiresAdjustment = true; 3873 } else { 3874 // Calling conventions aren't compatible, so complain. 3875 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3876 Diag(New->getLocation(), diag::err_cconv_change) 3877 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3878 << !FirstCCExplicit 3879 << (!FirstCCExplicit ? "" : 3880 FunctionType::getNameForCallConv(FI.getCC())); 3881 3882 // Put the note on the first decl, since it is the one that matters. 3883 Diag(First->getLocation(), diag::note_previous_declaration); 3884 return true; 3885 } 3886 } 3887 3888 // FIXME: diagnose the other way around? 3889 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3890 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3891 RequiresAdjustment = true; 3892 } 3893 3894 // Merge regparm attribute. 3895 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3896 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3897 if (NewTypeInfo.getHasRegParm()) { 3898 Diag(New->getLocation(), diag::err_regparm_mismatch) 3899 << NewType->getRegParmType() 3900 << OldType->getRegParmType(); 3901 Diag(OldLocation, diag::note_previous_declaration); 3902 return true; 3903 } 3904 3905 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3906 RequiresAdjustment = true; 3907 } 3908 3909 // Merge ns_returns_retained attribute. 3910 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3911 if (NewTypeInfo.getProducesResult()) { 3912 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3913 << "'ns_returns_retained'"; 3914 Diag(OldLocation, diag::note_previous_declaration); 3915 return true; 3916 } 3917 3918 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3919 RequiresAdjustment = true; 3920 } 3921 3922 if (OldTypeInfo.getNoCallerSavedRegs() != 3923 NewTypeInfo.getNoCallerSavedRegs()) { 3924 if (NewTypeInfo.getNoCallerSavedRegs()) { 3925 AnyX86NoCallerSavedRegistersAttr *Attr = 3926 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3927 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3928 Diag(OldLocation, diag::note_previous_declaration); 3929 return true; 3930 } 3931 3932 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3933 RequiresAdjustment = true; 3934 } 3935 3936 if (RequiresAdjustment) { 3937 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3938 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3939 New->setType(QualType(AdjustedType, 0)); 3940 NewQType = Context.getCanonicalType(New->getType()); 3941 } 3942 3943 // If this redeclaration makes the function inline, we may need to add it to 3944 // UndefinedButUsed. 3945 if (!Old->isInlined() && New->isInlined() && 3946 !New->hasAttr<GNUInlineAttr>() && 3947 !getLangOpts().GNUInline && 3948 Old->isUsed(false) && 3949 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3950 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3951 SourceLocation())); 3952 3953 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3954 // about it. 3955 if (New->hasAttr<GNUInlineAttr>() && 3956 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3957 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3958 } 3959 3960 // If pass_object_size params don't match up perfectly, this isn't a valid 3961 // redeclaration. 3962 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3963 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3964 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3965 << New->getDeclName(); 3966 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3967 return true; 3968 } 3969 3970 if (getLangOpts().CPlusPlus) { 3971 OldQType = Context.getCanonicalType(Old->getType()); 3972 NewQType = Context.getCanonicalType(New->getType()); 3973 3974 // Go back to the type source info to compare the declared return types, 3975 // per C++1y [dcl.type.auto]p13: 3976 // Redeclarations or specializations of a function or function template 3977 // with a declared return type that uses a placeholder type shall also 3978 // use that placeholder, not a deduced type. 3979 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3980 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3981 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3982 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3983 OldDeclaredReturnType)) { 3984 QualType ResQT; 3985 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3986 OldDeclaredReturnType->isObjCObjectPointerType()) 3987 // FIXME: This does the wrong thing for a deduced return type. 3988 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3989 if (ResQT.isNull()) { 3990 if (New->isCXXClassMember() && New->isOutOfLine()) 3991 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3992 << New << New->getReturnTypeSourceRange(); 3993 else 3994 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3995 << New->getReturnTypeSourceRange(); 3996 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3997 << Old->getReturnTypeSourceRange(); 3998 return true; 3999 } 4000 else 4001 NewQType = ResQT; 4002 } 4003 4004 QualType OldReturnType = OldType->getReturnType(); 4005 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 4006 if (OldReturnType != NewReturnType) { 4007 // If this function has a deduced return type and has already been 4008 // defined, copy the deduced value from the old declaration. 4009 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 4010 if (OldAT && OldAT->isDeduced()) { 4011 QualType DT = OldAT->getDeducedType(); 4012 if (DT.isNull()) { 4013 New->setType(SubstAutoTypeDependent(New->getType())); 4014 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 4015 } else { 4016 New->setType(SubstAutoType(New->getType(), DT)); 4017 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 4018 } 4019 } 4020 } 4021 4022 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 4023 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 4024 if (OldMethod && NewMethod) { 4025 // Preserve triviality. 4026 NewMethod->setTrivial(OldMethod->isTrivial()); 4027 4028 // MSVC allows explicit template specialization at class scope: 4029 // 2 CXXMethodDecls referring to the same function will be injected. 4030 // We don't want a redeclaration error. 4031 bool IsClassScopeExplicitSpecialization = 4032 OldMethod->isFunctionTemplateSpecialization() && 4033 NewMethod->isFunctionTemplateSpecialization(); 4034 bool isFriend = NewMethod->getFriendObjectKind(); 4035 4036 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 4037 !IsClassScopeExplicitSpecialization) { 4038 // -- Member function declarations with the same name and the 4039 // same parameter types cannot be overloaded if any of them 4040 // is a static member function declaration. 4041 if (OldMethod->isStatic() != NewMethod->isStatic()) { 4042 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 4043 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4044 return true; 4045 } 4046 4047 // C++ [class.mem]p1: 4048 // [...] A member shall not be declared twice in the 4049 // member-specification, except that a nested class or member 4050 // class template can be declared and then later defined. 4051 if (!inTemplateInstantiation()) { 4052 unsigned NewDiag; 4053 if (isa<CXXConstructorDecl>(OldMethod)) 4054 NewDiag = diag::err_constructor_redeclared; 4055 else if (isa<CXXDestructorDecl>(NewMethod)) 4056 NewDiag = diag::err_destructor_redeclared; 4057 else if (isa<CXXConversionDecl>(NewMethod)) 4058 NewDiag = diag::err_conv_function_redeclared; 4059 else 4060 NewDiag = diag::err_member_redeclared; 4061 4062 Diag(New->getLocation(), NewDiag); 4063 } else { 4064 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 4065 << New << New->getType(); 4066 } 4067 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4068 return true; 4069 4070 // Complain if this is an explicit declaration of a special 4071 // member that was initially declared implicitly. 4072 // 4073 // As an exception, it's okay to befriend such methods in order 4074 // to permit the implicit constructor/destructor/operator calls. 4075 } else if (OldMethod->isImplicit()) { 4076 if (isFriend) { 4077 NewMethod->setImplicit(); 4078 } else { 4079 Diag(NewMethod->getLocation(), 4080 diag::err_definition_of_implicitly_declared_member) 4081 << New << getSpecialMember(OldMethod); 4082 return true; 4083 } 4084 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 4085 Diag(NewMethod->getLocation(), 4086 diag::err_definition_of_explicitly_defaulted_member) 4087 << getSpecialMember(OldMethod); 4088 return true; 4089 } 4090 } 4091 4092 // C++1z [over.load]p2 4093 // Certain function declarations cannot be overloaded: 4094 // -- Function declarations that differ only in the return type, 4095 // the exception specification, or both cannot be overloaded. 4096 4097 // Check the exception specifications match. This may recompute the type of 4098 // both Old and New if it resolved exception specifications, so grab the 4099 // types again after this. Because this updates the type, we do this before 4100 // any of the other checks below, which may update the "de facto" NewQType 4101 // but do not necessarily update the type of New. 4102 if (CheckEquivalentExceptionSpec(Old, New)) 4103 return true; 4104 4105 // C++11 [dcl.attr.noreturn]p1: 4106 // The first declaration of a function shall specify the noreturn 4107 // attribute if any declaration of that function specifies the noreturn 4108 // attribute. 4109 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 4110 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 4111 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 4112 << NRA; 4113 Diag(Old->getLocation(), diag::note_previous_declaration); 4114 } 4115 4116 // C++11 [dcl.attr.depend]p2: 4117 // The first declaration of a function shall specify the 4118 // carries_dependency attribute for its declarator-id if any declaration 4119 // of the function specifies the carries_dependency attribute. 4120 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 4121 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 4122 Diag(CDA->getLocation(), 4123 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 4124 Diag(Old->getFirstDecl()->getLocation(), 4125 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 4126 } 4127 4128 // (C++98 8.3.5p3): 4129 // All declarations for a function shall agree exactly in both the 4130 // return type and the parameter-type-list. 4131 // We also want to respect all the extended bits except noreturn. 4132 4133 // noreturn should now match unless the old type info didn't have it. 4134 QualType OldQTypeForComparison = OldQType; 4135 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 4136 auto *OldType = OldQType->castAs<FunctionProtoType>(); 4137 const FunctionType *OldTypeForComparison 4138 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 4139 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 4140 assert(OldQTypeForComparison.isCanonical()); 4141 } 4142 4143 if (haveIncompatibleLanguageLinkages(Old, New)) { 4144 // As a special case, retain the language linkage from previous 4145 // declarations of a friend function as an extension. 4146 // 4147 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 4148 // and is useful because there's otherwise no way to specify language 4149 // linkage within class scope. 4150 // 4151 // Check cautiously as the friend object kind isn't yet complete. 4152 if (New->getFriendObjectKind() != Decl::FOK_None) { 4153 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 4154 Diag(OldLocation, PrevDiag); 4155 } else { 4156 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4157 Diag(OldLocation, PrevDiag); 4158 return true; 4159 } 4160 } 4161 4162 // If the function types are compatible, merge the declarations. Ignore the 4163 // exception specifier because it was already checked above in 4164 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 4165 // about incompatible types under -fms-compatibility. 4166 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 4167 NewQType)) 4168 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4169 4170 // If the types are imprecise (due to dependent constructs in friends or 4171 // local extern declarations), it's OK if they differ. We'll check again 4172 // during instantiation. 4173 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 4174 return false; 4175 4176 // Fall through for conflicting redeclarations and redefinitions. 4177 } 4178 4179 // C: Function types need to be compatible, not identical. This handles 4180 // duplicate function decls like "void f(int); void f(enum X);" properly. 4181 if (!getLangOpts().CPlusPlus) { 4182 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 4183 // type is specified by a function definition that contains a (possibly 4184 // empty) identifier list, both shall agree in the number of parameters 4185 // and the type of each parameter shall be compatible with the type that 4186 // results from the application of default argument promotions to the 4187 // type of the corresponding identifier. ... 4188 // This cannot be handled by ASTContext::typesAreCompatible() because that 4189 // doesn't know whether the function type is for a definition or not when 4190 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 4191 // we need to cover here is that the number of arguments agree as the 4192 // default argument promotion rules were already checked by 4193 // ASTContext::typesAreCompatible(). 4194 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 4195 Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) { 4196 if (Old->hasInheritedPrototype()) 4197 Old = Old->getCanonicalDecl(); 4198 Diag(New->getLocation(), diag::err_conflicting_types) << New; 4199 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 4200 return true; 4201 } 4202 4203 // If we are merging two functions where only one of them has a prototype, 4204 // we may have enough information to decide to issue a diagnostic that the 4205 // function without a protoype will change behavior in C23. This handles 4206 // cases like: 4207 // void i(); void i(int j); 4208 // void i(int j); void i(); 4209 // void i(); void i(int j) {} 4210 // See ActOnFinishFunctionBody() for other cases of the behavior change 4211 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 4212 // type without a prototype. 4213 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 4214 !New->isImplicit() && !Old->isImplicit()) { 4215 const FunctionDecl *WithProto, *WithoutProto; 4216 if (New->hasWrittenPrototype()) { 4217 WithProto = New; 4218 WithoutProto = Old; 4219 } else { 4220 WithProto = Old; 4221 WithoutProto = New; 4222 } 4223 4224 if (WithProto->getNumParams() != 0) { 4225 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { 4226 // The one without the prototype will be changing behavior in C23, so 4227 // warn about that one so long as it's a user-visible declaration. 4228 bool IsWithoutProtoADef = false, IsWithProtoADef = false; 4229 if (WithoutProto == New) 4230 IsWithoutProtoADef = NewDeclIsDefn; 4231 else 4232 IsWithProtoADef = NewDeclIsDefn; 4233 Diag(WithoutProto->getLocation(), 4234 diag::warn_non_prototype_changes_behavior) 4235 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) 4236 << (WithoutProto == Old) << IsWithProtoADef; 4237 4238 // The reason the one without the prototype will be changing behavior 4239 // is because of the one with the prototype, so note that so long as 4240 // it's a user-visible declaration. There is one exception to this: 4241 // when the new declaration is a definition without a prototype, the 4242 // old declaration with a prototype is not the cause of the issue, 4243 // and that does not need to be noted because the one with a 4244 // prototype will not change behavior in C23. 4245 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && 4246 !IsWithoutProtoADef) 4247 Diag(WithProto->getLocation(), diag::note_conflicting_prototype); 4248 } 4249 } 4250 } 4251 4252 if (Context.typesAreCompatible(OldQType, NewQType)) { 4253 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4254 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4255 const FunctionProtoType *OldProto = nullptr; 4256 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4257 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4258 // The old declaration provided a function prototype, but the 4259 // new declaration does not. Merge in the prototype. 4260 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4261 NewQType = Context.getFunctionType(NewFuncType->getReturnType(), 4262 OldProto->getParamTypes(), 4263 OldProto->getExtProtoInfo()); 4264 New->setType(NewQType); 4265 New->setHasInheritedPrototype(); 4266 4267 // Synthesize parameters with the same types. 4268 SmallVector<ParmVarDecl *, 16> Params; 4269 for (const auto &ParamType : OldProto->param_types()) { 4270 ParmVarDecl *Param = ParmVarDecl::Create( 4271 Context, New, SourceLocation(), SourceLocation(), nullptr, 4272 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4273 Param->setScopeInfo(0, Params.size()); 4274 Param->setImplicit(); 4275 Params.push_back(Param); 4276 } 4277 4278 New->setParams(Params); 4279 } 4280 4281 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4282 } 4283 } 4284 4285 // Check if the function types are compatible when pointer size address 4286 // spaces are ignored. 4287 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4288 return false; 4289 4290 // GNU C permits a K&R definition to follow a prototype declaration 4291 // if the declared types of the parameters in the K&R definition 4292 // match the types in the prototype declaration, even when the 4293 // promoted types of the parameters from the K&R definition differ 4294 // from the types in the prototype. GCC then keeps the types from 4295 // the prototype. 4296 // 4297 // If a variadic prototype is followed by a non-variadic K&R definition, 4298 // the K&R definition becomes variadic. This is sort of an edge case, but 4299 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4300 // C99 6.9.1p8. 4301 if (!getLangOpts().CPlusPlus && 4302 Old->hasPrototype() && !New->hasPrototype() && 4303 New->getType()->getAs<FunctionProtoType>() && 4304 Old->getNumParams() == New->getNumParams()) { 4305 SmallVector<QualType, 16> ArgTypes; 4306 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4307 const FunctionProtoType *OldProto 4308 = Old->getType()->getAs<FunctionProtoType>(); 4309 const FunctionProtoType *NewProto 4310 = New->getType()->getAs<FunctionProtoType>(); 4311 4312 // Determine whether this is the GNU C extension. 4313 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4314 NewProto->getReturnType()); 4315 bool LooseCompatible = !MergedReturn.isNull(); 4316 for (unsigned Idx = 0, End = Old->getNumParams(); 4317 LooseCompatible && Idx != End; ++Idx) { 4318 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4319 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4320 if (Context.typesAreCompatible(OldParm->getType(), 4321 NewProto->getParamType(Idx))) { 4322 ArgTypes.push_back(NewParm->getType()); 4323 } else if (Context.typesAreCompatible(OldParm->getType(), 4324 NewParm->getType(), 4325 /*CompareUnqualified=*/true)) { 4326 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4327 NewProto->getParamType(Idx) }; 4328 Warnings.push_back(Warn); 4329 ArgTypes.push_back(NewParm->getType()); 4330 } else 4331 LooseCompatible = false; 4332 } 4333 4334 if (LooseCompatible) { 4335 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4336 Diag(Warnings[Warn].NewParm->getLocation(), 4337 diag::ext_param_promoted_not_compatible_with_prototype) 4338 << Warnings[Warn].PromotedType 4339 << Warnings[Warn].OldParm->getType(); 4340 if (Warnings[Warn].OldParm->getLocation().isValid()) 4341 Diag(Warnings[Warn].OldParm->getLocation(), 4342 diag::note_previous_declaration); 4343 } 4344 4345 if (MergeTypeWithOld) 4346 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4347 OldProto->getExtProtoInfo())); 4348 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4349 } 4350 4351 // Fall through to diagnose conflicting types. 4352 } 4353 4354 // A function that has already been declared has been redeclared or 4355 // defined with a different type; show an appropriate diagnostic. 4356 4357 // If the previous declaration was an implicitly-generated builtin 4358 // declaration, then at the very least we should use a specialized note. 4359 unsigned BuiltinID; 4360 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4361 // If it's actually a library-defined builtin function like 'malloc' 4362 // or 'printf', just warn about the incompatible redeclaration. 4363 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4364 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4365 Diag(OldLocation, diag::note_previous_builtin_declaration) 4366 << Old << Old->getType(); 4367 return false; 4368 } 4369 4370 PrevDiag = diag::note_previous_builtin_declaration; 4371 } 4372 4373 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4374 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4375 return true; 4376 } 4377 4378 /// Completes the merge of two function declarations that are 4379 /// known to be compatible. 4380 /// 4381 /// This routine handles the merging of attributes and other 4382 /// properties of function declarations from the old declaration to 4383 /// the new declaration, once we know that New is in fact a 4384 /// redeclaration of Old. 4385 /// 4386 /// \returns false 4387 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4388 Scope *S, bool MergeTypeWithOld) { 4389 // Merge the attributes 4390 mergeDeclAttributes(New, Old); 4391 4392 // Merge "pure" flag. 4393 if (Old->isPureVirtual()) 4394 New->setIsPureVirtual(); 4395 4396 // Merge "used" flag. 4397 if (Old->getMostRecentDecl()->isUsed(false)) 4398 New->setIsUsed(); 4399 4400 // Merge attributes from the parameters. These can mismatch with K&R 4401 // declarations. 4402 if (New->getNumParams() == Old->getNumParams()) 4403 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4404 ParmVarDecl *NewParam = New->getParamDecl(i); 4405 ParmVarDecl *OldParam = Old->getParamDecl(i); 4406 mergeParamDeclAttributes(NewParam, OldParam, *this); 4407 mergeParamDeclTypes(NewParam, OldParam, *this); 4408 } 4409 4410 if (getLangOpts().CPlusPlus) 4411 return MergeCXXFunctionDecl(New, Old, S); 4412 4413 // Merge the function types so the we get the composite types for the return 4414 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4415 // was visible. 4416 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4417 if (!Merged.isNull() && MergeTypeWithOld) 4418 New->setType(Merged); 4419 4420 return false; 4421 } 4422 4423 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4424 ObjCMethodDecl *oldMethod) { 4425 // Merge the attributes, including deprecated/unavailable 4426 AvailabilityMergeKind MergeKind = 4427 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4428 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4429 : AMK_ProtocolImplementation) 4430 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4431 : AMK_Override; 4432 4433 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4434 4435 // Merge attributes from the parameters. 4436 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4437 oe = oldMethod->param_end(); 4438 for (ObjCMethodDecl::param_iterator 4439 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4440 ni != ne && oi != oe; ++ni, ++oi) 4441 mergeParamDeclAttributes(*ni, *oi, *this); 4442 4443 CheckObjCMethodOverride(newMethod, oldMethod); 4444 } 4445 4446 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4447 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4448 4449 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4450 ? diag::err_redefinition_different_type 4451 : diag::err_redeclaration_different_type) 4452 << New->getDeclName() << New->getType() << Old->getType(); 4453 4454 diag::kind PrevDiag; 4455 SourceLocation OldLocation; 4456 std::tie(PrevDiag, OldLocation) 4457 = getNoteDiagForInvalidRedeclaration(Old, New); 4458 S.Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4459 New->setInvalidDecl(); 4460 } 4461 4462 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4463 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4464 /// emitting diagnostics as appropriate. 4465 /// 4466 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4467 /// to here in AddInitializerToDecl. We can't check them before the initializer 4468 /// is attached. 4469 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4470 bool MergeTypeWithOld) { 4471 if (New->isInvalidDecl() || Old->isInvalidDecl() || New->getType()->containsErrors() || Old->getType()->containsErrors()) 4472 return; 4473 4474 QualType MergedT; 4475 if (getLangOpts().CPlusPlus) { 4476 if (New->getType()->isUndeducedType()) { 4477 // We don't know what the new type is until the initializer is attached. 4478 return; 4479 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4480 // These could still be something that needs exception specs checked. 4481 return MergeVarDeclExceptionSpecs(New, Old); 4482 } 4483 // C++ [basic.link]p10: 4484 // [...] the types specified by all declarations referring to a given 4485 // object or function shall be identical, except that declarations for an 4486 // array object can specify array types that differ by the presence or 4487 // absence of a major array bound (8.3.4). 4488 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4489 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4490 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4491 4492 // We are merging a variable declaration New into Old. If it has an array 4493 // bound, and that bound differs from Old's bound, we should diagnose the 4494 // mismatch. 4495 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4496 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4497 PrevVD = PrevVD->getPreviousDecl()) { 4498 QualType PrevVDTy = PrevVD->getType(); 4499 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4500 continue; 4501 4502 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4503 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4504 } 4505 } 4506 4507 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4508 if (Context.hasSameType(OldArray->getElementType(), 4509 NewArray->getElementType())) 4510 MergedT = New->getType(); 4511 } 4512 // FIXME: Check visibility. New is hidden but has a complete type. If New 4513 // has no array bound, it should not inherit one from Old, if Old is not 4514 // visible. 4515 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4516 if (Context.hasSameType(OldArray->getElementType(), 4517 NewArray->getElementType())) 4518 MergedT = Old->getType(); 4519 } 4520 } 4521 else if (New->getType()->isObjCObjectPointerType() && 4522 Old->getType()->isObjCObjectPointerType()) { 4523 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4524 Old->getType()); 4525 } 4526 } else { 4527 // C 6.2.7p2: 4528 // All declarations that refer to the same object or function shall have 4529 // compatible type. 4530 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4531 } 4532 if (MergedT.isNull()) { 4533 // It's OK if we couldn't merge types if either type is dependent, for a 4534 // block-scope variable. In other cases (static data members of class 4535 // templates, variable templates, ...), we require the types to be 4536 // equivalent. 4537 // FIXME: The C++ standard doesn't say anything about this. 4538 if ((New->getType()->isDependentType() || 4539 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4540 // If the old type was dependent, we can't merge with it, so the new type 4541 // becomes dependent for now. We'll reproduce the original type when we 4542 // instantiate the TypeSourceInfo for the variable. 4543 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4544 New->setType(Context.DependentTy); 4545 return; 4546 } 4547 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4548 } 4549 4550 // Don't actually update the type on the new declaration if the old 4551 // declaration was an extern declaration in a different scope. 4552 if (MergeTypeWithOld) 4553 New->setType(MergedT); 4554 } 4555 4556 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4557 LookupResult &Previous) { 4558 // C11 6.2.7p4: 4559 // For an identifier with internal or external linkage declared 4560 // in a scope in which a prior declaration of that identifier is 4561 // visible, if the prior declaration specifies internal or 4562 // external linkage, the type of the identifier at the later 4563 // declaration becomes the composite type. 4564 // 4565 // If the variable isn't visible, we do not merge with its type. 4566 if (Previous.isShadowed()) 4567 return false; 4568 4569 if (S.getLangOpts().CPlusPlus) { 4570 // C++11 [dcl.array]p3: 4571 // If there is a preceding declaration of the entity in the same 4572 // scope in which the bound was specified, an omitted array bound 4573 // is taken to be the same as in that earlier declaration. 4574 return NewVD->isPreviousDeclInSameBlockScope() || 4575 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4576 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4577 } else { 4578 // If the old declaration was function-local, don't merge with its 4579 // type unless we're in the same function. 4580 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4581 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4582 } 4583 } 4584 4585 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4586 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4587 /// situation, merging decls or emitting diagnostics as appropriate. 4588 /// 4589 /// Tentative definition rules (C99 6.9.2p2) are checked by 4590 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4591 /// definitions here, since the initializer hasn't been attached. 4592 /// 4593 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4594 // If the new decl is already invalid, don't do any other checking. 4595 if (New->isInvalidDecl()) 4596 return; 4597 4598 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4599 return; 4600 4601 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4602 4603 // Verify the old decl was also a variable or variable template. 4604 VarDecl *Old = nullptr; 4605 VarTemplateDecl *OldTemplate = nullptr; 4606 if (Previous.isSingleResult()) { 4607 if (NewTemplate) { 4608 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4609 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4610 4611 if (auto *Shadow = 4612 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4613 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4614 return New->setInvalidDecl(); 4615 } else { 4616 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4617 4618 if (auto *Shadow = 4619 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4620 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4621 return New->setInvalidDecl(); 4622 } 4623 } 4624 if (!Old) { 4625 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4626 << New->getDeclName(); 4627 notePreviousDefinition(Previous.getRepresentativeDecl(), 4628 New->getLocation()); 4629 return New->setInvalidDecl(); 4630 } 4631 4632 // If the old declaration was found in an inline namespace and the new 4633 // declaration was qualified, update the DeclContext to match. 4634 adjustDeclContextForDeclaratorDecl(New, Old); 4635 4636 // Ensure the template parameters are compatible. 4637 if (NewTemplate && 4638 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4639 OldTemplate->getTemplateParameters(), 4640 /*Complain=*/true, TPL_TemplateMatch)) 4641 return New->setInvalidDecl(); 4642 4643 // C++ [class.mem]p1: 4644 // A member shall not be declared twice in the member-specification [...] 4645 // 4646 // Here, we need only consider static data members. 4647 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4648 Diag(New->getLocation(), diag::err_duplicate_member) 4649 << New->getIdentifier(); 4650 Diag(Old->getLocation(), diag::note_previous_declaration); 4651 New->setInvalidDecl(); 4652 } 4653 4654 mergeDeclAttributes(New, Old); 4655 // Warn if an already-declared variable is made a weak_import in a subsequent 4656 // declaration 4657 if (New->hasAttr<WeakImportAttr>() && 4658 Old->getStorageClass() == SC_None && 4659 !Old->hasAttr<WeakImportAttr>()) { 4660 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4661 Diag(Old->getLocation(), diag::note_previous_declaration); 4662 // Remove weak_import attribute on new declaration. 4663 New->dropAttr<WeakImportAttr>(); 4664 } 4665 4666 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4667 if (!Old->hasAttr<InternalLinkageAttr>()) { 4668 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4669 << ILA; 4670 Diag(Old->getLocation(), diag::note_previous_declaration); 4671 New->dropAttr<InternalLinkageAttr>(); 4672 } 4673 4674 // Merge the types. 4675 VarDecl *MostRecent = Old->getMostRecentDecl(); 4676 if (MostRecent != Old) { 4677 MergeVarDeclTypes(New, MostRecent, 4678 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4679 if (New->isInvalidDecl()) 4680 return; 4681 } 4682 4683 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4684 if (New->isInvalidDecl()) 4685 return; 4686 4687 diag::kind PrevDiag; 4688 SourceLocation OldLocation; 4689 std::tie(PrevDiag, OldLocation) = 4690 getNoteDiagForInvalidRedeclaration(Old, New); 4691 4692 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4693 if (New->getStorageClass() == SC_Static && 4694 !New->isStaticDataMember() && 4695 Old->hasExternalFormalLinkage()) { 4696 if (getLangOpts().MicrosoftExt) { 4697 Diag(New->getLocation(), diag::ext_static_non_static) 4698 << New->getDeclName(); 4699 Diag(OldLocation, PrevDiag); 4700 } else { 4701 Diag(New->getLocation(), diag::err_static_non_static) 4702 << New->getDeclName(); 4703 Diag(OldLocation, PrevDiag); 4704 return New->setInvalidDecl(); 4705 } 4706 } 4707 // C99 6.2.2p4: 4708 // For an identifier declared with the storage-class specifier 4709 // extern in a scope in which a prior declaration of that 4710 // identifier is visible,23) if the prior declaration specifies 4711 // internal or external linkage, the linkage of the identifier at 4712 // the later declaration is the same as the linkage specified at 4713 // the prior declaration. If no prior declaration is visible, or 4714 // if the prior declaration specifies no linkage, then the 4715 // identifier has external linkage. 4716 if (New->hasExternalStorage() && Old->hasLinkage()) 4717 /* Okay */; 4718 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4719 !New->isStaticDataMember() && 4720 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4721 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4722 Diag(OldLocation, PrevDiag); 4723 return New->setInvalidDecl(); 4724 } 4725 4726 // Check if extern is followed by non-extern and vice-versa. 4727 if (New->hasExternalStorage() && 4728 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4729 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4730 Diag(OldLocation, PrevDiag); 4731 return New->setInvalidDecl(); 4732 } 4733 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4734 !New->hasExternalStorage()) { 4735 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4736 Diag(OldLocation, PrevDiag); 4737 return New->setInvalidDecl(); 4738 } 4739 4740 if (CheckRedeclarationInModule(New, Old)) 4741 return; 4742 4743 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4744 4745 // FIXME: The test for external storage here seems wrong? We still 4746 // need to check for mismatches. 4747 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4748 // Don't complain about out-of-line definitions of static members. 4749 !(Old->getLexicalDeclContext()->isRecord() && 4750 !New->getLexicalDeclContext()->isRecord())) { 4751 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4752 Diag(OldLocation, PrevDiag); 4753 return New->setInvalidDecl(); 4754 } 4755 4756 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4757 if (VarDecl *Def = Old->getDefinition()) { 4758 // C++1z [dcl.fcn.spec]p4: 4759 // If the definition of a variable appears in a translation unit before 4760 // its first declaration as inline, the program is ill-formed. 4761 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4762 Diag(Def->getLocation(), diag::note_previous_definition); 4763 } 4764 } 4765 4766 // If this redeclaration makes the variable inline, we may need to add it to 4767 // UndefinedButUsed. 4768 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4769 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4770 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4771 SourceLocation())); 4772 4773 if (New->getTLSKind() != Old->getTLSKind()) { 4774 if (!Old->getTLSKind()) { 4775 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4776 Diag(OldLocation, PrevDiag); 4777 } else if (!New->getTLSKind()) { 4778 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4779 Diag(OldLocation, PrevDiag); 4780 } else { 4781 // Do not allow redeclaration to change the variable between requiring 4782 // static and dynamic initialization. 4783 // FIXME: GCC allows this, but uses the TLS keyword on the first 4784 // declaration to determine the kind. Do we need to be compatible here? 4785 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4786 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4787 Diag(OldLocation, PrevDiag); 4788 } 4789 } 4790 4791 // C++ doesn't have tentative definitions, so go right ahead and check here. 4792 if (getLangOpts().CPlusPlus) { 4793 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4794 Old->getCanonicalDecl()->isConstexpr()) { 4795 // This definition won't be a definition any more once it's been merged. 4796 Diag(New->getLocation(), 4797 diag::warn_deprecated_redundant_constexpr_static_def); 4798 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { 4799 VarDecl *Def = Old->getDefinition(); 4800 if (Def && checkVarDeclRedefinition(Def, New)) 4801 return; 4802 } 4803 } 4804 4805 if (haveIncompatibleLanguageLinkages(Old, New)) { 4806 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4807 Diag(OldLocation, PrevDiag); 4808 New->setInvalidDecl(); 4809 return; 4810 } 4811 4812 // Merge "used" flag. 4813 if (Old->getMostRecentDecl()->isUsed(false)) 4814 New->setIsUsed(); 4815 4816 // Keep a chain of previous declarations. 4817 New->setPreviousDecl(Old); 4818 if (NewTemplate) 4819 NewTemplate->setPreviousDecl(OldTemplate); 4820 4821 // Inherit access appropriately. 4822 New->setAccess(Old->getAccess()); 4823 if (NewTemplate) 4824 NewTemplate->setAccess(New->getAccess()); 4825 4826 if (Old->isInline()) 4827 New->setImplicitlyInline(); 4828 } 4829 4830 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4831 SourceManager &SrcMgr = getSourceManager(); 4832 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4833 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4834 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4835 auto FOld = SrcMgr.getFileEntryRefForID(FOldDecLoc.first); 4836 auto &HSI = PP.getHeaderSearchInfo(); 4837 StringRef HdrFilename = 4838 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4839 4840 auto noteFromModuleOrInclude = [&](Module *Mod, 4841 SourceLocation IncLoc) -> bool { 4842 // Redefinition errors with modules are common with non modular mapped 4843 // headers, example: a non-modular header H in module A that also gets 4844 // included directly in a TU. Pointing twice to the same header/definition 4845 // is confusing, try to get better diagnostics when modules is on. 4846 if (IncLoc.isValid()) { 4847 if (Mod) { 4848 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4849 << HdrFilename.str() << Mod->getFullModuleName(); 4850 if (!Mod->DefinitionLoc.isInvalid()) 4851 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4852 << Mod->getFullModuleName(); 4853 } else { 4854 Diag(IncLoc, diag::note_redefinition_include_same_file) 4855 << HdrFilename.str(); 4856 } 4857 return true; 4858 } 4859 4860 return false; 4861 }; 4862 4863 // Is it the same file and same offset? Provide more information on why 4864 // this leads to a redefinition error. 4865 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4866 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4867 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4868 bool EmittedDiag = 4869 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4870 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4871 4872 // If the header has no guards, emit a note suggesting one. 4873 if (FOld && !HSI.isFileMultipleIncludeGuarded(*FOld)) 4874 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4875 4876 if (EmittedDiag) 4877 return; 4878 } 4879 4880 // Redefinition coming from different files or couldn't do better above. 4881 if (Old->getLocation().isValid()) 4882 Diag(Old->getLocation(), diag::note_previous_definition); 4883 } 4884 4885 /// We've just determined that \p Old and \p New both appear to be definitions 4886 /// of the same variable. Either diagnose or fix the problem. 4887 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4888 if (!hasVisibleDefinition(Old) && 4889 (New->getFormalLinkage() == Linkage::Internal || New->isInline() || 4890 isa<VarTemplateSpecializationDecl>(New) || 4891 New->getDescribedVarTemplate() || New->getNumTemplateParameterLists() || 4892 New->getDeclContext()->isDependentContext())) { 4893 // The previous definition is hidden, and multiple definitions are 4894 // permitted (in separate TUs). Demote this to a declaration. 4895 New->demoteThisDefinitionToDeclaration(); 4896 4897 // Make the canonical definition visible. 4898 if (auto *OldTD = Old->getDescribedVarTemplate()) 4899 makeMergedDefinitionVisible(OldTD); 4900 makeMergedDefinitionVisible(Old); 4901 return false; 4902 } else { 4903 Diag(New->getLocation(), diag::err_redefinition) << New; 4904 notePreviousDefinition(Old, New->getLocation()); 4905 New->setInvalidDecl(); 4906 return true; 4907 } 4908 } 4909 4910 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4911 /// no declarator (e.g. "struct foo;") is parsed. 4912 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4913 DeclSpec &DS, 4914 const ParsedAttributesView &DeclAttrs, 4915 RecordDecl *&AnonRecord) { 4916 return ParsedFreeStandingDeclSpec( 4917 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord); 4918 } 4919 4920 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4921 // disambiguate entities defined in different scopes. 4922 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4923 // compatibility. 4924 // We will pick our mangling number depending on which version of MSVC is being 4925 // targeted. 4926 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4927 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4928 ? S->getMSCurManglingNumber() 4929 : S->getMSLastManglingNumber(); 4930 } 4931 4932 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4933 if (!Context.getLangOpts().CPlusPlus) 4934 return; 4935 4936 if (isa<CXXRecordDecl>(Tag->getParent())) { 4937 // If this tag is the direct child of a class, number it if 4938 // it is anonymous. 4939 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4940 return; 4941 MangleNumberingContext &MCtx = 4942 Context.getManglingNumberContext(Tag->getParent()); 4943 Context.setManglingNumber( 4944 Tag, MCtx.getManglingNumber( 4945 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4946 return; 4947 } 4948 4949 // If this tag isn't a direct child of a class, number it if it is local. 4950 MangleNumberingContext *MCtx; 4951 Decl *ManglingContextDecl; 4952 std::tie(MCtx, ManglingContextDecl) = 4953 getCurrentMangleNumberContext(Tag->getDeclContext()); 4954 if (MCtx) { 4955 Context.setManglingNumber( 4956 Tag, MCtx->getManglingNumber( 4957 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4958 } 4959 } 4960 4961 namespace { 4962 struct NonCLikeKind { 4963 enum { 4964 None, 4965 BaseClass, 4966 DefaultMemberInit, 4967 Lambda, 4968 Friend, 4969 OtherMember, 4970 Invalid, 4971 } Kind = None; 4972 SourceRange Range; 4973 4974 explicit operator bool() { return Kind != None; } 4975 }; 4976 } 4977 4978 /// Determine whether a class is C-like, according to the rules of C++ 4979 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4980 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4981 if (RD->isInvalidDecl()) 4982 return {NonCLikeKind::Invalid, {}}; 4983 4984 // C++ [dcl.typedef]p9: [P1766R1] 4985 // An unnamed class with a typedef name for linkage purposes shall not 4986 // 4987 // -- have any base classes 4988 if (RD->getNumBases()) 4989 return {NonCLikeKind::BaseClass, 4990 SourceRange(RD->bases_begin()->getBeginLoc(), 4991 RD->bases_end()[-1].getEndLoc())}; 4992 bool Invalid = false; 4993 for (Decl *D : RD->decls()) { 4994 // Don't complain about things we already diagnosed. 4995 if (D->isInvalidDecl()) { 4996 Invalid = true; 4997 continue; 4998 } 4999 5000 // -- have any [...] default member initializers 5001 if (auto *FD = dyn_cast<FieldDecl>(D)) { 5002 if (FD->hasInClassInitializer()) { 5003 auto *Init = FD->getInClassInitializer(); 5004 return {NonCLikeKind::DefaultMemberInit, 5005 Init ? Init->getSourceRange() : D->getSourceRange()}; 5006 } 5007 continue; 5008 } 5009 5010 // FIXME: We don't allow friend declarations. This violates the wording of 5011 // P1766, but not the intent. 5012 if (isa<FriendDecl>(D)) 5013 return {NonCLikeKind::Friend, D->getSourceRange()}; 5014 5015 // -- declare any members other than non-static data members, member 5016 // enumerations, or member classes, 5017 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 5018 isa<EnumDecl>(D)) 5019 continue; 5020 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 5021 if (!MemberRD) { 5022 if (D->isImplicit()) 5023 continue; 5024 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 5025 } 5026 5027 // -- contain a lambda-expression, 5028 if (MemberRD->isLambda()) 5029 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 5030 5031 // and all member classes shall also satisfy these requirements 5032 // (recursively). 5033 if (MemberRD->isThisDeclarationADefinition()) { 5034 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 5035 return Kind; 5036 } 5037 } 5038 5039 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 5040 } 5041 5042 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 5043 TypedefNameDecl *NewTD) { 5044 if (TagFromDeclSpec->isInvalidDecl()) 5045 return; 5046 5047 // Do nothing if the tag already has a name for linkage purposes. 5048 if (TagFromDeclSpec->hasNameForLinkage()) 5049 return; 5050 5051 // A well-formed anonymous tag must always be a TUK_Definition. 5052 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 5053 5054 // The type must match the tag exactly; no qualifiers allowed. 5055 if (!Context.hasSameType(NewTD->getUnderlyingType(), 5056 Context.getTagDeclType(TagFromDeclSpec))) { 5057 if (getLangOpts().CPlusPlus) 5058 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 5059 return; 5060 } 5061 5062 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 5063 // An unnamed class with a typedef name for linkage purposes shall [be 5064 // C-like]. 5065 // 5066 // FIXME: Also diagnose if we've already computed the linkage. That ideally 5067 // shouldn't happen, but there are constructs that the language rule doesn't 5068 // disallow for which we can't reasonably avoid computing linkage early. 5069 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 5070 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 5071 : NonCLikeKind(); 5072 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 5073 if (NonCLike || ChangesLinkage) { 5074 if (NonCLike.Kind == NonCLikeKind::Invalid) 5075 return; 5076 5077 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 5078 if (ChangesLinkage) { 5079 // If the linkage changes, we can't accept this as an extension. 5080 if (NonCLike.Kind == NonCLikeKind::None) 5081 DiagID = diag::err_typedef_changes_linkage; 5082 else 5083 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 5084 } 5085 5086 SourceLocation FixitLoc = 5087 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 5088 llvm::SmallString<40> TextToInsert; 5089 TextToInsert += ' '; 5090 TextToInsert += NewTD->getIdentifier()->getName(); 5091 5092 Diag(FixitLoc, DiagID) 5093 << isa<TypeAliasDecl>(NewTD) 5094 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 5095 if (NonCLike.Kind != NonCLikeKind::None) { 5096 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 5097 << NonCLike.Kind - 1 << NonCLike.Range; 5098 } 5099 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 5100 << NewTD << isa<TypeAliasDecl>(NewTD); 5101 5102 if (ChangesLinkage) 5103 return; 5104 } 5105 5106 // Otherwise, set this as the anon-decl typedef for the tag. 5107 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 5108 } 5109 5110 static unsigned GetDiagnosticTypeSpecifierID(const DeclSpec &DS) { 5111 DeclSpec::TST T = DS.getTypeSpecType(); 5112 switch (T) { 5113 case DeclSpec::TST_class: 5114 return 0; 5115 case DeclSpec::TST_struct: 5116 return 1; 5117 case DeclSpec::TST_interface: 5118 return 2; 5119 case DeclSpec::TST_union: 5120 return 3; 5121 case DeclSpec::TST_enum: 5122 if (const auto *ED = dyn_cast<EnumDecl>(DS.getRepAsDecl())) { 5123 if (ED->isScopedUsingClassTag()) 5124 return 5; 5125 if (ED->isScoped()) 5126 return 6; 5127 } 5128 return 4; 5129 default: 5130 llvm_unreachable("unexpected type specifier"); 5131 } 5132 } 5133 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 5134 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 5135 /// parameters to cope with template friend declarations. 5136 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 5137 DeclSpec &DS, 5138 const ParsedAttributesView &DeclAttrs, 5139 MultiTemplateParamsArg TemplateParams, 5140 bool IsExplicitInstantiation, 5141 RecordDecl *&AnonRecord) { 5142 Decl *TagD = nullptr; 5143 TagDecl *Tag = nullptr; 5144 if (DS.getTypeSpecType() == DeclSpec::TST_class || 5145 DS.getTypeSpecType() == DeclSpec::TST_struct || 5146 DS.getTypeSpecType() == DeclSpec::TST_interface || 5147 DS.getTypeSpecType() == DeclSpec::TST_union || 5148 DS.getTypeSpecType() == DeclSpec::TST_enum) { 5149 TagD = DS.getRepAsDecl(); 5150 5151 if (!TagD) // We probably had an error 5152 return nullptr; 5153 5154 // Note that the above type specs guarantee that the 5155 // type rep is a Decl, whereas in many of the others 5156 // it's a Type. 5157 if (isa<TagDecl>(TagD)) 5158 Tag = cast<TagDecl>(TagD); 5159 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 5160 Tag = CTD->getTemplatedDecl(); 5161 } 5162 5163 if (Tag) { 5164 handleTagNumbering(Tag, S); 5165 Tag->setFreeStanding(); 5166 if (Tag->isInvalidDecl()) 5167 return Tag; 5168 } 5169 5170 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 5171 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 5172 // or incomplete types shall not be restrict-qualified." 5173 if (TypeQuals & DeclSpec::TQ_restrict) 5174 Diag(DS.getRestrictSpecLoc(), 5175 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 5176 << DS.getSourceRange(); 5177 } 5178 5179 if (DS.isInlineSpecified()) 5180 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 5181 << getLangOpts().CPlusPlus17; 5182 5183 if (DS.hasConstexprSpecifier()) { 5184 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 5185 // and definitions of functions and variables. 5186 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 5187 // the declaration of a function or function template 5188 if (Tag) 5189 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 5190 << GetDiagnosticTypeSpecifierID(DS) 5191 << static_cast<int>(DS.getConstexprSpecifier()); 5192 else 5193 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 5194 << static_cast<int>(DS.getConstexprSpecifier()); 5195 // Don't emit warnings after this error. 5196 return TagD; 5197 } 5198 5199 DiagnoseFunctionSpecifiers(DS); 5200 5201 if (DS.isFriendSpecified()) { 5202 // If we're dealing with a decl but not a TagDecl, assume that 5203 // whatever routines created it handled the friendship aspect. 5204 if (TagD && !Tag) 5205 return nullptr; 5206 return ActOnFriendTypeDecl(S, DS, TemplateParams); 5207 } 5208 5209 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 5210 bool IsExplicitSpecialization = 5211 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 5212 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 5213 !IsExplicitInstantiation && !IsExplicitSpecialization && 5214 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 5215 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 5216 // nested-name-specifier unless it is an explicit instantiation 5217 // or an explicit specialization. 5218 // 5219 // FIXME: We allow class template partial specializations here too, per the 5220 // obvious intent of DR1819. 5221 // 5222 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 5223 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 5224 << GetDiagnosticTypeSpecifierID(DS) << SS.getRange(); 5225 return nullptr; 5226 } 5227 5228 // Track whether this decl-specifier declares anything. 5229 bool DeclaresAnything = true; 5230 5231 // Handle anonymous struct definitions. 5232 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 5233 if (!Record->getDeclName() && Record->isCompleteDefinition() && 5234 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 5235 if (getLangOpts().CPlusPlus || 5236 Record->getDeclContext()->isRecord()) { 5237 // If CurContext is a DeclContext that can contain statements, 5238 // RecursiveASTVisitor won't visit the decls that 5239 // BuildAnonymousStructOrUnion() will put into CurContext. 5240 // Also store them here so that they can be part of the 5241 // DeclStmt that gets created in this case. 5242 // FIXME: Also return the IndirectFieldDecls created by 5243 // BuildAnonymousStructOr union, for the same reason? 5244 if (CurContext->isFunctionOrMethod()) 5245 AnonRecord = Record; 5246 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 5247 Context.getPrintingPolicy()); 5248 } 5249 5250 DeclaresAnything = false; 5251 } 5252 } 5253 5254 // C11 6.7.2.1p2: 5255 // A struct-declaration that does not declare an anonymous structure or 5256 // anonymous union shall contain a struct-declarator-list. 5257 // 5258 // This rule also existed in C89 and C99; the grammar for struct-declaration 5259 // did not permit a struct-declaration without a struct-declarator-list. 5260 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5261 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5262 // Check for Microsoft C extension: anonymous struct/union member. 5263 // Handle 2 kinds of anonymous struct/union: 5264 // struct STRUCT; 5265 // union UNION; 5266 // and 5267 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5268 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5269 if ((Tag && Tag->getDeclName()) || 5270 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5271 RecordDecl *Record = nullptr; 5272 if (Tag) 5273 Record = dyn_cast<RecordDecl>(Tag); 5274 else if (const RecordType *RT = 5275 DS.getRepAsType().get()->getAsStructureType()) 5276 Record = RT->getDecl(); 5277 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5278 Record = UT->getDecl(); 5279 5280 if (Record && getLangOpts().MicrosoftExt) { 5281 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5282 << Record->isUnion() << DS.getSourceRange(); 5283 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5284 } 5285 5286 DeclaresAnything = false; 5287 } 5288 } 5289 5290 // Skip all the checks below if we have a type error. 5291 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5292 (TagD && TagD->isInvalidDecl())) 5293 return TagD; 5294 5295 if (getLangOpts().CPlusPlus && 5296 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5297 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5298 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5299 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5300 DeclaresAnything = false; 5301 5302 if (!DS.isMissingDeclaratorOk()) { 5303 // Customize diagnostic for a typedef missing a name. 5304 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5305 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5306 << DS.getSourceRange(); 5307 else 5308 DeclaresAnything = false; 5309 } 5310 5311 if (DS.isModulePrivateSpecified() && 5312 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5313 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5314 << llvm::to_underlying(Tag->getTagKind()) 5315 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5316 5317 ActOnDocumentableDecl(TagD); 5318 5319 // C 6.7/2: 5320 // A declaration [...] shall declare at least a declarator [...], a tag, 5321 // or the members of an enumeration. 5322 // C++ [dcl.dcl]p3: 5323 // [If there are no declarators], and except for the declaration of an 5324 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5325 // names into the program, or shall redeclare a name introduced by a 5326 // previous declaration. 5327 if (!DeclaresAnything) { 5328 // In C, we allow this as a (popular) extension / bug. Don't bother 5329 // producing further diagnostics for redundant qualifiers after this. 5330 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5331 ? diag::err_no_declarators 5332 : diag::ext_no_declarators) 5333 << DS.getSourceRange(); 5334 return TagD; 5335 } 5336 5337 // C++ [dcl.stc]p1: 5338 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5339 // init-declarator-list of the declaration shall not be empty. 5340 // C++ [dcl.fct.spec]p1: 5341 // If a cv-qualifier appears in a decl-specifier-seq, the 5342 // init-declarator-list of the declaration shall not be empty. 5343 // 5344 // Spurious qualifiers here appear to be valid in C. 5345 unsigned DiagID = diag::warn_standalone_specifier; 5346 if (getLangOpts().CPlusPlus) 5347 DiagID = diag::ext_standalone_specifier; 5348 5349 // Note that a linkage-specification sets a storage class, but 5350 // 'extern "C" struct foo;' is actually valid and not theoretically 5351 // useless. 5352 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5353 if (SCS == DeclSpec::SCS_mutable) 5354 // Since mutable is not a viable storage class specifier in C, there is 5355 // no reason to treat it as an extension. Instead, diagnose as an error. 5356 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5357 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5358 Diag(DS.getStorageClassSpecLoc(), DiagID) 5359 << DeclSpec::getSpecifierName(SCS); 5360 } 5361 5362 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5363 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5364 << DeclSpec::getSpecifierName(TSCS); 5365 if (DS.getTypeQualifiers()) { 5366 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5367 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5368 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5369 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5370 // Restrict is covered above. 5371 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5372 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5373 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5374 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5375 } 5376 5377 // Warn about ignored type attributes, for example: 5378 // __attribute__((aligned)) struct A; 5379 // Attributes should be placed after tag to apply to type declaration. 5380 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { 5381 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5382 if (TypeSpecType == DeclSpec::TST_class || 5383 TypeSpecType == DeclSpec::TST_struct || 5384 TypeSpecType == DeclSpec::TST_interface || 5385 TypeSpecType == DeclSpec::TST_union || 5386 TypeSpecType == DeclSpec::TST_enum) { 5387 5388 auto EmitAttributeDiagnostic = [this, &DS](const ParsedAttr &AL) { 5389 unsigned DiagnosticId = diag::warn_declspec_attribute_ignored; 5390 if (AL.isAlignas() && !getLangOpts().CPlusPlus) 5391 DiagnosticId = diag::warn_attribute_ignored; 5392 else if (AL.isRegularKeywordAttribute()) 5393 DiagnosticId = diag::err_declspec_keyword_has_no_effect; 5394 else 5395 DiagnosticId = diag::warn_declspec_attribute_ignored; 5396 Diag(AL.getLoc(), DiagnosticId) 5397 << AL << GetDiagnosticTypeSpecifierID(DS); 5398 }; 5399 5400 llvm::for_each(DS.getAttributes(), EmitAttributeDiagnostic); 5401 llvm::for_each(DeclAttrs, EmitAttributeDiagnostic); 5402 } 5403 } 5404 5405 return TagD; 5406 } 5407 5408 /// We are trying to inject an anonymous member into the given scope; 5409 /// check if there's an existing declaration that can't be overloaded. 5410 /// 5411 /// \return true if this is a forbidden redeclaration 5412 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, 5413 DeclContext *Owner, 5414 DeclarationName Name, 5415 SourceLocation NameLoc, bool IsUnion, 5416 StorageClass SC) { 5417 LookupResult R(SemaRef, Name, NameLoc, 5418 Owner->isRecord() ? Sema::LookupMemberName 5419 : Sema::LookupOrdinaryName, 5420 Sema::ForVisibleRedeclaration); 5421 if (!SemaRef.LookupName(R, S)) return false; 5422 5423 // Pick a representative declaration. 5424 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5425 assert(PrevDecl && "Expected a non-null Decl"); 5426 5427 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5428 return false; 5429 5430 if (SC == StorageClass::SC_None && 5431 PrevDecl->isPlaceholderVar(SemaRef.getLangOpts()) && 5432 (Owner->isFunctionOrMethod() || Owner->isRecord())) { 5433 if (!Owner->isRecord()) 5434 SemaRef.DiagPlaceholderVariableDefinition(NameLoc); 5435 return false; 5436 } 5437 5438 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5439 << IsUnion << Name; 5440 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5441 5442 return true; 5443 } 5444 5445 void Sema::ActOnDefinedDeclarationSpecifier(Decl *D) { 5446 if (auto *RD = dyn_cast_if_present<RecordDecl>(D)) 5447 DiagPlaceholderFieldDeclDefinitions(RD); 5448 } 5449 5450 /// Emit diagnostic warnings for placeholder members. 5451 /// We can only do that after the class is fully constructed, 5452 /// as anonymous union/structs can insert placeholders 5453 /// in their parent scope (which might be a Record). 5454 void Sema::DiagPlaceholderFieldDeclDefinitions(RecordDecl *Record) { 5455 if (!getLangOpts().CPlusPlus) 5456 return; 5457 5458 // This function can be parsed before we have validated the 5459 // structure as an anonymous struct 5460 if (Record->isAnonymousStructOrUnion()) 5461 return; 5462 5463 const NamedDecl *First = 0; 5464 for (const Decl *D : Record->decls()) { 5465 const NamedDecl *ND = dyn_cast<NamedDecl>(D); 5466 if (!ND || !ND->isPlaceholderVar(getLangOpts())) 5467 continue; 5468 if (!First) 5469 First = ND; 5470 else 5471 DiagPlaceholderVariableDefinition(ND->getLocation()); 5472 } 5473 } 5474 5475 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5476 /// anonymous struct or union AnonRecord into the owning context Owner 5477 /// and scope S. This routine will be invoked just after we realize 5478 /// that an unnamed union or struct is actually an anonymous union or 5479 /// struct, e.g., 5480 /// 5481 /// @code 5482 /// union { 5483 /// int i; 5484 /// float f; 5485 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5486 /// // f into the surrounding scope.x 5487 /// @endcode 5488 /// 5489 /// This routine is recursive, injecting the names of nested anonymous 5490 /// structs/unions into the owning context and scope as well. 5491 static bool 5492 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5493 RecordDecl *AnonRecord, AccessSpecifier AS, 5494 StorageClass SC, 5495 SmallVectorImpl<NamedDecl *> &Chaining) { 5496 bool Invalid = false; 5497 5498 // Look every FieldDecl and IndirectFieldDecl with a name. 5499 for (auto *D : AnonRecord->decls()) { 5500 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5501 cast<NamedDecl>(D)->getDeclName()) { 5502 ValueDecl *VD = cast<ValueDecl>(D); 5503 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5504 VD->getLocation(), AnonRecord->isUnion(), 5505 SC)) { 5506 // C++ [class.union]p2: 5507 // The names of the members of an anonymous union shall be 5508 // distinct from the names of any other entity in the 5509 // scope in which the anonymous union is declared. 5510 Invalid = true; 5511 } else { 5512 // C++ [class.union]p2: 5513 // For the purpose of name lookup, after the anonymous union 5514 // definition, the members of the anonymous union are 5515 // considered to have been defined in the scope in which the 5516 // anonymous union is declared. 5517 unsigned OldChainingSize = Chaining.size(); 5518 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5519 Chaining.append(IF->chain_begin(), IF->chain_end()); 5520 else 5521 Chaining.push_back(VD); 5522 5523 assert(Chaining.size() >= 2); 5524 NamedDecl **NamedChain = 5525 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5526 for (unsigned i = 0; i < Chaining.size(); i++) 5527 NamedChain[i] = Chaining[i]; 5528 5529 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5530 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5531 VD->getType(), {NamedChain, Chaining.size()}); 5532 5533 for (const auto *Attr : VD->attrs()) 5534 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5535 5536 IndirectField->setAccess(AS); 5537 IndirectField->setImplicit(); 5538 SemaRef.PushOnScopeChains(IndirectField, S); 5539 5540 // That includes picking up the appropriate access specifier. 5541 if (AS != AS_none) IndirectField->setAccess(AS); 5542 5543 Chaining.resize(OldChainingSize); 5544 } 5545 } 5546 } 5547 5548 return Invalid; 5549 } 5550 5551 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5552 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5553 /// illegal input values are mapped to SC_None. 5554 static StorageClass 5555 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5556 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5557 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5558 "Parser allowed 'typedef' as storage class VarDecl."); 5559 switch (StorageClassSpec) { 5560 case DeclSpec::SCS_unspecified: return SC_None; 5561 case DeclSpec::SCS_extern: 5562 if (DS.isExternInLinkageSpec()) 5563 return SC_None; 5564 return SC_Extern; 5565 case DeclSpec::SCS_static: return SC_Static; 5566 case DeclSpec::SCS_auto: return SC_Auto; 5567 case DeclSpec::SCS_register: return SC_Register; 5568 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5569 // Illegal SCSs map to None: error reporting is up to the caller. 5570 case DeclSpec::SCS_mutable: // Fall through. 5571 case DeclSpec::SCS_typedef: return SC_None; 5572 } 5573 llvm_unreachable("unknown storage class specifier"); 5574 } 5575 5576 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5577 assert(Record->hasInClassInitializer()); 5578 5579 for (const auto *I : Record->decls()) { 5580 const auto *FD = dyn_cast<FieldDecl>(I); 5581 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5582 FD = IFD->getAnonField(); 5583 if (FD && FD->hasInClassInitializer()) 5584 return FD->getLocation(); 5585 } 5586 5587 llvm_unreachable("couldn't find in-class initializer"); 5588 } 5589 5590 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5591 SourceLocation DefaultInitLoc) { 5592 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5593 return; 5594 5595 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5596 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5597 } 5598 5599 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5600 CXXRecordDecl *AnonUnion) { 5601 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5602 return; 5603 5604 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5605 } 5606 5607 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5608 /// anonymous structure or union. Anonymous unions are a C++ feature 5609 /// (C++ [class.union]) and a C11 feature; anonymous structures 5610 /// are a C11 feature and GNU C++ extension. 5611 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5612 AccessSpecifier AS, 5613 RecordDecl *Record, 5614 const PrintingPolicy &Policy) { 5615 DeclContext *Owner = Record->getDeclContext(); 5616 5617 // Diagnose whether this anonymous struct/union is an extension. 5618 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5619 Diag(Record->getLocation(), diag::ext_anonymous_union); 5620 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5621 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5622 else if (!Record->isUnion() && !getLangOpts().C11) 5623 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5624 5625 // C and C++ require different kinds of checks for anonymous 5626 // structs/unions. 5627 bool Invalid = false; 5628 if (getLangOpts().CPlusPlus) { 5629 const char *PrevSpec = nullptr; 5630 if (Record->isUnion()) { 5631 // C++ [class.union]p6: 5632 // C++17 [class.union.anon]p2: 5633 // Anonymous unions declared in a named namespace or in the 5634 // global namespace shall be declared static. 5635 unsigned DiagID; 5636 DeclContext *OwnerScope = Owner->getRedeclContext(); 5637 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5638 (OwnerScope->isTranslationUnit() || 5639 (OwnerScope->isNamespace() && 5640 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5641 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5642 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5643 5644 // Recover by adding 'static'. 5645 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5646 PrevSpec, DiagID, Policy); 5647 } 5648 // C++ [class.union]p6: 5649 // A storage class is not allowed in a declaration of an 5650 // anonymous union in a class scope. 5651 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5652 isa<RecordDecl>(Owner)) { 5653 Diag(DS.getStorageClassSpecLoc(), 5654 diag::err_anonymous_union_with_storage_spec) 5655 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5656 5657 // Recover by removing the storage specifier. 5658 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5659 SourceLocation(), 5660 PrevSpec, DiagID, Context.getPrintingPolicy()); 5661 } 5662 } 5663 5664 // Ignore const/volatile/restrict qualifiers. 5665 if (DS.getTypeQualifiers()) { 5666 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5667 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5668 << Record->isUnion() << "const" 5669 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5670 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5671 Diag(DS.getVolatileSpecLoc(), 5672 diag::ext_anonymous_struct_union_qualified) 5673 << Record->isUnion() << "volatile" 5674 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5675 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5676 Diag(DS.getRestrictSpecLoc(), 5677 diag::ext_anonymous_struct_union_qualified) 5678 << Record->isUnion() << "restrict" 5679 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5680 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5681 Diag(DS.getAtomicSpecLoc(), 5682 diag::ext_anonymous_struct_union_qualified) 5683 << Record->isUnion() << "_Atomic" 5684 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5685 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5686 Diag(DS.getUnalignedSpecLoc(), 5687 diag::ext_anonymous_struct_union_qualified) 5688 << Record->isUnion() << "__unaligned" 5689 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5690 5691 DS.ClearTypeQualifiers(); 5692 } 5693 5694 // C++ [class.union]p2: 5695 // The member-specification of an anonymous union shall only 5696 // define non-static data members. [Note: nested types and 5697 // functions cannot be declared within an anonymous union. ] 5698 for (auto *Mem : Record->decls()) { 5699 // Ignore invalid declarations; we already diagnosed them. 5700 if (Mem->isInvalidDecl()) 5701 continue; 5702 5703 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5704 // C++ [class.union]p3: 5705 // An anonymous union shall not have private or protected 5706 // members (clause 11). 5707 assert(FD->getAccess() != AS_none); 5708 if (FD->getAccess() != AS_public) { 5709 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5710 << Record->isUnion() << (FD->getAccess() == AS_protected); 5711 Invalid = true; 5712 } 5713 5714 // C++ [class.union]p1 5715 // An object of a class with a non-trivial constructor, a non-trivial 5716 // copy constructor, a non-trivial destructor, or a non-trivial copy 5717 // assignment operator cannot be a member of a union, nor can an 5718 // array of such objects. 5719 if (CheckNontrivialField(FD)) 5720 Invalid = true; 5721 } else if (Mem->isImplicit()) { 5722 // Any implicit members are fine. 5723 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5724 // This is a type that showed up in an 5725 // elaborated-type-specifier inside the anonymous struct or 5726 // union, but which actually declares a type outside of the 5727 // anonymous struct or union. It's okay. 5728 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5729 if (!MemRecord->isAnonymousStructOrUnion() && 5730 MemRecord->getDeclName()) { 5731 // Visual C++ allows type definition in anonymous struct or union. 5732 if (getLangOpts().MicrosoftExt) 5733 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5734 << Record->isUnion(); 5735 else { 5736 // This is a nested type declaration. 5737 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5738 << Record->isUnion(); 5739 Invalid = true; 5740 } 5741 } else { 5742 // This is an anonymous type definition within another anonymous type. 5743 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5744 // not part of standard C++. 5745 Diag(MemRecord->getLocation(), 5746 diag::ext_anonymous_record_with_anonymous_type) 5747 << Record->isUnion(); 5748 } 5749 } else if (isa<AccessSpecDecl>(Mem)) { 5750 // Any access specifier is fine. 5751 } else if (isa<StaticAssertDecl>(Mem)) { 5752 // In C++1z, static_assert declarations are also fine. 5753 } else { 5754 // We have something that isn't a non-static data 5755 // member. Complain about it. 5756 unsigned DK = diag::err_anonymous_record_bad_member; 5757 if (isa<TypeDecl>(Mem)) 5758 DK = diag::err_anonymous_record_with_type; 5759 else if (isa<FunctionDecl>(Mem)) 5760 DK = diag::err_anonymous_record_with_function; 5761 else if (isa<VarDecl>(Mem)) 5762 DK = diag::err_anonymous_record_with_static; 5763 5764 // Visual C++ allows type definition in anonymous struct or union. 5765 if (getLangOpts().MicrosoftExt && 5766 DK == diag::err_anonymous_record_with_type) 5767 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5768 << Record->isUnion(); 5769 else { 5770 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5771 Invalid = true; 5772 } 5773 } 5774 } 5775 5776 // C++11 [class.union]p8 (DR1460): 5777 // At most one variant member of a union may have a 5778 // brace-or-equal-initializer. 5779 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5780 Owner->isRecord()) 5781 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5782 cast<CXXRecordDecl>(Record)); 5783 } 5784 5785 if (!Record->isUnion() && !Owner->isRecord()) { 5786 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5787 << getLangOpts().CPlusPlus; 5788 Invalid = true; 5789 } 5790 5791 // C++ [dcl.dcl]p3: 5792 // [If there are no declarators], and except for the declaration of an 5793 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5794 // names into the program 5795 // C++ [class.mem]p2: 5796 // each such member-declaration shall either declare at least one member 5797 // name of the class or declare at least one unnamed bit-field 5798 // 5799 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5800 if (getLangOpts().CPlusPlus && Record->field_empty()) 5801 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5802 5803 // Mock up a declarator. 5804 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); 5805 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5806 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc); 5807 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5808 5809 // Create a declaration for this anonymous struct/union. 5810 NamedDecl *Anon = nullptr; 5811 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5812 Anon = FieldDecl::Create( 5813 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5814 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5815 /*BitWidth=*/nullptr, /*Mutable=*/false, 5816 /*InitStyle=*/ICIS_NoInit); 5817 Anon->setAccess(AS); 5818 ProcessDeclAttributes(S, Anon, Dc); 5819 5820 if (getLangOpts().CPlusPlus) 5821 FieldCollector->Add(cast<FieldDecl>(Anon)); 5822 } else { 5823 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5824 if (SCSpec == DeclSpec::SCS_mutable) { 5825 // mutable can only appear on non-static class members, so it's always 5826 // an error here 5827 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5828 Invalid = true; 5829 SC = SC_None; 5830 } 5831 5832 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5833 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5834 Context.getTypeDeclType(Record), TInfo, SC); 5835 ProcessDeclAttributes(S, Anon, Dc); 5836 5837 // Default-initialize the implicit variable. This initialization will be 5838 // trivial in almost all cases, except if a union member has an in-class 5839 // initializer: 5840 // union { int n = 0; }; 5841 ActOnUninitializedDecl(Anon); 5842 } 5843 Anon->setImplicit(); 5844 5845 // Mark this as an anonymous struct/union type. 5846 Record->setAnonymousStructOrUnion(true); 5847 5848 // Add the anonymous struct/union object to the current 5849 // context. We'll be referencing this object when we refer to one of 5850 // its members. 5851 Owner->addDecl(Anon); 5852 5853 // Inject the members of the anonymous struct/union into the owning 5854 // context and into the identifier resolver chain for name lookup 5855 // purposes. 5856 SmallVector<NamedDecl*, 2> Chain; 5857 Chain.push_back(Anon); 5858 5859 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, SC, 5860 Chain)) 5861 Invalid = true; 5862 5863 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5864 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5865 MangleNumberingContext *MCtx; 5866 Decl *ManglingContextDecl; 5867 std::tie(MCtx, ManglingContextDecl) = 5868 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5869 if (MCtx) { 5870 Context.setManglingNumber( 5871 NewVD, MCtx->getManglingNumber( 5872 NewVD, getMSManglingNumber(getLangOpts(), S))); 5873 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5874 } 5875 } 5876 } 5877 5878 if (Invalid) 5879 Anon->setInvalidDecl(); 5880 5881 return Anon; 5882 } 5883 5884 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5885 /// Microsoft C anonymous structure. 5886 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5887 /// Example: 5888 /// 5889 /// struct A { int a; }; 5890 /// struct B { struct A; int b; }; 5891 /// 5892 /// void foo() { 5893 /// B var; 5894 /// var.a = 3; 5895 /// } 5896 /// 5897 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5898 RecordDecl *Record) { 5899 assert(Record && "expected a record!"); 5900 5901 // Mock up a declarator. 5902 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 5903 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc); 5904 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5905 5906 auto *ParentDecl = cast<RecordDecl>(CurContext); 5907 QualType RecTy = Context.getTypeDeclType(Record); 5908 5909 // Create a declaration for this anonymous struct. 5910 NamedDecl *Anon = 5911 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5912 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5913 /*BitWidth=*/nullptr, /*Mutable=*/false, 5914 /*InitStyle=*/ICIS_NoInit); 5915 Anon->setImplicit(); 5916 5917 // Add the anonymous struct object to the current context. 5918 CurContext->addDecl(Anon); 5919 5920 // Inject the members of the anonymous struct into the current 5921 // context and into the identifier resolver chain for name lookup 5922 // purposes. 5923 SmallVector<NamedDecl*, 2> Chain; 5924 Chain.push_back(Anon); 5925 5926 RecordDecl *RecordDef = Record->getDefinition(); 5927 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5928 diag::err_field_incomplete_or_sizeless) || 5929 InjectAnonymousStructOrUnionMembers( 5930 *this, S, CurContext, RecordDef, AS_none, 5931 StorageClassSpecToVarDeclStorageClass(DS), Chain)) { 5932 Anon->setInvalidDecl(); 5933 ParentDecl->setInvalidDecl(); 5934 } 5935 5936 return Anon; 5937 } 5938 5939 /// GetNameForDeclarator - Determine the full declaration name for the 5940 /// given Declarator. 5941 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5942 return GetNameFromUnqualifiedId(D.getName()); 5943 } 5944 5945 /// Retrieves the declaration name from a parsed unqualified-id. 5946 DeclarationNameInfo 5947 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5948 DeclarationNameInfo NameInfo; 5949 NameInfo.setLoc(Name.StartLocation); 5950 5951 switch (Name.getKind()) { 5952 5953 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5954 case UnqualifiedIdKind::IK_Identifier: 5955 NameInfo.setName(Name.Identifier); 5956 return NameInfo; 5957 5958 case UnqualifiedIdKind::IK_DeductionGuideName: { 5959 // C++ [temp.deduct.guide]p3: 5960 // The simple-template-id shall name a class template specialization. 5961 // The template-name shall be the same identifier as the template-name 5962 // of the simple-template-id. 5963 // These together intend to imply that the template-name shall name a 5964 // class template. 5965 // FIXME: template<typename T> struct X {}; 5966 // template<typename T> using Y = X<T>; 5967 // Y(int) -> Y<int>; 5968 // satisfies these rules but does not name a class template. 5969 TemplateName TN = Name.TemplateName.get().get(); 5970 auto *Template = TN.getAsTemplateDecl(); 5971 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5972 Diag(Name.StartLocation, 5973 diag::err_deduction_guide_name_not_class_template) 5974 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5975 if (Template) 5976 NoteTemplateLocation(*Template); 5977 return DeclarationNameInfo(); 5978 } 5979 5980 NameInfo.setName( 5981 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5982 return NameInfo; 5983 } 5984 5985 case UnqualifiedIdKind::IK_OperatorFunctionId: 5986 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5987 Name.OperatorFunctionId.Operator)); 5988 NameInfo.setCXXOperatorNameRange(SourceRange( 5989 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5990 return NameInfo; 5991 5992 case UnqualifiedIdKind::IK_LiteralOperatorId: 5993 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5994 Name.Identifier)); 5995 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5996 return NameInfo; 5997 5998 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5999 TypeSourceInfo *TInfo; 6000 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 6001 if (Ty.isNull()) 6002 return DeclarationNameInfo(); 6003 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 6004 Context.getCanonicalType(Ty))); 6005 NameInfo.setNamedTypeInfo(TInfo); 6006 return NameInfo; 6007 } 6008 6009 case UnqualifiedIdKind::IK_ConstructorName: { 6010 TypeSourceInfo *TInfo; 6011 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 6012 if (Ty.isNull()) 6013 return DeclarationNameInfo(); 6014 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 6015 Context.getCanonicalType(Ty))); 6016 NameInfo.setNamedTypeInfo(TInfo); 6017 return NameInfo; 6018 } 6019 6020 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 6021 // In well-formed code, we can only have a constructor 6022 // template-id that refers to the current context, so go there 6023 // to find the actual type being constructed. 6024 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 6025 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 6026 return DeclarationNameInfo(); 6027 6028 // Determine the type of the class being constructed. 6029 QualType CurClassType = Context.getTypeDeclType(CurClass); 6030 6031 // FIXME: Check two things: that the template-id names the same type as 6032 // CurClassType, and that the template-id does not occur when the name 6033 // was qualified. 6034 6035 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 6036 Context.getCanonicalType(CurClassType))); 6037 // FIXME: should we retrieve TypeSourceInfo? 6038 NameInfo.setNamedTypeInfo(nullptr); 6039 return NameInfo; 6040 } 6041 6042 case UnqualifiedIdKind::IK_DestructorName: { 6043 TypeSourceInfo *TInfo; 6044 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 6045 if (Ty.isNull()) 6046 return DeclarationNameInfo(); 6047 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 6048 Context.getCanonicalType(Ty))); 6049 NameInfo.setNamedTypeInfo(TInfo); 6050 return NameInfo; 6051 } 6052 6053 case UnqualifiedIdKind::IK_TemplateId: { 6054 TemplateName TName = Name.TemplateId->Template.get(); 6055 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 6056 return Context.getNameForTemplate(TName, TNameLoc); 6057 } 6058 6059 } // switch (Name.getKind()) 6060 6061 llvm_unreachable("Unknown name kind"); 6062 } 6063 6064 static QualType getCoreType(QualType Ty) { 6065 do { 6066 if (Ty->isPointerType() || Ty->isReferenceType()) 6067 Ty = Ty->getPointeeType(); 6068 else if (Ty->isArrayType()) 6069 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 6070 else 6071 return Ty.withoutLocalFastQualifiers(); 6072 } while (true); 6073 } 6074 6075 /// hasSimilarParameters - Determine whether the C++ functions Declaration 6076 /// and Definition have "nearly" matching parameters. This heuristic is 6077 /// used to improve diagnostics in the case where an out-of-line function 6078 /// definition doesn't match any declaration within the class or namespace. 6079 /// Also sets Params to the list of indices to the parameters that differ 6080 /// between the declaration and the definition. If hasSimilarParameters 6081 /// returns true and Params is empty, then all of the parameters match. 6082 static bool hasSimilarParameters(ASTContext &Context, 6083 FunctionDecl *Declaration, 6084 FunctionDecl *Definition, 6085 SmallVectorImpl<unsigned> &Params) { 6086 Params.clear(); 6087 if (Declaration->param_size() != Definition->param_size()) 6088 return false; 6089 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 6090 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 6091 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 6092 6093 // The parameter types are identical 6094 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 6095 continue; 6096 6097 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 6098 QualType DefParamBaseTy = getCoreType(DefParamTy); 6099 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 6100 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 6101 6102 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 6103 (DeclTyName && DeclTyName == DefTyName)) 6104 Params.push_back(Idx); 6105 else // The two parameters aren't even close 6106 return false; 6107 } 6108 6109 return true; 6110 } 6111 6112 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given 6113 /// declarator needs to be rebuilt in the current instantiation. 6114 /// Any bits of declarator which appear before the name are valid for 6115 /// consideration here. That's specifically the type in the decl spec 6116 /// and the base type in any member-pointer chunks. 6117 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 6118 DeclarationName Name) { 6119 // The types we specifically need to rebuild are: 6120 // - typenames, typeofs, and decltypes 6121 // - types which will become injected class names 6122 // Of course, we also need to rebuild any type referencing such a 6123 // type. It's safest to just say "dependent", but we call out a 6124 // few cases here. 6125 6126 DeclSpec &DS = D.getMutableDeclSpec(); 6127 switch (DS.getTypeSpecType()) { 6128 case DeclSpec::TST_typename: 6129 case DeclSpec::TST_typeofType: 6130 case DeclSpec::TST_typeof_unqualType: 6131 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait: 6132 #include "clang/Basic/TransformTypeTraits.def" 6133 case DeclSpec::TST_atomic: { 6134 // Grab the type from the parser. 6135 TypeSourceInfo *TSI = nullptr; 6136 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 6137 if (T.isNull() || !T->isInstantiationDependentType()) break; 6138 6139 // Make sure there's a type source info. This isn't really much 6140 // of a waste; most dependent types should have type source info 6141 // attached already. 6142 if (!TSI) 6143 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 6144 6145 // Rebuild the type in the current instantiation. 6146 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 6147 if (!TSI) return true; 6148 6149 // Store the new type back in the decl spec. 6150 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 6151 DS.UpdateTypeRep(LocType); 6152 break; 6153 } 6154 6155 case DeclSpec::TST_decltype: 6156 case DeclSpec::TST_typeof_unqualExpr: 6157 case DeclSpec::TST_typeofExpr: { 6158 Expr *E = DS.getRepAsExpr(); 6159 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 6160 if (Result.isInvalid()) return true; 6161 DS.UpdateExprRep(Result.get()); 6162 break; 6163 } 6164 6165 default: 6166 // Nothing to do for these decl specs. 6167 break; 6168 } 6169 6170 // It doesn't matter what order we do this in. 6171 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 6172 DeclaratorChunk &Chunk = D.getTypeObject(I); 6173 6174 // The only type information in the declarator which can come 6175 // before the declaration name is the base type of a member 6176 // pointer. 6177 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 6178 continue; 6179 6180 // Rebuild the scope specifier in-place. 6181 CXXScopeSpec &SS = Chunk.Mem.Scope(); 6182 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 6183 return true; 6184 } 6185 6186 return false; 6187 } 6188 6189 /// Returns true if the declaration is declared in a system header or from a 6190 /// system macro. 6191 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 6192 return SM.isInSystemHeader(D->getLocation()) || 6193 SM.isInSystemMacro(D->getLocation()); 6194 } 6195 6196 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 6197 // Avoid warning twice on the same identifier, and don't warn on redeclaration 6198 // of system decl. 6199 if (D->getPreviousDecl() || D->isImplicit()) 6200 return; 6201 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 6202 if (Status != ReservedIdentifierStatus::NotReserved && 6203 !isFromSystemHeader(Context.getSourceManager(), D)) { 6204 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 6205 << D << static_cast<int>(Status); 6206 } 6207 } 6208 6209 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 6210 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6211 6212 // Check if we are in an `omp begin/end declare variant` scope. Handle this 6213 // declaration only if the `bind_to_declaration` extension is set. 6214 SmallVector<FunctionDecl *, 4> Bases; 6215 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 6216 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty:: 6217 implementation_extension_bind_to_declaration)) 6218 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6219 S, D, MultiTemplateParamsArg(), Bases); 6220 6221 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 6222 6223 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 6224 Dcl && Dcl->getDeclContext()->isFileContext()) 6225 Dcl->setTopLevelDeclInObjCContainer(); 6226 6227 if (!Bases.empty()) 6228 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 6229 6230 return Dcl; 6231 } 6232 6233 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 6234 /// If T is the name of a class, then each of the following shall have a 6235 /// name different from T: 6236 /// - every static data member of class T; 6237 /// - every member function of class T 6238 /// - every member of class T that is itself a type; 6239 /// \returns true if the declaration name violates these rules. 6240 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 6241 DeclarationNameInfo NameInfo) { 6242 DeclarationName Name = NameInfo.getName(); 6243 6244 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 6245 while (Record && Record->isAnonymousStructOrUnion()) 6246 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 6247 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 6248 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 6249 return true; 6250 } 6251 6252 return false; 6253 } 6254 6255 /// Diagnose a declaration whose declarator-id has the given 6256 /// nested-name-specifier. 6257 /// 6258 /// \param SS The nested-name-specifier of the declarator-id. 6259 /// 6260 /// \param DC The declaration context to which the nested-name-specifier 6261 /// resolves. 6262 /// 6263 /// \param Name The name of the entity being declared. 6264 /// 6265 /// \param Loc The location of the name of the entity being declared. 6266 /// 6267 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 6268 /// we're declaring an explicit / partial specialization / instantiation. 6269 /// 6270 /// \returns true if we cannot safely recover from this error, false otherwise. 6271 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 6272 DeclarationName Name, 6273 SourceLocation Loc, bool IsTemplateId) { 6274 DeclContext *Cur = CurContext; 6275 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 6276 Cur = Cur->getParent(); 6277 6278 // If the user provided a superfluous scope specifier that refers back to the 6279 // class in which the entity is already declared, diagnose and ignore it. 6280 // 6281 // class X { 6282 // void X::f(); 6283 // }; 6284 // 6285 // Note, it was once ill-formed to give redundant qualification in all 6286 // contexts, but that rule was removed by DR482. 6287 if (Cur->Equals(DC)) { 6288 if (Cur->isRecord()) { 6289 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 6290 : diag::err_member_extra_qualification) 6291 << Name << FixItHint::CreateRemoval(SS.getRange()); 6292 SS.clear(); 6293 } else { 6294 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 6295 } 6296 return false; 6297 } 6298 6299 // Check whether the qualifying scope encloses the scope of the original 6300 // declaration. For a template-id, we perform the checks in 6301 // CheckTemplateSpecializationScope. 6302 if (!Cur->Encloses(DC) && !IsTemplateId) { 6303 if (Cur->isRecord()) 6304 Diag(Loc, diag::err_member_qualification) 6305 << Name << SS.getRange(); 6306 else if (isa<TranslationUnitDecl>(DC)) 6307 Diag(Loc, diag::err_invalid_declarator_global_scope) 6308 << Name << SS.getRange(); 6309 else if (isa<FunctionDecl>(Cur)) 6310 Diag(Loc, diag::err_invalid_declarator_in_function) 6311 << Name << SS.getRange(); 6312 else if (isa<BlockDecl>(Cur)) 6313 Diag(Loc, diag::err_invalid_declarator_in_block) 6314 << Name << SS.getRange(); 6315 else if (isa<ExportDecl>(Cur)) { 6316 if (!isa<NamespaceDecl>(DC)) 6317 Diag(Loc, diag::err_export_non_namespace_scope_name) 6318 << Name << SS.getRange(); 6319 else 6320 // The cases that DC is not NamespaceDecl should be handled in 6321 // CheckRedeclarationExported. 6322 return false; 6323 } else 6324 Diag(Loc, diag::err_invalid_declarator_scope) 6325 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 6326 6327 return true; 6328 } 6329 6330 if (Cur->isRecord()) { 6331 // Cannot qualify members within a class. 6332 Diag(Loc, diag::err_member_qualification) 6333 << Name << SS.getRange(); 6334 SS.clear(); 6335 6336 // C++ constructors and destructors with incorrect scopes can break 6337 // our AST invariants by having the wrong underlying types. If 6338 // that's the case, then drop this declaration entirely. 6339 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6340 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6341 !Context.hasSameType(Name.getCXXNameType(), 6342 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6343 return true; 6344 6345 return false; 6346 } 6347 6348 // C++11 [dcl.meaning]p1: 6349 // [...] "The nested-name-specifier of the qualified declarator-id shall 6350 // not begin with a decltype-specifer" 6351 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6352 while (SpecLoc.getPrefix()) 6353 SpecLoc = SpecLoc.getPrefix(); 6354 if (isa_and_nonnull<DecltypeType>( 6355 SpecLoc.getNestedNameSpecifier()->getAsType())) 6356 Diag(Loc, diag::err_decltype_in_declarator) 6357 << SpecLoc.getTypeLoc().getSourceRange(); 6358 6359 return false; 6360 } 6361 6362 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6363 MultiTemplateParamsArg TemplateParamLists) { 6364 // TODO: consider using NameInfo for diagnostic. 6365 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6366 DeclarationName Name = NameInfo.getName(); 6367 6368 // All of these full declarators require an identifier. If it doesn't have 6369 // one, the ParsedFreeStandingDeclSpec action should be used. 6370 if (D.isDecompositionDeclarator()) { 6371 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6372 } else if (!Name) { 6373 if (!D.isInvalidType()) // Reject this if we think it is valid. 6374 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6375 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6376 return nullptr; 6377 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6378 return nullptr; 6379 6380 // The scope passed in may not be a decl scope. Zip up the scope tree until 6381 // we find one that is. 6382 while ((S->getFlags() & Scope::DeclScope) == 0 || 6383 (S->getFlags() & Scope::TemplateParamScope) != 0) 6384 S = S->getParent(); 6385 6386 DeclContext *DC = CurContext; 6387 if (D.getCXXScopeSpec().isInvalid()) 6388 D.setInvalidType(); 6389 else if (D.getCXXScopeSpec().isSet()) { 6390 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6391 UPPC_DeclarationQualifier)) 6392 return nullptr; 6393 6394 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6395 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6396 if (!DC || isa<EnumDecl>(DC)) { 6397 // If we could not compute the declaration context, it's because the 6398 // declaration context is dependent but does not refer to a class, 6399 // class template, or class template partial specialization. Complain 6400 // and return early, to avoid the coming semantic disaster. 6401 Diag(D.getIdentifierLoc(), 6402 diag::err_template_qualified_declarator_no_match) 6403 << D.getCXXScopeSpec().getScopeRep() 6404 << D.getCXXScopeSpec().getRange(); 6405 return nullptr; 6406 } 6407 bool IsDependentContext = DC->isDependentContext(); 6408 6409 if (!IsDependentContext && 6410 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6411 return nullptr; 6412 6413 // If a class is incomplete, do not parse entities inside it. 6414 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6415 Diag(D.getIdentifierLoc(), 6416 diag::err_member_def_undefined_record) 6417 << Name << DC << D.getCXXScopeSpec().getRange(); 6418 return nullptr; 6419 } 6420 if (!D.getDeclSpec().isFriendSpecified()) { 6421 if (diagnoseQualifiedDeclaration( 6422 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6423 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6424 if (DC->isRecord()) 6425 return nullptr; 6426 6427 D.setInvalidType(); 6428 } 6429 } 6430 6431 // Check whether we need to rebuild the type of the given 6432 // declaration in the current instantiation. 6433 if (EnteringContext && IsDependentContext && 6434 TemplateParamLists.size() != 0) { 6435 ContextRAII SavedContext(*this, DC); 6436 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6437 D.setInvalidType(); 6438 } 6439 } 6440 6441 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 6442 QualType R = TInfo->getType(); 6443 6444 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6445 UPPC_DeclarationType)) 6446 D.setInvalidType(); 6447 6448 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6449 forRedeclarationInCurContext()); 6450 6451 // See if this is a redefinition of a variable in the same scope. 6452 if (!D.getCXXScopeSpec().isSet()) { 6453 bool IsLinkageLookup = false; 6454 bool CreateBuiltins = false; 6455 6456 // If the declaration we're planning to build will be a function 6457 // or object with linkage, then look for another declaration with 6458 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6459 // 6460 // If the declaration we're planning to build will be declared with 6461 // external linkage in the translation unit, create any builtin with 6462 // the same name. 6463 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6464 /* Do nothing*/; 6465 else if (CurContext->isFunctionOrMethod() && 6466 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6467 R->isFunctionType())) { 6468 IsLinkageLookup = true; 6469 CreateBuiltins = 6470 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6471 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6472 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6473 CreateBuiltins = true; 6474 6475 if (IsLinkageLookup) { 6476 Previous.clear(LookupRedeclarationWithLinkage); 6477 Previous.setRedeclarationKind(ForExternalRedeclaration); 6478 } 6479 6480 LookupName(Previous, S, CreateBuiltins); 6481 } else { // Something like "int foo::x;" 6482 LookupQualifiedName(Previous, DC); 6483 6484 // C++ [dcl.meaning]p1: 6485 // When the declarator-id is qualified, the declaration shall refer to a 6486 // previously declared member of the class or namespace to which the 6487 // qualifier refers (or, in the case of a namespace, of an element of the 6488 // inline namespace set of that namespace (7.3.1)) or to a specialization 6489 // thereof; [...] 6490 // 6491 // Note that we already checked the context above, and that we do not have 6492 // enough information to make sure that Previous contains the declaration 6493 // we want to match. For example, given: 6494 // 6495 // class X { 6496 // void f(); 6497 // void f(float); 6498 // }; 6499 // 6500 // void X::f(int) { } // ill-formed 6501 // 6502 // In this case, Previous will point to the overload set 6503 // containing the two f's declared in X, but neither of them 6504 // matches. 6505 6506 RemoveUsingDecls(Previous); 6507 } 6508 6509 if (Previous.isSingleResult() && 6510 Previous.getFoundDecl()->isTemplateParameter()) { 6511 // Maybe we will complain about the shadowed template parameter. 6512 if (!D.isInvalidType()) 6513 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6514 Previous.getFoundDecl()); 6515 6516 // Just pretend that we didn't see the previous declaration. 6517 Previous.clear(); 6518 } 6519 6520 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6521 // Forget that the previous declaration is the injected-class-name. 6522 Previous.clear(); 6523 6524 // In C++, the previous declaration we find might be a tag type 6525 // (class or enum). In this case, the new declaration will hide the 6526 // tag type. Note that this applies to functions, function templates, and 6527 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6528 if (Previous.isSingleTagDecl() && 6529 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6530 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6531 Previous.clear(); 6532 6533 // Check that there are no default arguments other than in the parameters 6534 // of a function declaration (C++ only). 6535 if (getLangOpts().CPlusPlus) 6536 CheckExtraCXXDefaultArguments(D); 6537 6538 NamedDecl *New; 6539 6540 bool AddToScope = true; 6541 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6542 if (TemplateParamLists.size()) { 6543 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6544 return nullptr; 6545 } 6546 6547 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6548 } else if (R->isFunctionType()) { 6549 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6550 TemplateParamLists, 6551 AddToScope); 6552 } else { 6553 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6554 AddToScope); 6555 } 6556 6557 if (!New) 6558 return nullptr; 6559 6560 // If this has an identifier and is not a function template specialization, 6561 // add it to the scope stack. 6562 if (New->getDeclName() && AddToScope) 6563 PushOnScopeChains(New, S); 6564 6565 if (isInOpenMPDeclareTargetContext()) 6566 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6567 6568 return New; 6569 } 6570 6571 /// Helper method to turn variable array types into constant array 6572 /// types in certain situations which would otherwise be errors (for 6573 /// GCC compatibility). 6574 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6575 ASTContext &Context, 6576 bool &SizeIsNegative, 6577 llvm::APSInt &Oversized) { 6578 // This method tries to turn a variable array into a constant 6579 // array even when the size isn't an ICE. This is necessary 6580 // for compatibility with code that depends on gcc's buggy 6581 // constant expression folding, like struct {char x[(int)(char*)2];} 6582 SizeIsNegative = false; 6583 Oversized = 0; 6584 6585 if (T->isDependentType()) 6586 return QualType(); 6587 6588 QualifierCollector Qs; 6589 const Type *Ty = Qs.strip(T); 6590 6591 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6592 QualType Pointee = PTy->getPointeeType(); 6593 QualType FixedType = 6594 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6595 Oversized); 6596 if (FixedType.isNull()) return FixedType; 6597 FixedType = Context.getPointerType(FixedType); 6598 return Qs.apply(Context, FixedType); 6599 } 6600 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6601 QualType Inner = PTy->getInnerType(); 6602 QualType FixedType = 6603 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6604 Oversized); 6605 if (FixedType.isNull()) return FixedType; 6606 FixedType = Context.getParenType(FixedType); 6607 return Qs.apply(Context, FixedType); 6608 } 6609 6610 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6611 if (!VLATy) 6612 return QualType(); 6613 6614 QualType ElemTy = VLATy->getElementType(); 6615 if (ElemTy->isVariablyModifiedType()) { 6616 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6617 SizeIsNegative, Oversized); 6618 if (ElemTy.isNull()) 6619 return QualType(); 6620 } 6621 6622 Expr::EvalResult Result; 6623 if (!VLATy->getSizeExpr() || 6624 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6625 return QualType(); 6626 6627 llvm::APSInt Res = Result.Val.getInt(); 6628 6629 // Check whether the array size is negative. 6630 if (Res.isSigned() && Res.isNegative()) { 6631 SizeIsNegative = true; 6632 return QualType(); 6633 } 6634 6635 // Check whether the array is too large to be addressed. 6636 unsigned ActiveSizeBits = 6637 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6638 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6639 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6640 : Res.getActiveBits(); 6641 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6642 Oversized = Res; 6643 return QualType(); 6644 } 6645 6646 QualType FoldedArrayType = Context.getConstantArrayType( 6647 ElemTy, Res, VLATy->getSizeExpr(), ArraySizeModifier::Normal, 0); 6648 return Qs.apply(Context, FoldedArrayType); 6649 } 6650 6651 static void 6652 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6653 SrcTL = SrcTL.getUnqualifiedLoc(); 6654 DstTL = DstTL.getUnqualifiedLoc(); 6655 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6656 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6657 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6658 DstPTL.getPointeeLoc()); 6659 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6660 return; 6661 } 6662 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6663 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6664 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6665 DstPTL.getInnerLoc()); 6666 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6667 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6668 return; 6669 } 6670 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6671 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6672 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6673 TypeLoc DstElemTL = DstATL.getElementLoc(); 6674 if (VariableArrayTypeLoc SrcElemATL = 6675 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6676 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6677 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6678 } else { 6679 DstElemTL.initializeFullCopy(SrcElemTL); 6680 } 6681 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6682 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6683 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6684 } 6685 6686 /// Helper method to turn variable array types into constant array 6687 /// types in certain situations which would otherwise be errors (for 6688 /// GCC compatibility). 6689 static TypeSourceInfo* 6690 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6691 ASTContext &Context, 6692 bool &SizeIsNegative, 6693 llvm::APSInt &Oversized) { 6694 QualType FixedTy 6695 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6696 SizeIsNegative, Oversized); 6697 if (FixedTy.isNull()) 6698 return nullptr; 6699 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6700 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6701 FixedTInfo->getTypeLoc()); 6702 return FixedTInfo; 6703 } 6704 6705 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6706 /// true if we were successful. 6707 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6708 QualType &T, SourceLocation Loc, 6709 unsigned FailedFoldDiagID) { 6710 bool SizeIsNegative; 6711 llvm::APSInt Oversized; 6712 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6713 TInfo, Context, SizeIsNegative, Oversized); 6714 if (FixedTInfo) { 6715 Diag(Loc, diag::ext_vla_folded_to_constant); 6716 TInfo = FixedTInfo; 6717 T = FixedTInfo->getType(); 6718 return true; 6719 } 6720 6721 if (SizeIsNegative) 6722 Diag(Loc, diag::err_typecheck_negative_array_size); 6723 else if (Oversized.getBoolValue()) 6724 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6725 else if (FailedFoldDiagID) 6726 Diag(Loc, FailedFoldDiagID); 6727 return false; 6728 } 6729 6730 /// Register the given locally-scoped extern "C" declaration so 6731 /// that it can be found later for redeclarations. We include any extern "C" 6732 /// declaration that is not visible in the translation unit here, not just 6733 /// function-scope declarations. 6734 void 6735 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6736 if (!getLangOpts().CPlusPlus && 6737 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6738 // Don't need to track declarations in the TU in C. 6739 return; 6740 6741 // Note that we have a locally-scoped external with this name. 6742 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6743 } 6744 6745 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6746 // FIXME: We can have multiple results via __attribute__((overloadable)). 6747 auto Result = Context.getExternCContextDecl()->lookup(Name); 6748 return Result.empty() ? nullptr : *Result.begin(); 6749 } 6750 6751 /// Diagnose function specifiers on a declaration of an identifier that 6752 /// does not identify a function. 6753 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6754 // FIXME: We should probably indicate the identifier in question to avoid 6755 // confusion for constructs like "virtual int a(), b;" 6756 if (DS.isVirtualSpecified()) 6757 Diag(DS.getVirtualSpecLoc(), 6758 diag::err_virtual_non_function); 6759 6760 if (DS.hasExplicitSpecifier()) 6761 Diag(DS.getExplicitSpecLoc(), 6762 diag::err_explicit_non_function); 6763 6764 if (DS.isNoreturnSpecified()) 6765 Diag(DS.getNoreturnSpecLoc(), 6766 diag::err_noreturn_non_function); 6767 } 6768 6769 NamedDecl* 6770 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6771 TypeSourceInfo *TInfo, LookupResult &Previous) { 6772 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6773 if (D.getCXXScopeSpec().isSet()) { 6774 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6775 << D.getCXXScopeSpec().getRange(); 6776 D.setInvalidType(); 6777 // Pretend we didn't see the scope specifier. 6778 DC = CurContext; 6779 Previous.clear(); 6780 } 6781 6782 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6783 6784 if (D.getDeclSpec().isInlineSpecified()) 6785 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6786 << getLangOpts().CPlusPlus17; 6787 if (D.getDeclSpec().hasConstexprSpecifier()) 6788 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6789 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6790 6791 if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) { 6792 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName) 6793 Diag(D.getName().StartLocation, 6794 diag::err_deduction_guide_invalid_specifier) 6795 << "typedef"; 6796 else 6797 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6798 << D.getName().getSourceRange(); 6799 return nullptr; 6800 } 6801 6802 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6803 if (!NewTD) return nullptr; 6804 6805 // Handle attributes prior to checking for duplicates in MergeVarDecl 6806 ProcessDeclAttributes(S, NewTD, D); 6807 6808 CheckTypedefForVariablyModifiedType(S, NewTD); 6809 6810 bool Redeclaration = D.isRedeclaration(); 6811 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6812 D.setRedeclaration(Redeclaration); 6813 return ND; 6814 } 6815 6816 void 6817 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6818 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6819 // then it shall have block scope. 6820 // Note that variably modified types must be fixed before merging the decl so 6821 // that redeclarations will match. 6822 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6823 QualType T = TInfo->getType(); 6824 if (T->isVariablyModifiedType()) { 6825 setFunctionHasBranchProtectedScope(); 6826 6827 if (S->getFnParent() == nullptr) { 6828 bool SizeIsNegative; 6829 llvm::APSInt Oversized; 6830 TypeSourceInfo *FixedTInfo = 6831 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6832 SizeIsNegative, 6833 Oversized); 6834 if (FixedTInfo) { 6835 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6836 NewTD->setTypeSourceInfo(FixedTInfo); 6837 } else { 6838 if (SizeIsNegative) 6839 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6840 else if (T->isVariableArrayType()) 6841 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6842 else if (Oversized.getBoolValue()) 6843 Diag(NewTD->getLocation(), diag::err_array_too_large) 6844 << toString(Oversized, 10); 6845 else 6846 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6847 NewTD->setInvalidDecl(); 6848 } 6849 } 6850 } 6851 } 6852 6853 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6854 /// declares a typedef-name, either using the 'typedef' type specifier or via 6855 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6856 NamedDecl* 6857 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6858 LookupResult &Previous, bool &Redeclaration) { 6859 6860 // Find the shadowed declaration before filtering for scope. 6861 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6862 6863 // Merge the decl with the existing one if appropriate. If the decl is 6864 // in an outer scope, it isn't the same thing. 6865 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6866 /*AllowInlineNamespace*/false); 6867 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6868 if (!Previous.empty()) { 6869 Redeclaration = true; 6870 MergeTypedefNameDecl(S, NewTD, Previous); 6871 } else { 6872 inferGslPointerAttribute(NewTD); 6873 } 6874 6875 if (ShadowedDecl && !Redeclaration) 6876 CheckShadow(NewTD, ShadowedDecl, Previous); 6877 6878 // If this is the C FILE type, notify the AST context. 6879 if (IdentifierInfo *II = NewTD->getIdentifier()) 6880 if (!NewTD->isInvalidDecl() && 6881 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6882 switch (II->getInterestingIdentifierID()) { 6883 case tok::InterestingIdentifierKind::FILE: 6884 Context.setFILEDecl(NewTD); 6885 break; 6886 case tok::InterestingIdentifierKind::jmp_buf: 6887 Context.setjmp_bufDecl(NewTD); 6888 break; 6889 case tok::InterestingIdentifierKind::sigjmp_buf: 6890 Context.setsigjmp_bufDecl(NewTD); 6891 break; 6892 case tok::InterestingIdentifierKind::ucontext_t: 6893 Context.setucontext_tDecl(NewTD); 6894 break; 6895 case tok::InterestingIdentifierKind::float_t: 6896 case tok::InterestingIdentifierKind::double_t: 6897 NewTD->addAttr(AvailableOnlyInDefaultEvalMethodAttr::Create(Context)); 6898 break; 6899 default: 6900 break; 6901 } 6902 } 6903 6904 return NewTD; 6905 } 6906 6907 /// Determines whether the given declaration is an out-of-scope 6908 /// previous declaration. 6909 /// 6910 /// This routine should be invoked when name lookup has found a 6911 /// previous declaration (PrevDecl) that is not in the scope where a 6912 /// new declaration by the same name is being introduced. If the new 6913 /// declaration occurs in a local scope, previous declarations with 6914 /// linkage may still be considered previous declarations (C99 6915 /// 6.2.2p4-5, C++ [basic.link]p6). 6916 /// 6917 /// \param PrevDecl the previous declaration found by name 6918 /// lookup 6919 /// 6920 /// \param DC the context in which the new declaration is being 6921 /// declared. 6922 /// 6923 /// \returns true if PrevDecl is an out-of-scope previous declaration 6924 /// for a new delcaration with the same name. 6925 static bool 6926 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6927 ASTContext &Context) { 6928 if (!PrevDecl) 6929 return false; 6930 6931 if (!PrevDecl->hasLinkage()) 6932 return false; 6933 6934 if (Context.getLangOpts().CPlusPlus) { 6935 // C++ [basic.link]p6: 6936 // If there is a visible declaration of an entity with linkage 6937 // having the same name and type, ignoring entities declared 6938 // outside the innermost enclosing namespace scope, the block 6939 // scope declaration declares that same entity and receives the 6940 // linkage of the previous declaration. 6941 DeclContext *OuterContext = DC->getRedeclContext(); 6942 if (!OuterContext->isFunctionOrMethod()) 6943 // This rule only applies to block-scope declarations. 6944 return false; 6945 6946 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6947 if (PrevOuterContext->isRecord()) 6948 // We found a member function: ignore it. 6949 return false; 6950 6951 // Find the innermost enclosing namespace for the new and 6952 // previous declarations. 6953 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6954 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6955 6956 // The previous declaration is in a different namespace, so it 6957 // isn't the same function. 6958 if (!OuterContext->Equals(PrevOuterContext)) 6959 return false; 6960 } 6961 6962 return true; 6963 } 6964 6965 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6966 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6967 if (!SS.isSet()) return; 6968 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6969 } 6970 6971 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6972 QualType type = decl->getType(); 6973 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6974 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6975 // Various kinds of declaration aren't allowed to be __autoreleasing. 6976 unsigned kind = -1U; 6977 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6978 if (var->hasAttr<BlocksAttr>()) 6979 kind = 0; // __block 6980 else if (!var->hasLocalStorage()) 6981 kind = 1; // global 6982 } else if (isa<ObjCIvarDecl>(decl)) { 6983 kind = 3; // ivar 6984 } else if (isa<FieldDecl>(decl)) { 6985 kind = 2; // field 6986 } 6987 6988 if (kind != -1U) { 6989 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6990 << kind; 6991 } 6992 } else if (lifetime == Qualifiers::OCL_None) { 6993 // Try to infer lifetime. 6994 if (!type->isObjCLifetimeType()) 6995 return false; 6996 6997 lifetime = type->getObjCARCImplicitLifetime(); 6998 type = Context.getLifetimeQualifiedType(type, lifetime); 6999 decl->setType(type); 7000 } 7001 7002 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 7003 // Thread-local variables cannot have lifetime. 7004 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 7005 var->getTLSKind()) { 7006 Diag(var->getLocation(), diag::err_arc_thread_ownership) 7007 << var->getType(); 7008 return true; 7009 } 7010 } 7011 7012 return false; 7013 } 7014 7015 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 7016 if (Decl->getType().hasAddressSpace()) 7017 return; 7018 if (Decl->getType()->isDependentType()) 7019 return; 7020 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 7021 QualType Type = Var->getType(); 7022 if (Type->isSamplerT() || Type->isVoidType()) 7023 return; 7024 LangAS ImplAS = LangAS::opencl_private; 7025 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 7026 // __opencl_c_program_scope_global_variables feature, the address space 7027 // for a variable at program scope or a static or extern variable inside 7028 // a function are inferred to be __global. 7029 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 7030 Var->hasGlobalStorage()) 7031 ImplAS = LangAS::opencl_global; 7032 // If the original type from a decayed type is an array type and that array 7033 // type has no address space yet, deduce it now. 7034 if (auto DT = dyn_cast<DecayedType>(Type)) { 7035 auto OrigTy = DT->getOriginalType(); 7036 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 7037 // Add the address space to the original array type and then propagate 7038 // that to the element type through `getAsArrayType`. 7039 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 7040 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 7041 // Re-generate the decayed type. 7042 Type = Context.getDecayedType(OrigTy); 7043 } 7044 } 7045 Type = Context.getAddrSpaceQualType(Type, ImplAS); 7046 // Apply any qualifiers (including address space) from the array type to 7047 // the element type. This implements C99 6.7.3p8: "If the specification of 7048 // an array type includes any type qualifiers, the element type is so 7049 // qualified, not the array type." 7050 if (Type->isArrayType()) 7051 Type = QualType(Context.getAsArrayType(Type), 0); 7052 Decl->setType(Type); 7053 } 7054 } 7055 7056 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 7057 // Ensure that an auto decl is deduced otherwise the checks below might cache 7058 // the wrong linkage. 7059 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 7060 7061 // 'weak' only applies to declarations with external linkage. 7062 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 7063 if (!ND.isExternallyVisible()) { 7064 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 7065 ND.dropAttr<WeakAttr>(); 7066 } 7067 } 7068 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 7069 if (ND.isExternallyVisible()) { 7070 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 7071 ND.dropAttrs<WeakRefAttr, AliasAttr>(); 7072 } 7073 } 7074 7075 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 7076 if (VD->hasInit()) { 7077 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 7078 assert(VD->isThisDeclarationADefinition() && 7079 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 7080 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 7081 VD->dropAttr<AliasAttr>(); 7082 } 7083 } 7084 } 7085 7086 // 'selectany' only applies to externally visible variable declarations. 7087 // It does not apply to functions. 7088 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 7089 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 7090 S.Diag(Attr->getLocation(), 7091 diag::err_attribute_selectany_non_extern_data); 7092 ND.dropAttr<SelectAnyAttr>(); 7093 } 7094 } 7095 7096 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 7097 auto *VD = dyn_cast<VarDecl>(&ND); 7098 bool IsAnonymousNS = false; 7099 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 7100 if (VD) { 7101 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 7102 while (NS && !IsAnonymousNS) { 7103 IsAnonymousNS = NS->isAnonymousNamespace(); 7104 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 7105 } 7106 } 7107 // dll attributes require external linkage. Static locals may have external 7108 // linkage but still cannot be explicitly imported or exported. 7109 // In Microsoft mode, a variable defined in anonymous namespace must have 7110 // external linkage in order to be exported. 7111 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 7112 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 7113 (!AnonNSInMicrosoftMode && 7114 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 7115 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 7116 << &ND << Attr; 7117 ND.setInvalidDecl(); 7118 } 7119 } 7120 7121 // Check the attributes on the function type, if any. 7122 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 7123 // Don't declare this variable in the second operand of the for-statement; 7124 // GCC miscompiles that by ending its lifetime before evaluating the 7125 // third operand. See gcc.gnu.org/PR86769. 7126 AttributedTypeLoc ATL; 7127 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 7128 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 7129 TL = ATL.getModifiedLoc()) { 7130 // The [[lifetimebound]] attribute can be applied to the implicit object 7131 // parameter of a non-static member function (other than a ctor or dtor) 7132 // by applying it to the function type. 7133 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 7134 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 7135 if (!MD || MD->isStatic()) { 7136 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 7137 << !MD << A->getRange(); 7138 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 7139 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 7140 << isa<CXXDestructorDecl>(MD) << A->getRange(); 7141 } 7142 } 7143 } 7144 } 7145 } 7146 7147 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 7148 NamedDecl *NewDecl, 7149 bool IsSpecialization, 7150 bool IsDefinition) { 7151 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 7152 return; 7153 7154 bool IsTemplate = false; 7155 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 7156 OldDecl = OldTD->getTemplatedDecl(); 7157 IsTemplate = true; 7158 if (!IsSpecialization) 7159 IsDefinition = false; 7160 } 7161 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 7162 NewDecl = NewTD->getTemplatedDecl(); 7163 IsTemplate = true; 7164 } 7165 7166 if (!OldDecl || !NewDecl) 7167 return; 7168 7169 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 7170 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 7171 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 7172 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 7173 7174 // dllimport and dllexport are inheritable attributes so we have to exclude 7175 // inherited attribute instances. 7176 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 7177 (NewExportAttr && !NewExportAttr->isInherited()); 7178 7179 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 7180 // the only exception being explicit specializations. 7181 // Implicitly generated declarations are also excluded for now because there 7182 // is no other way to switch these to use dllimport or dllexport. 7183 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 7184 7185 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 7186 // Allow with a warning for free functions and global variables. 7187 bool JustWarn = false; 7188 if (!OldDecl->isCXXClassMember()) { 7189 auto *VD = dyn_cast<VarDecl>(OldDecl); 7190 if (VD && !VD->getDescribedVarTemplate()) 7191 JustWarn = true; 7192 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 7193 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 7194 JustWarn = true; 7195 } 7196 7197 // We cannot change a declaration that's been used because IR has already 7198 // been emitted. Dllimported functions will still work though (modulo 7199 // address equality) as they can use the thunk. 7200 if (OldDecl->isUsed()) 7201 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 7202 JustWarn = false; 7203 7204 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 7205 : diag::err_attribute_dll_redeclaration; 7206 S.Diag(NewDecl->getLocation(), DiagID) 7207 << NewDecl 7208 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 7209 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7210 if (!JustWarn) { 7211 NewDecl->setInvalidDecl(); 7212 return; 7213 } 7214 } 7215 7216 // A redeclaration is not allowed to drop a dllimport attribute, the only 7217 // exceptions being inline function definitions (except for function 7218 // templates), local extern declarations, qualified friend declarations or 7219 // special MSVC extension: in the last case, the declaration is treated as if 7220 // it were marked dllexport. 7221 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 7222 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 7223 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 7224 // Ignore static data because out-of-line definitions are diagnosed 7225 // separately. 7226 IsStaticDataMember = VD->isStaticDataMember(); 7227 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 7228 VarDecl::DeclarationOnly; 7229 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 7230 IsInline = FD->isInlined(); 7231 IsQualifiedFriend = FD->getQualifier() && 7232 FD->getFriendObjectKind() == Decl::FOK_Declared; 7233 } 7234 7235 if (OldImportAttr && !HasNewAttr && 7236 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 7237 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 7238 if (IsMicrosoftABI && IsDefinition) { 7239 if (IsSpecialization) { 7240 S.Diag( 7241 NewDecl->getLocation(), 7242 diag::err_attribute_dllimport_function_specialization_definition); 7243 S.Diag(OldImportAttr->getLocation(), diag::note_attribute); 7244 NewDecl->dropAttr<DLLImportAttr>(); 7245 } else { 7246 S.Diag(NewDecl->getLocation(), 7247 diag::warn_redeclaration_without_import_attribute) 7248 << NewDecl; 7249 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7250 NewDecl->dropAttr<DLLImportAttr>(); 7251 NewDecl->addAttr(DLLExportAttr::CreateImplicit( 7252 S.Context, NewImportAttr->getRange())); 7253 } 7254 } else if (IsMicrosoftABI && IsSpecialization) { 7255 assert(!IsDefinition); 7256 // MSVC allows this. Keep the inherited attribute. 7257 } else { 7258 S.Diag(NewDecl->getLocation(), 7259 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 7260 << NewDecl << OldImportAttr; 7261 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 7262 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 7263 OldDecl->dropAttr<DLLImportAttr>(); 7264 NewDecl->dropAttr<DLLImportAttr>(); 7265 } 7266 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 7267 // In MinGW, seeing a function declared inline drops the dllimport 7268 // attribute. 7269 OldDecl->dropAttr<DLLImportAttr>(); 7270 NewDecl->dropAttr<DLLImportAttr>(); 7271 S.Diag(NewDecl->getLocation(), 7272 diag::warn_dllimport_dropped_from_inline_function) 7273 << NewDecl << OldImportAttr; 7274 } 7275 7276 // A specialization of a class template member function is processed here 7277 // since it's a redeclaration. If the parent class is dllexport, the 7278 // specialization inherits that attribute. This doesn't happen automatically 7279 // since the parent class isn't instantiated until later. 7280 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 7281 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 7282 !NewImportAttr && !NewExportAttr) { 7283 if (const DLLExportAttr *ParentExportAttr = 7284 MD->getParent()->getAttr<DLLExportAttr>()) { 7285 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 7286 NewAttr->setInherited(true); 7287 NewDecl->addAttr(NewAttr); 7288 } 7289 } 7290 } 7291 } 7292 7293 /// Given that we are within the definition of the given function, 7294 /// will that definition behave like C99's 'inline', where the 7295 /// definition is discarded except for optimization purposes? 7296 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 7297 // Try to avoid calling GetGVALinkageForFunction. 7298 7299 // All cases of this require the 'inline' keyword. 7300 if (!FD->isInlined()) return false; 7301 7302 // This is only possible in C++ with the gnu_inline attribute. 7303 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 7304 return false; 7305 7306 // Okay, go ahead and call the relatively-more-expensive function. 7307 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 7308 } 7309 7310 /// Determine whether a variable is extern "C" prior to attaching 7311 /// an initializer. We can't just call isExternC() here, because that 7312 /// will also compute and cache whether the declaration is externally 7313 /// visible, which might change when we attach the initializer. 7314 /// 7315 /// This can only be used if the declaration is known to not be a 7316 /// redeclaration of an internal linkage declaration. 7317 /// 7318 /// For instance: 7319 /// 7320 /// auto x = []{}; 7321 /// 7322 /// Attaching the initializer here makes this declaration not externally 7323 /// visible, because its type has internal linkage. 7324 /// 7325 /// FIXME: This is a hack. 7326 template<typename T> 7327 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 7328 if (S.getLangOpts().CPlusPlus) { 7329 // In C++, the overloadable attribute negates the effects of extern "C". 7330 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 7331 return false; 7332 7333 // So do CUDA's host/device attributes. 7334 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 7335 D->template hasAttr<CUDAHostAttr>())) 7336 return false; 7337 } 7338 return D->isExternC(); 7339 } 7340 7341 static bool shouldConsiderLinkage(const VarDecl *VD) { 7342 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 7343 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 7344 isa<OMPDeclareMapperDecl>(DC)) 7345 return VD->hasExternalStorage(); 7346 if (DC->isFileContext()) 7347 return true; 7348 if (DC->isRecord()) 7349 return false; 7350 if (DC->getDeclKind() == Decl::HLSLBuffer) 7351 return false; 7352 7353 if (isa<RequiresExprBodyDecl>(DC)) 7354 return false; 7355 llvm_unreachable("Unexpected context"); 7356 } 7357 7358 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7359 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7360 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7361 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7362 return true; 7363 if (DC->isRecord()) 7364 return false; 7365 llvm_unreachable("Unexpected context"); 7366 } 7367 7368 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7369 ParsedAttr::Kind Kind) { 7370 // Check decl attributes on the DeclSpec. 7371 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7372 return true; 7373 7374 // Walk the declarator structure, checking decl attributes that were in a type 7375 // position to the decl itself. 7376 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7377 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7378 return true; 7379 } 7380 7381 // Finally, check attributes on the decl itself. 7382 return PD.getAttributes().hasAttribute(Kind) || 7383 PD.getDeclarationAttributes().hasAttribute(Kind); 7384 } 7385 7386 /// Adjust the \c DeclContext for a function or variable that might be a 7387 /// function-local external declaration. 7388 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7389 if (!DC->isFunctionOrMethod()) 7390 return false; 7391 7392 // If this is a local extern function or variable declared within a function 7393 // template, don't add it into the enclosing namespace scope until it is 7394 // instantiated; it might have a dependent type right now. 7395 if (DC->isDependentContext()) 7396 return true; 7397 7398 // C++11 [basic.link]p7: 7399 // When a block scope declaration of an entity with linkage is not found to 7400 // refer to some other declaration, then that entity is a member of the 7401 // innermost enclosing namespace. 7402 // 7403 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7404 // semantically-enclosing namespace, not a lexically-enclosing one. 7405 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7406 DC = DC->getParent(); 7407 return true; 7408 } 7409 7410 /// Returns true if given declaration has external C language linkage. 7411 static bool isDeclExternC(const Decl *D) { 7412 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7413 return FD->isExternC(); 7414 if (const auto *VD = dyn_cast<VarDecl>(D)) 7415 return VD->isExternC(); 7416 7417 llvm_unreachable("Unknown type of decl!"); 7418 } 7419 7420 /// Returns true if there hasn't been any invalid type diagnosed. 7421 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7422 DeclContext *DC = NewVD->getDeclContext(); 7423 QualType R = NewVD->getType(); 7424 7425 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7426 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7427 // argument. 7428 if (R->isImageType() || R->isPipeType()) { 7429 Se.Diag(NewVD->getLocation(), 7430 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7431 << R; 7432 NewVD->setInvalidDecl(); 7433 return false; 7434 } 7435 7436 // OpenCL v1.2 s6.9.r: 7437 // The event type cannot be used to declare a program scope variable. 7438 // OpenCL v2.0 s6.9.q: 7439 // The clk_event_t and reserve_id_t types cannot be declared in program 7440 // scope. 7441 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7442 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7443 Se.Diag(NewVD->getLocation(), 7444 diag::err_invalid_type_for_program_scope_var) 7445 << R; 7446 NewVD->setInvalidDecl(); 7447 return false; 7448 } 7449 } 7450 7451 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7452 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7453 Se.getLangOpts())) { 7454 QualType NR = R.getCanonicalType(); 7455 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7456 NR->isReferenceType()) { 7457 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7458 NR->isFunctionReferenceType()) { 7459 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7460 << NR->isReferenceType(); 7461 NewVD->setInvalidDecl(); 7462 return false; 7463 } 7464 NR = NR->getPointeeType(); 7465 } 7466 } 7467 7468 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7469 Se.getLangOpts())) { 7470 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7471 // half array type (unless the cl_khr_fp16 extension is enabled). 7472 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7473 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7474 NewVD->setInvalidDecl(); 7475 return false; 7476 } 7477 } 7478 7479 // OpenCL v1.2 s6.9.r: 7480 // The event type cannot be used with the __local, __constant and __global 7481 // address space qualifiers. 7482 if (R->isEventT()) { 7483 if (R.getAddressSpace() != LangAS::opencl_private) { 7484 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7485 NewVD->setInvalidDecl(); 7486 return false; 7487 } 7488 } 7489 7490 if (R->isSamplerT()) { 7491 // OpenCL v1.2 s6.9.b p4: 7492 // The sampler type cannot be used with the __local and __global address 7493 // space qualifiers. 7494 if (R.getAddressSpace() == LangAS::opencl_local || 7495 R.getAddressSpace() == LangAS::opencl_global) { 7496 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7497 NewVD->setInvalidDecl(); 7498 } 7499 7500 // OpenCL v1.2 s6.12.14.1: 7501 // A global sampler must be declared with either the constant address 7502 // space qualifier or with the const qualifier. 7503 if (DC->isTranslationUnit() && 7504 !(R.getAddressSpace() == LangAS::opencl_constant || 7505 R.isConstQualified())) { 7506 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7507 NewVD->setInvalidDecl(); 7508 } 7509 if (NewVD->isInvalidDecl()) 7510 return false; 7511 } 7512 7513 return true; 7514 } 7515 7516 template <typename AttrTy> 7517 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7518 const TypedefNameDecl *TND = TT->getDecl(); 7519 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7520 AttrTy *Clone = Attribute->clone(S.Context); 7521 Clone->setInherited(true); 7522 D->addAttr(Clone); 7523 } 7524 } 7525 7526 // This function emits warning and a corresponding note based on the 7527 // ReadOnlyPlacementAttr attribute. The warning checks that all global variable 7528 // declarations of an annotated type must be const qualified. 7529 void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) { 7530 QualType VarType = VD->getType().getCanonicalType(); 7531 7532 // Ignore local declarations (for now) and those with const qualification. 7533 // TODO: Local variables should not be allowed if their type declaration has 7534 // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch. 7535 if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified()) 7536 return; 7537 7538 if (VarType->isArrayType()) { 7539 // Retrieve element type for array declarations. 7540 VarType = S.getASTContext().getBaseElementType(VarType); 7541 } 7542 7543 const RecordDecl *RD = VarType->getAsRecordDecl(); 7544 7545 // Check if the record declaration is present and if it has any attributes. 7546 if (RD == nullptr) 7547 return; 7548 7549 if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) { 7550 S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD; 7551 S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement); 7552 return; 7553 } 7554 } 7555 7556 NamedDecl *Sema::ActOnVariableDeclarator( 7557 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7558 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7559 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7560 QualType R = TInfo->getType(); 7561 DeclarationName Name = GetNameForDeclarator(D).getName(); 7562 7563 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7564 bool IsPlaceholderVariable = false; 7565 7566 if (D.isDecompositionDeclarator()) { 7567 // Take the name of the first declarator as our name for diagnostic 7568 // purposes. 7569 auto &Decomp = D.getDecompositionDeclarator(); 7570 if (!Decomp.bindings().empty()) { 7571 II = Decomp.bindings()[0].Name; 7572 Name = II; 7573 } 7574 } else if (!II) { 7575 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7576 return nullptr; 7577 } 7578 7579 7580 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7581 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7582 7583 if (LangOpts.CPlusPlus && (DC->isClosure() || DC->isFunctionOrMethod()) && 7584 SC != SC_Static && SC != SC_Extern && II && II->isPlaceholder()) { 7585 IsPlaceholderVariable = true; 7586 if (!Previous.empty()) { 7587 NamedDecl *PrevDecl = *Previous.begin(); 7588 bool SameDC = PrevDecl->getDeclContext()->getRedeclContext()->Equals( 7589 DC->getRedeclContext()); 7590 if (SameDC && isDeclInScope(PrevDecl, CurContext, S, false)) 7591 DiagPlaceholderVariableDefinition(D.getIdentifierLoc()); 7592 } 7593 } 7594 7595 // dllimport globals without explicit storage class are treated as extern. We 7596 // have to change the storage class this early to get the right DeclContext. 7597 if (SC == SC_None && !DC->isRecord() && 7598 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7599 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7600 SC = SC_Extern; 7601 7602 DeclContext *OriginalDC = DC; 7603 bool IsLocalExternDecl = SC == SC_Extern && 7604 adjustContextForLocalExternDecl(DC); 7605 7606 if (SCSpec == DeclSpec::SCS_mutable) { 7607 // mutable can only appear on non-static class members, so it's always 7608 // an error here 7609 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7610 D.setInvalidType(); 7611 SC = SC_None; 7612 } 7613 7614 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7615 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7616 D.getDeclSpec().getStorageClassSpecLoc())) { 7617 // In C++11, the 'register' storage class specifier is deprecated. 7618 // Suppress the warning in system macros, it's used in macros in some 7619 // popular C system headers, such as in glibc's htonl() macro. 7620 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7621 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7622 : diag::warn_deprecated_register) 7623 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7624 } 7625 7626 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7627 7628 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7629 // C99 6.9p2: The storage-class specifiers auto and register shall not 7630 // appear in the declaration specifiers in an external declaration. 7631 // Global Register+Asm is a GNU extension we support. 7632 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7633 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7634 D.setInvalidType(); 7635 } 7636 } 7637 7638 // If this variable has a VLA type and an initializer, try to 7639 // fold to a constant-sized type. This is otherwise invalid. 7640 if (D.hasInitializer() && R->isVariableArrayType()) 7641 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7642 /*DiagID=*/0); 7643 7644 bool IsMemberSpecialization = false; 7645 bool IsVariableTemplateSpecialization = false; 7646 bool IsPartialSpecialization = false; 7647 bool IsVariableTemplate = false; 7648 VarDecl *NewVD = nullptr; 7649 VarTemplateDecl *NewTemplate = nullptr; 7650 TemplateParameterList *TemplateParams = nullptr; 7651 if (!getLangOpts().CPlusPlus) { 7652 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7653 II, R, TInfo, SC); 7654 7655 if (R->getContainedDeducedType()) 7656 ParsingInitForAutoVars.insert(NewVD); 7657 7658 if (D.isInvalidType()) 7659 NewVD->setInvalidDecl(); 7660 7661 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7662 NewVD->hasLocalStorage()) 7663 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7664 NTCUC_AutoVar, NTCUK_Destruct); 7665 } else { 7666 bool Invalid = false; 7667 7668 if (DC->isRecord() && !CurContext->isRecord()) { 7669 // This is an out-of-line definition of a static data member. 7670 switch (SC) { 7671 case SC_None: 7672 break; 7673 case SC_Static: 7674 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7675 diag::err_static_out_of_line) 7676 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7677 break; 7678 case SC_Auto: 7679 case SC_Register: 7680 case SC_Extern: 7681 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7682 // to names of variables declared in a block or to function parameters. 7683 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7684 // of class members 7685 7686 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7687 diag::err_storage_class_for_static_member) 7688 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7689 break; 7690 case SC_PrivateExtern: 7691 llvm_unreachable("C storage class in c++!"); 7692 } 7693 } 7694 7695 if (SC == SC_Static && CurContext->isRecord()) { 7696 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7697 // Walk up the enclosing DeclContexts to check for any that are 7698 // incompatible with static data members. 7699 const DeclContext *FunctionOrMethod = nullptr; 7700 const CXXRecordDecl *AnonStruct = nullptr; 7701 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7702 if (Ctxt->isFunctionOrMethod()) { 7703 FunctionOrMethod = Ctxt; 7704 break; 7705 } 7706 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7707 if (ParentDecl && !ParentDecl->getDeclName()) { 7708 AnonStruct = ParentDecl; 7709 break; 7710 } 7711 } 7712 if (FunctionOrMethod) { 7713 // C++ [class.static.data]p5: A local class shall not have static data 7714 // members. 7715 Diag(D.getIdentifierLoc(), 7716 diag::err_static_data_member_not_allowed_in_local_class) 7717 << Name << RD->getDeclName() 7718 << llvm::to_underlying(RD->getTagKind()); 7719 } else if (AnonStruct) { 7720 // C++ [class.static.data]p4: Unnamed classes and classes contained 7721 // directly or indirectly within unnamed classes shall not contain 7722 // static data members. 7723 Diag(D.getIdentifierLoc(), 7724 diag::err_static_data_member_not_allowed_in_anon_struct) 7725 << Name << llvm::to_underlying(AnonStruct->getTagKind()); 7726 Invalid = true; 7727 } else if (RD->isUnion()) { 7728 // C++98 [class.union]p1: If a union contains a static data member, 7729 // the program is ill-formed. C++11 drops this restriction. 7730 Diag(D.getIdentifierLoc(), 7731 getLangOpts().CPlusPlus11 7732 ? diag::warn_cxx98_compat_static_data_member_in_union 7733 : diag::ext_static_data_member_in_union) << Name; 7734 } 7735 } 7736 } 7737 7738 // Match up the template parameter lists with the scope specifier, then 7739 // determine whether we have a template or a template specialization. 7740 bool InvalidScope = false; 7741 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7742 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7743 D.getCXXScopeSpec(), 7744 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7745 ? D.getName().TemplateId 7746 : nullptr, 7747 TemplateParamLists, 7748 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7749 Invalid |= InvalidScope; 7750 7751 if (TemplateParams) { 7752 if (!TemplateParams->size() && 7753 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7754 // There is an extraneous 'template<>' for this variable. Complain 7755 // about it, but allow the declaration of the variable. 7756 Diag(TemplateParams->getTemplateLoc(), 7757 diag::err_template_variable_noparams) 7758 << II 7759 << SourceRange(TemplateParams->getTemplateLoc(), 7760 TemplateParams->getRAngleLoc()); 7761 TemplateParams = nullptr; 7762 } else { 7763 // Check that we can declare a template here. 7764 if (CheckTemplateDeclScope(S, TemplateParams)) 7765 return nullptr; 7766 7767 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7768 // This is an explicit specialization or a partial specialization. 7769 IsVariableTemplateSpecialization = true; 7770 IsPartialSpecialization = TemplateParams->size() > 0; 7771 } else { // if (TemplateParams->size() > 0) 7772 // This is a template declaration. 7773 IsVariableTemplate = true; 7774 7775 // Only C++1y supports variable templates (N3651). 7776 Diag(D.getIdentifierLoc(), 7777 getLangOpts().CPlusPlus14 7778 ? diag::warn_cxx11_compat_variable_template 7779 : diag::ext_variable_template); 7780 } 7781 } 7782 } else { 7783 // Check that we can declare a member specialization here. 7784 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7785 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7786 return nullptr; 7787 assert((Invalid || 7788 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7789 "should have a 'template<>' for this decl"); 7790 } 7791 7792 if (IsVariableTemplateSpecialization) { 7793 SourceLocation TemplateKWLoc = 7794 TemplateParamLists.size() > 0 7795 ? TemplateParamLists[0]->getTemplateLoc() 7796 : SourceLocation(); 7797 DeclResult Res = ActOnVarTemplateSpecialization( 7798 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7799 IsPartialSpecialization); 7800 if (Res.isInvalid()) 7801 return nullptr; 7802 NewVD = cast<VarDecl>(Res.get()); 7803 AddToScope = false; 7804 } else if (D.isDecompositionDeclarator()) { 7805 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7806 D.getIdentifierLoc(), R, TInfo, SC, 7807 Bindings); 7808 } else 7809 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7810 D.getIdentifierLoc(), II, R, TInfo, SC); 7811 7812 // If this is supposed to be a variable template, create it as such. 7813 if (IsVariableTemplate) { 7814 NewTemplate = 7815 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7816 TemplateParams, NewVD); 7817 NewVD->setDescribedVarTemplate(NewTemplate); 7818 } 7819 7820 // If this decl has an auto type in need of deduction, make a note of the 7821 // Decl so we can diagnose uses of it in its own initializer. 7822 if (R->getContainedDeducedType()) 7823 ParsingInitForAutoVars.insert(NewVD); 7824 7825 if (D.isInvalidType() || Invalid) { 7826 NewVD->setInvalidDecl(); 7827 if (NewTemplate) 7828 NewTemplate->setInvalidDecl(); 7829 } 7830 7831 SetNestedNameSpecifier(*this, NewVD, D); 7832 7833 // If we have any template parameter lists that don't directly belong to 7834 // the variable (matching the scope specifier), store them. 7835 // An explicit variable template specialization does not own any template 7836 // parameter lists. 7837 bool IsExplicitSpecialization = 7838 IsVariableTemplateSpecialization && !IsPartialSpecialization; 7839 unsigned VDTemplateParamLists = 7840 (TemplateParams && !IsExplicitSpecialization) ? 1 : 0; 7841 if (TemplateParamLists.size() > VDTemplateParamLists) 7842 NewVD->setTemplateParameterListsInfo( 7843 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7844 } 7845 7846 if (D.getDeclSpec().isInlineSpecified()) { 7847 if (!getLangOpts().CPlusPlus) { 7848 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7849 << 0; 7850 } else if (CurContext->isFunctionOrMethod()) { 7851 // 'inline' is not allowed on block scope variable declaration. 7852 Diag(D.getDeclSpec().getInlineSpecLoc(), 7853 diag::err_inline_declaration_block_scope) << Name 7854 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7855 } else { 7856 Diag(D.getDeclSpec().getInlineSpecLoc(), 7857 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7858 : diag::ext_inline_variable); 7859 NewVD->setInlineSpecified(); 7860 } 7861 } 7862 7863 // Set the lexical context. If the declarator has a C++ scope specifier, the 7864 // lexical context will be different from the semantic context. 7865 NewVD->setLexicalDeclContext(CurContext); 7866 if (NewTemplate) 7867 NewTemplate->setLexicalDeclContext(CurContext); 7868 7869 if (IsLocalExternDecl) { 7870 if (D.isDecompositionDeclarator()) 7871 for (auto *B : Bindings) 7872 B->setLocalExternDecl(); 7873 else 7874 NewVD->setLocalExternDecl(); 7875 } 7876 7877 bool EmitTLSUnsupportedError = false; 7878 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7879 // C++11 [dcl.stc]p4: 7880 // When thread_local is applied to a variable of block scope the 7881 // storage-class-specifier static is implied if it does not appear 7882 // explicitly. 7883 // Core issue: 'static' is not implied if the variable is declared 7884 // 'extern'. 7885 if (NewVD->hasLocalStorage() && 7886 (SCSpec != DeclSpec::SCS_unspecified || 7887 TSCS != DeclSpec::TSCS_thread_local || 7888 !DC->isFunctionOrMethod())) 7889 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7890 diag::err_thread_non_global) 7891 << DeclSpec::getSpecifierName(TSCS); 7892 else if (!Context.getTargetInfo().isTLSSupported()) { 7893 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 7894 getLangOpts().SYCLIsDevice) { 7895 // Postpone error emission until we've collected attributes required to 7896 // figure out whether it's a host or device variable and whether the 7897 // error should be ignored. 7898 EmitTLSUnsupportedError = true; 7899 // We still need to mark the variable as TLS so it shows up in AST with 7900 // proper storage class for other tools to use even if we're not going 7901 // to emit any code for it. 7902 NewVD->setTSCSpec(TSCS); 7903 } else 7904 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7905 diag::err_thread_unsupported); 7906 } else 7907 NewVD->setTSCSpec(TSCS); 7908 } 7909 7910 switch (D.getDeclSpec().getConstexprSpecifier()) { 7911 case ConstexprSpecKind::Unspecified: 7912 break; 7913 7914 case ConstexprSpecKind::Consteval: 7915 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7916 diag::err_constexpr_wrong_decl_kind) 7917 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7918 [[fallthrough]]; 7919 7920 case ConstexprSpecKind::Constexpr: 7921 NewVD->setConstexpr(true); 7922 // C++1z [dcl.spec.constexpr]p1: 7923 // A static data member declared with the constexpr specifier is 7924 // implicitly an inline variable. 7925 if (NewVD->isStaticDataMember() && 7926 (getLangOpts().CPlusPlus17 || 7927 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7928 NewVD->setImplicitlyInline(); 7929 break; 7930 7931 case ConstexprSpecKind::Constinit: 7932 if (!NewVD->hasGlobalStorage()) 7933 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7934 diag::err_constinit_local_variable); 7935 else 7936 NewVD->addAttr( 7937 ConstInitAttr::Create(Context, D.getDeclSpec().getConstexprSpecLoc(), 7938 ConstInitAttr::Keyword_constinit)); 7939 break; 7940 } 7941 7942 // C99 6.7.4p3 7943 // An inline definition of a function with external linkage shall 7944 // not contain a definition of a modifiable object with static or 7945 // thread storage duration... 7946 // We only apply this when the function is required to be defined 7947 // elsewhere, i.e. when the function is not 'extern inline'. Note 7948 // that a local variable with thread storage duration still has to 7949 // be marked 'static'. Also note that it's possible to get these 7950 // semantics in C++ using __attribute__((gnu_inline)). 7951 if (SC == SC_Static && S->getFnParent() != nullptr && 7952 !NewVD->getType().isConstQualified()) { 7953 FunctionDecl *CurFD = getCurFunctionDecl(); 7954 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7955 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7956 diag::warn_static_local_in_extern_inline); 7957 MaybeSuggestAddingStaticToDecl(CurFD); 7958 } 7959 } 7960 7961 if (D.getDeclSpec().isModulePrivateSpecified()) { 7962 if (IsVariableTemplateSpecialization) 7963 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7964 << (IsPartialSpecialization ? 1 : 0) 7965 << FixItHint::CreateRemoval( 7966 D.getDeclSpec().getModulePrivateSpecLoc()); 7967 else if (IsMemberSpecialization) 7968 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7969 << 2 7970 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7971 else if (NewVD->hasLocalStorage()) 7972 Diag(NewVD->getLocation(), diag::err_module_private_local) 7973 << 0 << NewVD 7974 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7975 << FixItHint::CreateRemoval( 7976 D.getDeclSpec().getModulePrivateSpecLoc()); 7977 else { 7978 NewVD->setModulePrivate(); 7979 if (NewTemplate) 7980 NewTemplate->setModulePrivate(); 7981 for (auto *B : Bindings) 7982 B->setModulePrivate(); 7983 } 7984 } 7985 7986 if (getLangOpts().OpenCL) { 7987 deduceOpenCLAddressSpace(NewVD); 7988 7989 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7990 if (TSC != TSCS_unspecified) { 7991 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7992 diag::err_opencl_unknown_type_specifier) 7993 << getLangOpts().getOpenCLVersionString() 7994 << DeclSpec::getSpecifierName(TSC) << 1; 7995 NewVD->setInvalidDecl(); 7996 } 7997 } 7998 7999 // WebAssembly tables are always in address space 1 (wasm_var). Don't apply 8000 // address space if the table has local storage (semantic checks elsewhere 8001 // will produce an error anyway). 8002 if (const auto *ATy = dyn_cast<ArrayType>(NewVD->getType())) { 8003 if (ATy && ATy->getElementType().isWebAssemblyReferenceType() && 8004 !NewVD->hasLocalStorage()) { 8005 QualType Type = Context.getAddrSpaceQualType( 8006 NewVD->getType(), Context.getLangASForBuiltinAddressSpace(1)); 8007 NewVD->setType(Type); 8008 } 8009 } 8010 8011 // Handle attributes prior to checking for duplicates in MergeVarDecl 8012 ProcessDeclAttributes(S, NewVD, D); 8013 8014 // FIXME: This is probably the wrong location to be doing this and we should 8015 // probably be doing this for more attributes (especially for function 8016 // pointer attributes such as format, warn_unused_result, etc.). Ideally 8017 // the code to copy attributes would be generated by TableGen. 8018 if (R->isFunctionPointerType()) 8019 if (const auto *TT = R->getAs<TypedefType>()) 8020 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 8021 8022 if (getLangOpts().CUDA || getLangOpts().OpenMPIsTargetDevice || 8023 getLangOpts().SYCLIsDevice) { 8024 if (EmitTLSUnsupportedError && 8025 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 8026 (getLangOpts().OpenMPIsTargetDevice && 8027 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 8028 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8029 diag::err_thread_unsupported); 8030 8031 if (EmitTLSUnsupportedError && 8032 (LangOpts.SYCLIsDevice || 8033 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice))) 8034 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 8035 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 8036 // storage [duration]." 8037 if (SC == SC_None && S->getFnParent() != nullptr && 8038 (NewVD->hasAttr<CUDASharedAttr>() || 8039 NewVD->hasAttr<CUDAConstantAttr>())) { 8040 NewVD->setStorageClass(SC_Static); 8041 } 8042 } 8043 8044 // Ensure that dllimport globals without explicit storage class are treated as 8045 // extern. The storage class is set above using parsed attributes. Now we can 8046 // check the VarDecl itself. 8047 assert(!NewVD->hasAttr<DLLImportAttr>() || 8048 NewVD->getAttr<DLLImportAttr>()->isInherited() || 8049 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 8050 8051 // In auto-retain/release, infer strong retension for variables of 8052 // retainable type. 8053 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 8054 NewVD->setInvalidDecl(); 8055 8056 // Handle GNU asm-label extension (encoded as an attribute). 8057 if (Expr *E = (Expr*)D.getAsmLabel()) { 8058 // The parser guarantees this is a string. 8059 StringLiteral *SE = cast<StringLiteral>(E); 8060 StringRef Label = SE->getString(); 8061 if (S->getFnParent() != nullptr) { 8062 switch (SC) { 8063 case SC_None: 8064 case SC_Auto: 8065 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 8066 break; 8067 case SC_Register: 8068 // Local Named register 8069 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 8070 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 8071 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8072 break; 8073 case SC_Static: 8074 case SC_Extern: 8075 case SC_PrivateExtern: 8076 break; 8077 } 8078 } else if (SC == SC_Register) { 8079 // Global Named register 8080 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 8081 const auto &TI = Context.getTargetInfo(); 8082 bool HasSizeMismatch; 8083 8084 if (!TI.isValidGCCRegisterName(Label)) 8085 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 8086 else if (!TI.validateGlobalRegisterVariable(Label, 8087 Context.getTypeSize(R), 8088 HasSizeMismatch)) 8089 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 8090 else if (HasSizeMismatch) 8091 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 8092 } 8093 8094 if (!R->isIntegralType(Context) && !R->isPointerType()) { 8095 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 8096 NewVD->setInvalidDecl(true); 8097 } 8098 } 8099 8100 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 8101 /*IsLiteralLabel=*/true, 8102 SE->getStrTokenLoc(0))); 8103 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8104 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8105 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 8106 if (I != ExtnameUndeclaredIdentifiers.end()) { 8107 if (isDeclExternC(NewVD)) { 8108 NewVD->addAttr(I->second); 8109 ExtnameUndeclaredIdentifiers.erase(I); 8110 } else 8111 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 8112 << /*Variable*/1 << NewVD; 8113 } 8114 } 8115 8116 // Find the shadowed declaration before filtering for scope. 8117 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 8118 ? getShadowedDeclaration(NewVD, Previous) 8119 : nullptr; 8120 8121 // Don't consider existing declarations that are in a different 8122 // scope and are out-of-semantic-context declarations (if the new 8123 // declaration has linkage). 8124 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 8125 D.getCXXScopeSpec().isNotEmpty() || 8126 IsMemberSpecialization || 8127 IsVariableTemplateSpecialization); 8128 8129 // Check whether the previous declaration is in the same block scope. This 8130 // affects whether we merge types with it, per C++11 [dcl.array]p3. 8131 if (getLangOpts().CPlusPlus && 8132 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 8133 NewVD->setPreviousDeclInSameBlockScope( 8134 Previous.isSingleResult() && !Previous.isShadowed() && 8135 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 8136 8137 if (!getLangOpts().CPlusPlus) { 8138 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8139 } else { 8140 // If this is an explicit specialization of a static data member, check it. 8141 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 8142 CheckMemberSpecialization(NewVD, Previous)) 8143 NewVD->setInvalidDecl(); 8144 8145 // Merge the decl with the existing one if appropriate. 8146 if (!Previous.empty()) { 8147 if (Previous.isSingleResult() && 8148 isa<FieldDecl>(Previous.getFoundDecl()) && 8149 D.getCXXScopeSpec().isSet()) { 8150 // The user tried to define a non-static data member 8151 // out-of-line (C++ [dcl.meaning]p1). 8152 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 8153 << D.getCXXScopeSpec().getRange(); 8154 Previous.clear(); 8155 NewVD->setInvalidDecl(); 8156 } 8157 } else if (D.getCXXScopeSpec().isSet()) { 8158 // No previous declaration in the qualifying scope. 8159 Diag(D.getIdentifierLoc(), diag::err_no_member) 8160 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 8161 << D.getCXXScopeSpec().getRange(); 8162 NewVD->setInvalidDecl(); 8163 } 8164 8165 if (!IsVariableTemplateSpecialization && !IsPlaceholderVariable) 8166 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 8167 8168 // CheckVariableDeclaration will set NewVD as invalid if something is in 8169 // error like WebAssembly tables being declared as arrays with a non-zero 8170 // size, but then parsing continues and emits further errors on that line. 8171 // To avoid that we check here if it happened and return nullptr. 8172 if (NewVD->getType()->isWebAssemblyTableType() && NewVD->isInvalidDecl()) 8173 return nullptr; 8174 8175 if (NewTemplate) { 8176 VarTemplateDecl *PrevVarTemplate = 8177 NewVD->getPreviousDecl() 8178 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 8179 : nullptr; 8180 8181 // Check the template parameter list of this declaration, possibly 8182 // merging in the template parameter list from the previous variable 8183 // template declaration. 8184 if (CheckTemplateParameterList( 8185 TemplateParams, 8186 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 8187 : nullptr, 8188 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 8189 DC->isDependentContext()) 8190 ? TPC_ClassTemplateMember 8191 : TPC_VarTemplate)) 8192 NewVD->setInvalidDecl(); 8193 8194 // If we are providing an explicit specialization of a static variable 8195 // template, make a note of that. 8196 if (PrevVarTemplate && 8197 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 8198 PrevVarTemplate->setMemberSpecialization(); 8199 } 8200 } 8201 8202 // Diagnose shadowed variables iff this isn't a redeclaration. 8203 if (!IsPlaceholderVariable && ShadowedDecl && !D.isRedeclaration()) 8204 CheckShadow(NewVD, ShadowedDecl, Previous); 8205 8206 ProcessPragmaWeak(S, NewVD); 8207 8208 // If this is the first declaration of an extern C variable, update 8209 // the map of such variables. 8210 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 8211 isIncompleteDeclExternC(*this, NewVD)) 8212 RegisterLocallyScopedExternCDecl(NewVD, S); 8213 8214 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 8215 MangleNumberingContext *MCtx; 8216 Decl *ManglingContextDecl; 8217 std::tie(MCtx, ManglingContextDecl) = 8218 getCurrentMangleNumberContext(NewVD->getDeclContext()); 8219 if (MCtx) { 8220 Context.setManglingNumber( 8221 NewVD, MCtx->getManglingNumber( 8222 NewVD, getMSManglingNumber(getLangOpts(), S))); 8223 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 8224 } 8225 } 8226 8227 // Special handling of variable named 'main'. 8228 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 8229 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 8230 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 8231 8232 // C++ [basic.start.main]p3 8233 // A program that declares a variable main at global scope is ill-formed. 8234 if (getLangOpts().CPlusPlus) 8235 Diag(D.getBeginLoc(), diag::err_main_global_variable); 8236 8237 // In C, and external-linkage variable named main results in undefined 8238 // behavior. 8239 else if (NewVD->hasExternalFormalLinkage()) 8240 Diag(D.getBeginLoc(), diag::warn_main_redefined); 8241 } 8242 8243 if (D.isRedeclaration() && !Previous.empty()) { 8244 NamedDecl *Prev = Previous.getRepresentativeDecl(); 8245 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 8246 D.isFunctionDefinition()); 8247 } 8248 8249 if (NewTemplate) { 8250 if (NewVD->isInvalidDecl()) 8251 NewTemplate->setInvalidDecl(); 8252 ActOnDocumentableDecl(NewTemplate); 8253 return NewTemplate; 8254 } 8255 8256 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 8257 CompleteMemberSpecialization(NewVD, Previous); 8258 8259 emitReadOnlyPlacementAttrWarning(*this, NewVD); 8260 8261 return NewVD; 8262 } 8263 8264 /// Enum describing the %select options in diag::warn_decl_shadow. 8265 enum ShadowedDeclKind { 8266 SDK_Local, 8267 SDK_Global, 8268 SDK_StaticMember, 8269 SDK_Field, 8270 SDK_Typedef, 8271 SDK_Using, 8272 SDK_StructuredBinding 8273 }; 8274 8275 /// Determine what kind of declaration we're shadowing. 8276 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 8277 const DeclContext *OldDC) { 8278 if (isa<TypeAliasDecl>(ShadowedDecl)) 8279 return SDK_Using; 8280 else if (isa<TypedefDecl>(ShadowedDecl)) 8281 return SDK_Typedef; 8282 else if (isa<BindingDecl>(ShadowedDecl)) 8283 return SDK_StructuredBinding; 8284 else if (isa<RecordDecl>(OldDC)) 8285 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 8286 8287 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 8288 } 8289 8290 /// Return the location of the capture if the given lambda captures the given 8291 /// variable \p VD, or an invalid source location otherwise. 8292 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 8293 const VarDecl *VD) { 8294 for (const Capture &Capture : LSI->Captures) { 8295 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 8296 return Capture.getLocation(); 8297 } 8298 return SourceLocation(); 8299 } 8300 8301 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 8302 const LookupResult &R) { 8303 // Only diagnose if we're shadowing an unambiguous field or variable. 8304 if (R.getResultKind() != LookupResult::Found) 8305 return false; 8306 8307 // Return false if warning is ignored. 8308 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 8309 } 8310 8311 /// Return the declaration shadowed by the given variable \p D, or null 8312 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8313 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 8314 const LookupResult &R) { 8315 if (!shouldWarnIfShadowedDecl(Diags, R)) 8316 return nullptr; 8317 8318 // Don't diagnose declarations at file scope. 8319 if (D->hasGlobalStorage() && !D->isStaticLocal()) 8320 return nullptr; 8321 8322 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8323 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8324 : nullptr; 8325 } 8326 8327 /// Return the declaration shadowed by the given typedef \p D, or null 8328 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8329 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 8330 const LookupResult &R) { 8331 // Don't warn if typedef declaration is part of a class 8332 if (D->getDeclContext()->isRecord()) 8333 return nullptr; 8334 8335 if (!shouldWarnIfShadowedDecl(Diags, R)) 8336 return nullptr; 8337 8338 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8339 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 8340 } 8341 8342 /// Return the declaration shadowed by the given variable \p D, or null 8343 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 8344 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 8345 const LookupResult &R) { 8346 if (!shouldWarnIfShadowedDecl(Diags, R)) 8347 return nullptr; 8348 8349 NamedDecl *ShadowedDecl = R.getFoundDecl(); 8350 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 8351 : nullptr; 8352 } 8353 8354 /// Diagnose variable or built-in function shadowing. Implements 8355 /// -Wshadow. 8356 /// 8357 /// This method is called whenever a VarDecl is added to a "useful" 8358 /// scope. 8359 /// 8360 /// \param ShadowedDecl the declaration that is shadowed by the given variable 8361 /// \param R the lookup of the name 8362 /// 8363 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 8364 const LookupResult &R) { 8365 DeclContext *NewDC = D->getDeclContext(); 8366 8367 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 8368 // Fields are not shadowed by variables in C++ static methods. 8369 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 8370 if (MD->isStatic()) 8371 return; 8372 8373 // Fields shadowed by constructor parameters are a special case. Usually 8374 // the constructor initializes the field with the parameter. 8375 if (isa<CXXConstructorDecl>(NewDC)) 8376 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 8377 // Remember that this was shadowed so we can either warn about its 8378 // modification or its existence depending on warning settings. 8379 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 8380 return; 8381 } 8382 } 8383 8384 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 8385 if (shadowedVar->isExternC()) { 8386 // For shadowing external vars, make sure that we point to the global 8387 // declaration, not a locally scoped extern declaration. 8388 for (auto *I : shadowedVar->redecls()) 8389 if (I->isFileVarDecl()) { 8390 ShadowedDecl = I; 8391 break; 8392 } 8393 } 8394 8395 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 8396 8397 unsigned WarningDiag = diag::warn_decl_shadow; 8398 SourceLocation CaptureLoc; 8399 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 8400 isa<CXXMethodDecl>(NewDC)) { 8401 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 8402 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 8403 if (RD->getLambdaCaptureDefault() == LCD_None) { 8404 // Try to avoid warnings for lambdas with an explicit capture list. 8405 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 8406 // Warn only when the lambda captures the shadowed decl explicitly. 8407 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 8408 if (CaptureLoc.isInvalid()) 8409 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 8410 } else { 8411 // Remember that this was shadowed so we can avoid the warning if the 8412 // shadowed decl isn't captured and the warning settings allow it. 8413 cast<LambdaScopeInfo>(getCurFunction()) 8414 ->ShadowingDecls.push_back( 8415 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 8416 return; 8417 } 8418 } 8419 8420 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 8421 // A variable can't shadow a local variable in an enclosing scope, if 8422 // they are separated by a non-capturing declaration context. 8423 for (DeclContext *ParentDC = NewDC; 8424 ParentDC && !ParentDC->Equals(OldDC); 8425 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8426 // Only block literals, captured statements, and lambda expressions 8427 // can capture; other scopes don't. 8428 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8429 !isLambdaCallOperator(ParentDC)) { 8430 return; 8431 } 8432 } 8433 } 8434 } 8435 } 8436 8437 // Never warn about shadowing a placeholder variable. 8438 if (ShadowedDecl->isPlaceholderVar(getLangOpts())) 8439 return; 8440 8441 // Only warn about certain kinds of shadowing for class members. 8442 if (NewDC && NewDC->isRecord()) { 8443 // In particular, don't warn about shadowing non-class members. 8444 if (!OldDC->isRecord()) 8445 return; 8446 8447 // TODO: should we warn about static data members shadowing 8448 // static data members from base classes? 8449 8450 // TODO: don't diagnose for inaccessible shadowed members. 8451 // This is hard to do perfectly because we might friend the 8452 // shadowing context, but that's just a false negative. 8453 } 8454 8455 8456 DeclarationName Name = R.getLookupName(); 8457 8458 // Emit warning and note. 8459 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8460 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8461 if (!CaptureLoc.isInvalid()) 8462 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8463 << Name << /*explicitly*/ 1; 8464 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8465 } 8466 8467 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8468 /// when these variables are captured by the lambda. 8469 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8470 for (const auto &Shadow : LSI->ShadowingDecls) { 8471 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 8472 // Try to avoid the warning when the shadowed decl isn't captured. 8473 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 8474 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8475 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 8476 ? diag::warn_decl_shadow_uncaptured_local 8477 : diag::warn_decl_shadow) 8478 << Shadow.VD->getDeclName() 8479 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8480 if (!CaptureLoc.isInvalid()) 8481 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8482 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8483 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8484 } 8485 } 8486 8487 /// Check -Wshadow without the advantage of a previous lookup. 8488 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8489 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8490 return; 8491 8492 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8493 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8494 LookupName(R, S); 8495 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8496 CheckShadow(D, ShadowedDecl, R); 8497 } 8498 8499 /// Check if 'E', which is an expression that is about to be modified, refers 8500 /// to a constructor parameter that shadows a field. 8501 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8502 // Quickly ignore expressions that can't be shadowing ctor parameters. 8503 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8504 return; 8505 E = E->IgnoreParenImpCasts(); 8506 auto *DRE = dyn_cast<DeclRefExpr>(E); 8507 if (!DRE) 8508 return; 8509 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8510 auto I = ShadowingDecls.find(D); 8511 if (I == ShadowingDecls.end()) 8512 return; 8513 const NamedDecl *ShadowedDecl = I->second; 8514 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8515 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8516 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8517 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8518 8519 // Avoid issuing multiple warnings about the same decl. 8520 ShadowingDecls.erase(I); 8521 } 8522 8523 /// Check for conflict between this global or extern "C" declaration and 8524 /// previous global or extern "C" declarations. This is only used in C++. 8525 template<typename T> 8526 static bool checkGlobalOrExternCConflict( 8527 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8528 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8529 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8530 8531 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8532 // The common case: this global doesn't conflict with any extern "C" 8533 // declaration. 8534 return false; 8535 } 8536 8537 if (Prev) { 8538 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8539 // Both the old and new declarations have C language linkage. This is a 8540 // redeclaration. 8541 Previous.clear(); 8542 Previous.addDecl(Prev); 8543 return true; 8544 } 8545 8546 // This is a global, non-extern "C" declaration, and there is a previous 8547 // non-global extern "C" declaration. Diagnose if this is a variable 8548 // declaration. 8549 if (!isa<VarDecl>(ND)) 8550 return false; 8551 } else { 8552 // The declaration is extern "C". Check for any declaration in the 8553 // translation unit which might conflict. 8554 if (IsGlobal) { 8555 // We have already performed the lookup into the translation unit. 8556 IsGlobal = false; 8557 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8558 I != E; ++I) { 8559 if (isa<VarDecl>(*I)) { 8560 Prev = *I; 8561 break; 8562 } 8563 } 8564 } else { 8565 DeclContext::lookup_result R = 8566 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8567 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8568 I != E; ++I) { 8569 if (isa<VarDecl>(*I)) { 8570 Prev = *I; 8571 break; 8572 } 8573 // FIXME: If we have any other entity with this name in global scope, 8574 // the declaration is ill-formed, but that is a defect: it breaks the 8575 // 'stat' hack, for instance. Only variables can have mangled name 8576 // clashes with extern "C" declarations, so only they deserve a 8577 // diagnostic. 8578 } 8579 } 8580 8581 if (!Prev) 8582 return false; 8583 } 8584 8585 // Use the first declaration's location to ensure we point at something which 8586 // is lexically inside an extern "C" linkage-spec. 8587 assert(Prev && "should have found a previous declaration to diagnose"); 8588 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8589 Prev = FD->getFirstDecl(); 8590 else 8591 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8592 8593 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8594 << IsGlobal << ND; 8595 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8596 << IsGlobal; 8597 return false; 8598 } 8599 8600 /// Apply special rules for handling extern "C" declarations. Returns \c true 8601 /// if we have found that this is a redeclaration of some prior entity. 8602 /// 8603 /// Per C++ [dcl.link]p6: 8604 /// Two declarations [for a function or variable] with C language linkage 8605 /// with the same name that appear in different scopes refer to the same 8606 /// [entity]. An entity with C language linkage shall not be declared with 8607 /// the same name as an entity in global scope. 8608 template<typename T> 8609 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8610 LookupResult &Previous) { 8611 if (!S.getLangOpts().CPlusPlus) { 8612 // In C, when declaring a global variable, look for a corresponding 'extern' 8613 // variable declared in function scope. We don't need this in C++, because 8614 // we find local extern decls in the surrounding file-scope DeclContext. 8615 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8616 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8617 Previous.clear(); 8618 Previous.addDecl(Prev); 8619 return true; 8620 } 8621 } 8622 return false; 8623 } 8624 8625 // A declaration in the translation unit can conflict with an extern "C" 8626 // declaration. 8627 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8628 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8629 8630 // An extern "C" declaration can conflict with a declaration in the 8631 // translation unit or can be a redeclaration of an extern "C" declaration 8632 // in another scope. 8633 if (isIncompleteDeclExternC(S,ND)) 8634 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8635 8636 // Neither global nor extern "C": nothing to do. 8637 return false; 8638 } 8639 8640 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8641 // If the decl is already known invalid, don't check it. 8642 if (NewVD->isInvalidDecl()) 8643 return; 8644 8645 QualType T = NewVD->getType(); 8646 8647 // Defer checking an 'auto' type until its initializer is attached. 8648 if (T->isUndeducedType()) 8649 return; 8650 8651 if (NewVD->hasAttrs()) 8652 CheckAlignasUnderalignment(NewVD); 8653 8654 if (T->isObjCObjectType()) { 8655 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8656 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8657 T = Context.getObjCObjectPointerType(T); 8658 NewVD->setType(T); 8659 } 8660 8661 // Emit an error if an address space was applied to decl with local storage. 8662 // This includes arrays of objects with address space qualifiers, but not 8663 // automatic variables that point to other address spaces. 8664 // ISO/IEC TR 18037 S5.1.2 8665 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8666 T.getAddressSpace() != LangAS::Default) { 8667 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8668 NewVD->setInvalidDecl(); 8669 return; 8670 } 8671 8672 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8673 // scope. 8674 if (getLangOpts().OpenCLVersion == 120 && 8675 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8676 getLangOpts()) && 8677 NewVD->isStaticLocal()) { 8678 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8679 NewVD->setInvalidDecl(); 8680 return; 8681 } 8682 8683 if (getLangOpts().OpenCL) { 8684 if (!diagnoseOpenCLTypes(*this, NewVD)) 8685 return; 8686 8687 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8688 if (NewVD->hasAttr<BlocksAttr>()) { 8689 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8690 return; 8691 } 8692 8693 if (T->isBlockPointerType()) { 8694 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8695 // can't use 'extern' storage class. 8696 if (!T.isConstQualified()) { 8697 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8698 << 0 /*const*/; 8699 NewVD->setInvalidDecl(); 8700 return; 8701 } 8702 if (NewVD->hasExternalStorage()) { 8703 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8704 NewVD->setInvalidDecl(); 8705 return; 8706 } 8707 } 8708 8709 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8710 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8711 NewVD->hasExternalStorage()) { 8712 if (!T->isSamplerT() && !T->isDependentType() && 8713 !(T.getAddressSpace() == LangAS::opencl_constant || 8714 (T.getAddressSpace() == LangAS::opencl_global && 8715 getOpenCLOptions().areProgramScopeVariablesSupported( 8716 getLangOpts())))) { 8717 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8718 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8719 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8720 << Scope << "global or constant"; 8721 else 8722 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8723 << Scope << "constant"; 8724 NewVD->setInvalidDecl(); 8725 return; 8726 } 8727 } else { 8728 if (T.getAddressSpace() == LangAS::opencl_global) { 8729 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8730 << 1 /*is any function*/ << "global"; 8731 NewVD->setInvalidDecl(); 8732 return; 8733 } 8734 if (T.getAddressSpace() == LangAS::opencl_constant || 8735 T.getAddressSpace() == LangAS::opencl_local) { 8736 FunctionDecl *FD = getCurFunctionDecl(); 8737 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8738 // in functions. 8739 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8740 if (T.getAddressSpace() == LangAS::opencl_constant) 8741 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8742 << 0 /*non-kernel only*/ << "constant"; 8743 else 8744 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8745 << 0 /*non-kernel only*/ << "local"; 8746 NewVD->setInvalidDecl(); 8747 return; 8748 } 8749 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8750 // in the outermost scope of a kernel function. 8751 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8752 if (!getCurScope()->isFunctionScope()) { 8753 if (T.getAddressSpace() == LangAS::opencl_constant) 8754 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8755 << "constant"; 8756 else 8757 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8758 << "local"; 8759 NewVD->setInvalidDecl(); 8760 return; 8761 } 8762 } 8763 } else if (T.getAddressSpace() != LangAS::opencl_private && 8764 // If we are parsing a template we didn't deduce an addr 8765 // space yet. 8766 T.getAddressSpace() != LangAS::Default) { 8767 // Do not allow other address spaces on automatic variable. 8768 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8769 NewVD->setInvalidDecl(); 8770 return; 8771 } 8772 } 8773 } 8774 8775 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8776 && !NewVD->hasAttr<BlocksAttr>()) { 8777 if (getLangOpts().getGC() != LangOptions::NonGC) 8778 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8779 else { 8780 assert(!getLangOpts().ObjCAutoRefCount); 8781 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8782 } 8783 } 8784 8785 // WebAssembly tables must be static with a zero length and can't be 8786 // declared within functions. 8787 if (T->isWebAssemblyTableType()) { 8788 if (getCurScope()->getParent()) { // Parent is null at top-level 8789 Diag(NewVD->getLocation(), diag::err_wasm_table_in_function); 8790 NewVD->setInvalidDecl(); 8791 return; 8792 } 8793 if (NewVD->getStorageClass() != SC_Static) { 8794 Diag(NewVD->getLocation(), diag::err_wasm_table_must_be_static); 8795 NewVD->setInvalidDecl(); 8796 return; 8797 } 8798 const auto *ATy = dyn_cast<ConstantArrayType>(T.getTypePtr()); 8799 if (!ATy || ATy->getSize().getSExtValue() != 0) { 8800 Diag(NewVD->getLocation(), 8801 diag::err_typecheck_wasm_table_must_have_zero_length); 8802 NewVD->setInvalidDecl(); 8803 return; 8804 } 8805 } 8806 8807 bool isVM = T->isVariablyModifiedType(); 8808 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8809 NewVD->hasAttr<BlocksAttr>()) 8810 setFunctionHasBranchProtectedScope(); 8811 8812 if ((isVM && NewVD->hasLinkage()) || 8813 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8814 bool SizeIsNegative; 8815 llvm::APSInt Oversized; 8816 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8817 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8818 QualType FixedT; 8819 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8820 FixedT = FixedTInfo->getType(); 8821 else if (FixedTInfo) { 8822 // Type and type-as-written are canonically different. We need to fix up 8823 // both types separately. 8824 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8825 Oversized); 8826 } 8827 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8828 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8829 // FIXME: This won't give the correct result for 8830 // int a[10][n]; 8831 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8832 8833 if (NewVD->isFileVarDecl()) 8834 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8835 << SizeRange; 8836 else if (NewVD->isStaticLocal()) 8837 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8838 << SizeRange; 8839 else 8840 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8841 << SizeRange; 8842 NewVD->setInvalidDecl(); 8843 return; 8844 } 8845 8846 if (!FixedTInfo) { 8847 if (NewVD->isFileVarDecl()) 8848 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8849 else 8850 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8851 NewVD->setInvalidDecl(); 8852 return; 8853 } 8854 8855 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8856 NewVD->setType(FixedT); 8857 NewVD->setTypeSourceInfo(FixedTInfo); 8858 } 8859 8860 if (T->isVoidType()) { 8861 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8862 // of objects and functions. 8863 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8864 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8865 << T; 8866 NewVD->setInvalidDecl(); 8867 return; 8868 } 8869 } 8870 8871 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8872 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8873 NewVD->setInvalidDecl(); 8874 return; 8875 } 8876 8877 if (!NewVD->hasLocalStorage() && T->isSizelessType() && 8878 !T.isWebAssemblyReferenceType()) { 8879 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8880 NewVD->setInvalidDecl(); 8881 return; 8882 } 8883 8884 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8885 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8886 NewVD->setInvalidDecl(); 8887 return; 8888 } 8889 8890 if (NewVD->isConstexpr() && !T->isDependentType() && 8891 RequireLiteralType(NewVD->getLocation(), T, 8892 diag::err_constexpr_var_non_literal)) { 8893 NewVD->setInvalidDecl(); 8894 return; 8895 } 8896 8897 // PPC MMA non-pointer types are not allowed as non-local variable types. 8898 if (Context.getTargetInfo().getTriple().isPPC64() && 8899 !NewVD->isLocalVarDecl() && 8900 CheckPPCMMAType(T, NewVD->getLocation())) { 8901 NewVD->setInvalidDecl(); 8902 return; 8903 } 8904 8905 // Check that SVE types are only used in functions with SVE available. 8906 if (T->isSVESizelessBuiltinType() && isa<FunctionDecl>(CurContext)) { 8907 const FunctionDecl *FD = cast<FunctionDecl>(CurContext); 8908 llvm::StringMap<bool> CallerFeatureMap; 8909 Context.getFunctionFeatureMap(CallerFeatureMap, FD); 8910 if (!Builtin::evaluateRequiredTargetFeatures( 8911 "sve", CallerFeatureMap)) { 8912 Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T; 8913 NewVD->setInvalidDecl(); 8914 return; 8915 } 8916 } 8917 8918 if (T->isRVVSizelessBuiltinType()) 8919 checkRVVTypeSupport(T, NewVD->getLocation(), cast<Decl>(CurContext)); 8920 } 8921 8922 /// Perform semantic checking on a newly-created variable 8923 /// declaration. 8924 /// 8925 /// This routine performs all of the type-checking required for a 8926 /// variable declaration once it has been built. It is used both to 8927 /// check variables after they have been parsed and their declarators 8928 /// have been translated into a declaration, and to check variables 8929 /// that have been instantiated from a template. 8930 /// 8931 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8932 /// 8933 /// Returns true if the variable declaration is a redeclaration. 8934 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8935 CheckVariableDeclarationType(NewVD); 8936 8937 // If the decl is already known invalid, don't check it. 8938 if (NewVD->isInvalidDecl()) 8939 return false; 8940 8941 // If we did not find anything by this name, look for a non-visible 8942 // extern "C" declaration with the same name. 8943 if (Previous.empty() && 8944 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8945 Previous.setShadowed(); 8946 8947 if (!Previous.empty()) { 8948 MergeVarDecl(NewVD, Previous); 8949 return true; 8950 } 8951 return false; 8952 } 8953 8954 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8955 /// and if so, check that it's a valid override and remember it. 8956 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8957 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8958 8959 // Look for methods in base classes that this method might override. 8960 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8961 /*DetectVirtual=*/false); 8962 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8963 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8964 DeclarationName Name = MD->getDeclName(); 8965 8966 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8967 // We really want to find the base class destructor here. 8968 QualType T = Context.getTypeDeclType(BaseRecord); 8969 CanQualType CT = Context.getCanonicalType(T); 8970 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8971 } 8972 8973 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8974 CXXMethodDecl *BaseMD = 8975 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8976 if (!BaseMD || !BaseMD->isVirtual() || 8977 IsOverride(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8978 /*ConsiderCudaAttrs=*/true)) 8979 continue; 8980 if (!CheckExplicitObjectOverride(MD, BaseMD)) 8981 continue; 8982 if (Overridden.insert(BaseMD).second) { 8983 MD->addOverriddenMethod(BaseMD); 8984 CheckOverridingFunctionReturnType(MD, BaseMD); 8985 CheckOverridingFunctionAttributes(MD, BaseMD); 8986 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8987 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8988 } 8989 8990 // A method can only override one function from each base class. We 8991 // don't track indirectly overridden methods from bases of bases. 8992 return true; 8993 } 8994 8995 return false; 8996 }; 8997 8998 DC->lookupInBases(VisitBase, Paths); 8999 return !Overridden.empty(); 9000 } 9001 9002 namespace { 9003 // Struct for holding all of the extra arguments needed by 9004 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 9005 struct ActOnFDArgs { 9006 Scope *S; 9007 Declarator &D; 9008 MultiTemplateParamsArg TemplateParamLists; 9009 bool AddToScope; 9010 }; 9011 } // end anonymous namespace 9012 9013 namespace { 9014 9015 // Callback to only accept typo corrections that have a non-zero edit distance. 9016 // Also only accept corrections that have the same parent decl. 9017 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 9018 public: 9019 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 9020 CXXRecordDecl *Parent) 9021 : Context(Context), OriginalFD(TypoFD), 9022 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 9023 9024 bool ValidateCandidate(const TypoCorrection &candidate) override { 9025 if (candidate.getEditDistance() == 0) 9026 return false; 9027 9028 SmallVector<unsigned, 1> MismatchedParams; 9029 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 9030 CDeclEnd = candidate.end(); 9031 CDecl != CDeclEnd; ++CDecl) { 9032 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9033 9034 if (FD && !FD->hasBody() && 9035 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 9036 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 9037 CXXRecordDecl *Parent = MD->getParent(); 9038 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 9039 return true; 9040 } else if (!ExpectedParent) { 9041 return true; 9042 } 9043 } 9044 } 9045 9046 return false; 9047 } 9048 9049 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9050 return std::make_unique<DifferentNameValidatorCCC>(*this); 9051 } 9052 9053 private: 9054 ASTContext &Context; 9055 FunctionDecl *OriginalFD; 9056 CXXRecordDecl *ExpectedParent; 9057 }; 9058 9059 } // end anonymous namespace 9060 9061 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 9062 TypoCorrectedFunctionDefinitions.insert(F); 9063 } 9064 9065 /// Generate diagnostics for an invalid function redeclaration. 9066 /// 9067 /// This routine handles generating the diagnostic messages for an invalid 9068 /// function redeclaration, including finding possible similar declarations 9069 /// or performing typo correction if there are no previous declarations with 9070 /// the same name. 9071 /// 9072 /// Returns a NamedDecl iff typo correction was performed and substituting in 9073 /// the new declaration name does not cause new errors. 9074 static NamedDecl *DiagnoseInvalidRedeclaration( 9075 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 9076 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 9077 DeclarationName Name = NewFD->getDeclName(); 9078 DeclContext *NewDC = NewFD->getDeclContext(); 9079 SmallVector<unsigned, 1> MismatchedParams; 9080 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 9081 TypoCorrection Correction; 9082 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 9083 unsigned DiagMsg = 9084 IsLocalFriend ? diag::err_no_matching_local_friend : 9085 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 9086 diag::err_member_decl_does_not_match; 9087 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 9088 IsLocalFriend ? Sema::LookupLocalFriendName 9089 : Sema::LookupOrdinaryName, 9090 Sema::ForVisibleRedeclaration); 9091 9092 NewFD->setInvalidDecl(); 9093 if (IsLocalFriend) 9094 SemaRef.LookupName(Prev, S); 9095 else 9096 SemaRef.LookupQualifiedName(Prev, NewDC); 9097 assert(!Prev.isAmbiguous() && 9098 "Cannot have an ambiguity in previous-declaration lookup"); 9099 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9100 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 9101 MD ? MD->getParent() : nullptr); 9102 if (!Prev.empty()) { 9103 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 9104 Func != FuncEnd; ++Func) { 9105 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 9106 if (FD && 9107 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9108 // Add 1 to the index so that 0 can mean the mismatch didn't 9109 // involve a parameter 9110 unsigned ParamNum = 9111 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 9112 NearMatches.push_back(std::make_pair(FD, ParamNum)); 9113 } 9114 } 9115 // If the qualified name lookup yielded nothing, try typo correction 9116 } else if ((Correction = SemaRef.CorrectTypo( 9117 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 9118 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 9119 IsLocalFriend ? nullptr : NewDC))) { 9120 // Set up everything for the call to ActOnFunctionDeclarator 9121 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 9122 ExtraArgs.D.getIdentifierLoc()); 9123 Previous.clear(); 9124 Previous.setLookupName(Correction.getCorrection()); 9125 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 9126 CDeclEnd = Correction.end(); 9127 CDecl != CDeclEnd; ++CDecl) { 9128 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 9129 if (FD && !FD->hasBody() && 9130 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 9131 Previous.addDecl(FD); 9132 } 9133 } 9134 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 9135 9136 NamedDecl *Result; 9137 // Retry building the function declaration with the new previous 9138 // declarations, and with errors suppressed. 9139 { 9140 // Trap errors. 9141 Sema::SFINAETrap Trap(SemaRef); 9142 9143 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 9144 // pieces need to verify the typo-corrected C++ declaration and hopefully 9145 // eliminate the need for the parameter pack ExtraArgs. 9146 Result = SemaRef.ActOnFunctionDeclarator( 9147 ExtraArgs.S, ExtraArgs.D, 9148 Correction.getCorrectionDecl()->getDeclContext(), 9149 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 9150 ExtraArgs.AddToScope); 9151 9152 if (Trap.hasErrorOccurred()) 9153 Result = nullptr; 9154 } 9155 9156 if (Result) { 9157 // Determine which correction we picked. 9158 Decl *Canonical = Result->getCanonicalDecl(); 9159 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9160 I != E; ++I) 9161 if ((*I)->getCanonicalDecl() == Canonical) 9162 Correction.setCorrectionDecl(*I); 9163 9164 // Let Sema know about the correction. 9165 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 9166 SemaRef.diagnoseTypo( 9167 Correction, 9168 SemaRef.PDiag(IsLocalFriend 9169 ? diag::err_no_matching_local_friend_suggest 9170 : diag::err_member_decl_does_not_match_suggest) 9171 << Name << NewDC << IsDefinition); 9172 return Result; 9173 } 9174 9175 // Pretend the typo correction never occurred 9176 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 9177 ExtraArgs.D.getIdentifierLoc()); 9178 ExtraArgs.D.setRedeclaration(wasRedeclaration); 9179 Previous.clear(); 9180 Previous.setLookupName(Name); 9181 } 9182 9183 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 9184 << Name << NewDC << IsDefinition << NewFD->getLocation(); 9185 9186 bool NewFDisConst = false; 9187 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 9188 NewFDisConst = NewMD->isConst(); 9189 9190 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 9191 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 9192 NearMatch != NearMatchEnd; ++NearMatch) { 9193 FunctionDecl *FD = NearMatch->first; 9194 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 9195 bool FDisConst = MD && MD->isConst(); 9196 bool IsMember = MD || !IsLocalFriend; 9197 9198 // FIXME: These notes are poorly worded for the local friend case. 9199 if (unsigned Idx = NearMatch->second) { 9200 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 9201 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 9202 if (Loc.isInvalid()) Loc = FD->getLocation(); 9203 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 9204 : diag::note_local_decl_close_param_match) 9205 << Idx << FDParam->getType() 9206 << NewFD->getParamDecl(Idx - 1)->getType(); 9207 } else if (FDisConst != NewFDisConst) { 9208 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 9209 << NewFDisConst << FD->getSourceRange().getEnd() 9210 << (NewFDisConst 9211 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 9212 .getConstQualifierLoc()) 9213 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 9214 .getRParenLoc() 9215 .getLocWithOffset(1), 9216 " const")); 9217 } else 9218 SemaRef.Diag(FD->getLocation(), 9219 IsMember ? diag::note_member_def_close_match 9220 : diag::note_local_decl_close_match); 9221 } 9222 return nullptr; 9223 } 9224 9225 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 9226 switch (D.getDeclSpec().getStorageClassSpec()) { 9227 default: llvm_unreachable("Unknown storage class!"); 9228 case DeclSpec::SCS_auto: 9229 case DeclSpec::SCS_register: 9230 case DeclSpec::SCS_mutable: 9231 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9232 diag::err_typecheck_sclass_func); 9233 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9234 D.setInvalidType(); 9235 break; 9236 case DeclSpec::SCS_unspecified: break; 9237 case DeclSpec::SCS_extern: 9238 if (D.getDeclSpec().isExternInLinkageSpec()) 9239 return SC_None; 9240 return SC_Extern; 9241 case DeclSpec::SCS_static: { 9242 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 9243 // C99 6.7.1p5: 9244 // The declaration of an identifier for a function that has 9245 // block scope shall have no explicit storage-class specifier 9246 // other than extern 9247 // See also (C++ [dcl.stc]p4). 9248 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9249 diag::err_static_block_func); 9250 break; 9251 } else 9252 return SC_Static; 9253 } 9254 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 9255 } 9256 9257 // No explicit storage class has already been returned 9258 return SC_None; 9259 } 9260 9261 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 9262 DeclContext *DC, QualType &R, 9263 TypeSourceInfo *TInfo, 9264 StorageClass SC, 9265 bool &IsVirtualOkay) { 9266 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 9267 DeclarationName Name = NameInfo.getName(); 9268 9269 FunctionDecl *NewFD = nullptr; 9270 bool isInline = D.getDeclSpec().isInlineSpecified(); 9271 9272 if (!SemaRef.getLangOpts().CPlusPlus) { 9273 // Determine whether the function was written with a prototype. This is 9274 // true when: 9275 // - there is a prototype in the declarator, or 9276 // - the type R of the function is some kind of typedef or other non- 9277 // attributed reference to a type name (which eventually refers to a 9278 // function type). Note, we can't always look at the adjusted type to 9279 // check this case because attributes may cause a non-function 9280 // declarator to still have a function type. e.g., 9281 // typedef void func(int a); 9282 // __attribute__((noreturn)) func other_func; // This has a prototype 9283 bool HasPrototype = 9284 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 9285 (D.getDeclSpec().isTypeRep() && 9286 SemaRef.GetTypeFromParser(D.getDeclSpec().getRepAsType(), nullptr) 9287 ->isFunctionProtoType()) || 9288 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 9289 assert( 9290 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 9291 "Strict prototypes are required"); 9292 9293 NewFD = FunctionDecl::Create( 9294 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9295 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 9296 ConstexprSpecKind::Unspecified, 9297 /*TrailingRequiresClause=*/nullptr); 9298 if (D.isInvalidType()) 9299 NewFD->setInvalidDecl(); 9300 9301 return NewFD; 9302 } 9303 9304 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 9305 9306 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9307 if (ConstexprKind == ConstexprSpecKind::Constinit) { 9308 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 9309 diag::err_constexpr_wrong_decl_kind) 9310 << static_cast<int>(ConstexprKind); 9311 ConstexprKind = ConstexprSpecKind::Unspecified; 9312 D.getMutableDeclSpec().ClearConstexprSpec(); 9313 } 9314 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 9315 9316 SemaRef.CheckExplicitObjectMemberFunction(DC, D, Name, R); 9317 9318 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 9319 // This is a C++ constructor declaration. 9320 assert(DC->isRecord() && 9321 "Constructors can only be declared in a member context"); 9322 9323 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 9324 return CXXConstructorDecl::Create( 9325 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9326 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 9327 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 9328 InheritedConstructor(), TrailingRequiresClause); 9329 9330 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9331 // This is a C++ destructor declaration. 9332 if (DC->isRecord()) { 9333 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 9334 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 9335 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 9336 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 9337 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9338 /*isImplicitlyDeclared=*/false, ConstexprKind, 9339 TrailingRequiresClause); 9340 // User defined destructors start as not selected if the class definition is still 9341 // not done. 9342 if (Record->isBeingDefined()) 9343 NewDD->setIneligibleOrNotSelected(true); 9344 9345 // If the destructor needs an implicit exception specification, set it 9346 // now. FIXME: It'd be nice to be able to create the right type to start 9347 // with, but the type needs to reference the destructor declaration. 9348 if (SemaRef.getLangOpts().CPlusPlus11) 9349 SemaRef.AdjustDestructorExceptionSpec(NewDD); 9350 9351 IsVirtualOkay = true; 9352 return NewDD; 9353 9354 } else { 9355 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 9356 D.setInvalidType(); 9357 9358 // Create a FunctionDecl to satisfy the function definition parsing 9359 // code path. 9360 return FunctionDecl::Create( 9361 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 9362 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9363 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 9364 } 9365 9366 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 9367 if (!DC->isRecord()) { 9368 SemaRef.Diag(D.getIdentifierLoc(), 9369 diag::err_conv_function_not_member); 9370 return nullptr; 9371 } 9372 9373 SemaRef.CheckConversionDeclarator(D, R, SC); 9374 if (D.isInvalidType()) 9375 return nullptr; 9376 9377 IsVirtualOkay = true; 9378 return CXXConversionDecl::Create( 9379 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9380 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9381 ExplicitSpecifier, ConstexprKind, SourceLocation(), 9382 TrailingRequiresClause); 9383 9384 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 9385 if (TrailingRequiresClause) 9386 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 9387 diag::err_trailing_requires_clause_on_deduction_guide) 9388 << TrailingRequiresClause->getSourceRange(); 9389 if (SemaRef.CheckDeductionGuideDeclarator(D, R, SC)) 9390 return nullptr; 9391 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 9392 ExplicitSpecifier, NameInfo, R, TInfo, 9393 D.getEndLoc()); 9394 } else if (DC->isRecord()) { 9395 // If the name of the function is the same as the name of the record, 9396 // then this must be an invalid constructor that has a return type. 9397 // (The parser checks for a return type and makes the declarator a 9398 // constructor if it has no return type). 9399 if (Name.getAsIdentifierInfo() && 9400 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 9401 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 9402 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 9403 << SourceRange(D.getIdentifierLoc()); 9404 return nullptr; 9405 } 9406 9407 // This is a C++ method declaration. 9408 CXXMethodDecl *Ret = CXXMethodDecl::Create( 9409 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 9410 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9411 ConstexprKind, SourceLocation(), TrailingRequiresClause); 9412 IsVirtualOkay = !Ret->isStatic(); 9413 return Ret; 9414 } else { 9415 bool isFriend = 9416 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 9417 if (!isFriend && SemaRef.CurContext->isRecord()) 9418 return nullptr; 9419 9420 // Determine whether the function was written with a 9421 // prototype. This true when: 9422 // - we're in C++ (where every function has a prototype), 9423 return FunctionDecl::Create( 9424 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9425 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9426 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 9427 } 9428 } 9429 9430 enum OpenCLParamType { 9431 ValidKernelParam, 9432 PtrPtrKernelParam, 9433 PtrKernelParam, 9434 InvalidAddrSpacePtrKernelParam, 9435 InvalidKernelParam, 9436 RecordKernelParam 9437 }; 9438 9439 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 9440 // Size dependent types are just typedefs to normal integer types 9441 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 9442 // integers other than by their names. 9443 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 9444 9445 // Remove typedefs one by one until we reach a typedef 9446 // for a size dependent type. 9447 QualType DesugaredTy = Ty; 9448 do { 9449 ArrayRef<StringRef> Names(SizeTypeNames); 9450 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 9451 if (Names.end() != Match) 9452 return true; 9453 9454 Ty = DesugaredTy; 9455 DesugaredTy = Ty.getSingleStepDesugaredType(C); 9456 } while (DesugaredTy != Ty); 9457 9458 return false; 9459 } 9460 9461 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9462 if (PT->isDependentType()) 9463 return InvalidKernelParam; 9464 9465 if (PT->isPointerType() || PT->isReferenceType()) { 9466 QualType PointeeType = PT->getPointeeType(); 9467 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9468 PointeeType.getAddressSpace() == LangAS::opencl_private || 9469 PointeeType.getAddressSpace() == LangAS::Default) 9470 return InvalidAddrSpacePtrKernelParam; 9471 9472 if (PointeeType->isPointerType()) { 9473 // This is a pointer to pointer parameter. 9474 // Recursively check inner type. 9475 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9476 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9477 ParamKind == InvalidKernelParam) 9478 return ParamKind; 9479 9480 // OpenCL v3.0 s6.11.a: 9481 // A restriction to pass pointers to pointers only applies to OpenCL C 9482 // v1.2 or below. 9483 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9484 return ValidKernelParam; 9485 9486 return PtrPtrKernelParam; 9487 } 9488 9489 // C++ for OpenCL v1.0 s2.4: 9490 // Moreover the types used in parameters of the kernel functions must be: 9491 // Standard layout types for pointer parameters. The same applies to 9492 // reference if an implementation supports them in kernel parameters. 9493 if (S.getLangOpts().OpenCLCPlusPlus && 9494 !S.getOpenCLOptions().isAvailableOption( 9495 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) { 9496 auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl(); 9497 bool IsStandardLayoutType = true; 9498 if (CXXRec) { 9499 // If template type is not ODR-used its definition is only available 9500 // in the template definition not its instantiation. 9501 // FIXME: This logic doesn't work for types that depend on template 9502 // parameter (PR58590). 9503 if (!CXXRec->hasDefinition()) 9504 CXXRec = CXXRec->getTemplateInstantiationPattern(); 9505 if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout()) 9506 IsStandardLayoutType = false; 9507 } 9508 if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9509 !IsStandardLayoutType) 9510 return InvalidKernelParam; 9511 } 9512 9513 // OpenCL v1.2 s6.9.p: 9514 // A restriction to pass pointers only applies to OpenCL C v1.2 or below. 9515 if (S.getLangOpts().getOpenCLCompatibleVersion() > 120) 9516 return ValidKernelParam; 9517 9518 return PtrKernelParam; 9519 } 9520 9521 // OpenCL v1.2 s6.9.k: 9522 // Arguments to kernel functions in a program cannot be declared with the 9523 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9524 // uintptr_t or a struct and/or union that contain fields declared to be one 9525 // of these built-in scalar types. 9526 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9527 return InvalidKernelParam; 9528 9529 if (PT->isImageType()) 9530 return PtrKernelParam; 9531 9532 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9533 return InvalidKernelParam; 9534 9535 // OpenCL extension spec v1.2 s9.5: 9536 // This extension adds support for half scalar and vector types as built-in 9537 // types that can be used for arithmetic operations, conversions etc. 9538 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9539 PT->isHalfType()) 9540 return InvalidKernelParam; 9541 9542 // Look into an array argument to check if it has a forbidden type. 9543 if (PT->isArrayType()) { 9544 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9545 // Call ourself to check an underlying type of an array. Since the 9546 // getPointeeOrArrayElementType returns an innermost type which is not an 9547 // array, this recursive call only happens once. 9548 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9549 } 9550 9551 // C++ for OpenCL v1.0 s2.4: 9552 // Moreover the types used in parameters of the kernel functions must be: 9553 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9554 // types) for parameters passed by value; 9555 if (S.getLangOpts().OpenCLCPlusPlus && 9556 !S.getOpenCLOptions().isAvailableOption( 9557 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9558 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9559 return InvalidKernelParam; 9560 9561 if (PT->isRecordType()) 9562 return RecordKernelParam; 9563 9564 return ValidKernelParam; 9565 } 9566 9567 static void checkIsValidOpenCLKernelParameter( 9568 Sema &S, 9569 Declarator &D, 9570 ParmVarDecl *Param, 9571 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9572 QualType PT = Param->getType(); 9573 9574 // Cache the valid types we encounter to avoid rechecking structs that are 9575 // used again 9576 if (ValidTypes.count(PT.getTypePtr())) 9577 return; 9578 9579 switch (getOpenCLKernelParameterType(S, PT)) { 9580 case PtrPtrKernelParam: 9581 // OpenCL v3.0 s6.11.a: 9582 // A kernel function argument cannot be declared as a pointer to a pointer 9583 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9584 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9585 D.setInvalidType(); 9586 return; 9587 9588 case InvalidAddrSpacePtrKernelParam: 9589 // OpenCL v1.0 s6.5: 9590 // __kernel function arguments declared to be a pointer of a type can point 9591 // to one of the following address spaces only : __global, __local or 9592 // __constant. 9593 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9594 D.setInvalidType(); 9595 return; 9596 9597 // OpenCL v1.2 s6.9.k: 9598 // Arguments to kernel functions in a program cannot be declared with the 9599 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9600 // uintptr_t or a struct and/or union that contain fields declared to be 9601 // one of these built-in scalar types. 9602 9603 case InvalidKernelParam: 9604 // OpenCL v1.2 s6.8 n: 9605 // A kernel function argument cannot be declared 9606 // of event_t type. 9607 // Do not diagnose half type since it is diagnosed as invalid argument 9608 // type for any function elsewhere. 9609 if (!PT->isHalfType()) { 9610 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9611 9612 // Explain what typedefs are involved. 9613 const TypedefType *Typedef = nullptr; 9614 while ((Typedef = PT->getAs<TypedefType>())) { 9615 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9616 // SourceLocation may be invalid for a built-in type. 9617 if (Loc.isValid()) 9618 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9619 PT = Typedef->desugar(); 9620 } 9621 } 9622 9623 D.setInvalidType(); 9624 return; 9625 9626 case PtrKernelParam: 9627 case ValidKernelParam: 9628 ValidTypes.insert(PT.getTypePtr()); 9629 return; 9630 9631 case RecordKernelParam: 9632 break; 9633 } 9634 9635 // Track nested structs we will inspect 9636 SmallVector<const Decl *, 4> VisitStack; 9637 9638 // Track where we are in the nested structs. Items will migrate from 9639 // VisitStack to HistoryStack as we do the DFS for bad field. 9640 SmallVector<const FieldDecl *, 4> HistoryStack; 9641 HistoryStack.push_back(nullptr); 9642 9643 // At this point we already handled everything except of a RecordType or 9644 // an ArrayType of a RecordType. 9645 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9646 const RecordType *RecTy = 9647 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9648 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9649 9650 VisitStack.push_back(RecTy->getDecl()); 9651 assert(VisitStack.back() && "First decl null?"); 9652 9653 do { 9654 const Decl *Next = VisitStack.pop_back_val(); 9655 if (!Next) { 9656 assert(!HistoryStack.empty()); 9657 // Found a marker, we have gone up a level 9658 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9659 ValidTypes.insert(Hist->getType().getTypePtr()); 9660 9661 continue; 9662 } 9663 9664 // Adds everything except the original parameter declaration (which is not a 9665 // field itself) to the history stack. 9666 const RecordDecl *RD; 9667 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9668 HistoryStack.push_back(Field); 9669 9670 QualType FieldTy = Field->getType(); 9671 // Other field types (known to be valid or invalid) are handled while we 9672 // walk around RecordDecl::fields(). 9673 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9674 "Unexpected type."); 9675 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9676 9677 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9678 } else { 9679 RD = cast<RecordDecl>(Next); 9680 } 9681 9682 // Add a null marker so we know when we've gone back up a level 9683 VisitStack.push_back(nullptr); 9684 9685 for (const auto *FD : RD->fields()) { 9686 QualType QT = FD->getType(); 9687 9688 if (ValidTypes.count(QT.getTypePtr())) 9689 continue; 9690 9691 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9692 if (ParamType == ValidKernelParam) 9693 continue; 9694 9695 if (ParamType == RecordKernelParam) { 9696 VisitStack.push_back(FD); 9697 continue; 9698 } 9699 9700 // OpenCL v1.2 s6.9.p: 9701 // Arguments to kernel functions that are declared to be a struct or union 9702 // do not allow OpenCL objects to be passed as elements of the struct or 9703 // union. This restriction was lifted in OpenCL v2.0 with the introduction 9704 // of SVM. 9705 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9706 ParamType == InvalidAddrSpacePtrKernelParam) { 9707 S.Diag(Param->getLocation(), 9708 diag::err_record_with_pointers_kernel_param) 9709 << PT->isUnionType() 9710 << PT; 9711 } else { 9712 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9713 } 9714 9715 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9716 << OrigRecDecl->getDeclName(); 9717 9718 // We have an error, now let's go back up through history and show where 9719 // the offending field came from 9720 for (ArrayRef<const FieldDecl *>::const_iterator 9721 I = HistoryStack.begin() + 1, 9722 E = HistoryStack.end(); 9723 I != E; ++I) { 9724 const FieldDecl *OuterField = *I; 9725 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9726 << OuterField->getType(); 9727 } 9728 9729 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9730 << QT->isPointerType() 9731 << QT; 9732 D.setInvalidType(); 9733 return; 9734 } 9735 } while (!VisitStack.empty()); 9736 } 9737 9738 /// Find the DeclContext in which a tag is implicitly declared if we see an 9739 /// elaborated type specifier in the specified context, and lookup finds 9740 /// nothing. 9741 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9742 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9743 DC = DC->getParent(); 9744 return DC; 9745 } 9746 9747 /// Find the Scope in which a tag is implicitly declared if we see an 9748 /// elaborated type specifier in the specified context, and lookup finds 9749 /// nothing. 9750 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9751 while (S->isClassScope() || 9752 (LangOpts.CPlusPlus && 9753 S->isFunctionPrototypeScope()) || 9754 ((S->getFlags() & Scope::DeclScope) == 0) || 9755 (S->getEntity() && S->getEntity()->isTransparentContext())) 9756 S = S->getParent(); 9757 return S; 9758 } 9759 9760 /// Determine whether a declaration matches a known function in namespace std. 9761 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9762 unsigned BuiltinID) { 9763 switch (BuiltinID) { 9764 case Builtin::BI__GetExceptionInfo: 9765 // No type checking whatsoever. 9766 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9767 9768 case Builtin::BIaddressof: 9769 case Builtin::BI__addressof: 9770 case Builtin::BIforward: 9771 case Builtin::BIforward_like: 9772 case Builtin::BImove: 9773 case Builtin::BImove_if_noexcept: 9774 case Builtin::BIas_const: { 9775 // Ensure that we don't treat the algorithm 9776 // OutputIt std::move(InputIt, InputIt, OutputIt) 9777 // as the builtin std::move. 9778 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9779 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9780 } 9781 9782 default: 9783 return false; 9784 } 9785 } 9786 9787 NamedDecl* 9788 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9789 TypeSourceInfo *TInfo, LookupResult &Previous, 9790 MultiTemplateParamsArg TemplateParamListsRef, 9791 bool &AddToScope) { 9792 QualType R = TInfo->getType(); 9793 9794 assert(R->isFunctionType()); 9795 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9796 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9797 9798 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9799 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9800 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9801 if (!TemplateParamLists.empty() && 9802 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9803 TemplateParamLists.back() = Invented; 9804 else 9805 TemplateParamLists.push_back(Invented); 9806 } 9807 9808 // TODO: consider using NameInfo for diagnostic. 9809 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9810 DeclarationName Name = NameInfo.getName(); 9811 StorageClass SC = getFunctionStorageClass(*this, D); 9812 9813 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9814 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9815 diag::err_invalid_thread) 9816 << DeclSpec::getSpecifierName(TSCS); 9817 9818 if (D.isFirstDeclarationOfMember()) 9819 adjustMemberFunctionCC( 9820 R, !(D.isStaticMember() || D.isExplicitObjectMemberFunction()), 9821 D.isCtorOrDtor(), D.getIdentifierLoc()); 9822 9823 bool isFriend = false; 9824 FunctionTemplateDecl *FunctionTemplate = nullptr; 9825 bool isMemberSpecialization = false; 9826 bool isFunctionTemplateSpecialization = false; 9827 9828 bool HasExplicitTemplateArgs = false; 9829 TemplateArgumentListInfo TemplateArgs; 9830 9831 bool isVirtualOkay = false; 9832 9833 DeclContext *OriginalDC = DC; 9834 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9835 9836 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9837 isVirtualOkay); 9838 if (!NewFD) return nullptr; 9839 9840 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9841 NewFD->setTopLevelDeclInObjCContainer(); 9842 9843 // Set the lexical context. If this is a function-scope declaration, or has a 9844 // C++ scope specifier, or is the object of a friend declaration, the lexical 9845 // context will be different from the semantic context. 9846 NewFD->setLexicalDeclContext(CurContext); 9847 9848 if (IsLocalExternDecl) 9849 NewFD->setLocalExternDecl(); 9850 9851 if (getLangOpts().CPlusPlus) { 9852 // The rules for implicit inlines changed in C++20 for methods and friends 9853 // with an in-class definition (when such a definition is not attached to 9854 // the global module). User-specified 'inline' overrides this (set when 9855 // the function decl is created above). 9856 // FIXME: We need a better way to separate C++ standard and clang modules. 9857 bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules || 9858 !NewFD->getOwningModule() || 9859 NewFD->getOwningModule()->isGlobalModule() || 9860 NewFD->getOwningModule()->isHeaderLikeModule(); 9861 bool isInline = D.getDeclSpec().isInlineSpecified(); 9862 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9863 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9864 isFriend = D.getDeclSpec().isFriendSpecified(); 9865 if (isFriend && !isInline && D.isFunctionDefinition()) { 9866 // Pre-C++20 [class.friend]p5 9867 // A function can be defined in a friend declaration of a 9868 // class . . . . Such a function is implicitly inline. 9869 // Post C++20 [class.friend]p7 9870 // Such a function is implicitly an inline function if it is attached 9871 // to the global module. 9872 NewFD->setImplicitlyInline(ImplicitInlineCXX20); 9873 } 9874 9875 // If this is a method defined in an __interface, and is not a constructor 9876 // or an overloaded operator, then set the pure flag (isVirtual will already 9877 // return true). 9878 if (const CXXRecordDecl *Parent = 9879 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9880 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9881 NewFD->setIsPureVirtual(true); 9882 9883 // C++ [class.union]p2 9884 // A union can have member functions, but not virtual functions. 9885 if (isVirtual && Parent->isUnion()) { 9886 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9887 NewFD->setInvalidDecl(); 9888 } 9889 if ((Parent->isClass() || Parent->isStruct()) && 9890 Parent->hasAttr<SYCLSpecialClassAttr>() && 9891 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9892 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9893 if (auto *Def = Parent->getDefinition()) 9894 Def->setInitMethod(true); 9895 } 9896 } 9897 9898 SetNestedNameSpecifier(*this, NewFD, D); 9899 isMemberSpecialization = false; 9900 isFunctionTemplateSpecialization = false; 9901 if (D.isInvalidType()) 9902 NewFD->setInvalidDecl(); 9903 9904 // Match up the template parameter lists with the scope specifier, then 9905 // determine whether we have a template or a template specialization. 9906 bool Invalid = false; 9907 TemplateIdAnnotation *TemplateId = 9908 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9909 ? D.getName().TemplateId 9910 : nullptr; 9911 TemplateParameterList *TemplateParams = 9912 MatchTemplateParametersToScopeSpecifier( 9913 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9914 D.getCXXScopeSpec(), TemplateId, TemplateParamLists, isFriend, 9915 isMemberSpecialization, Invalid); 9916 if (TemplateParams) { 9917 // Check that we can declare a template here. 9918 if (CheckTemplateDeclScope(S, TemplateParams)) 9919 NewFD->setInvalidDecl(); 9920 9921 if (TemplateParams->size() > 0) { 9922 // This is a function template 9923 9924 // A destructor cannot be a template. 9925 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9926 Diag(NewFD->getLocation(), diag::err_destructor_template); 9927 NewFD->setInvalidDecl(); 9928 // Function template with explicit template arguments. 9929 } else if (TemplateId) { 9930 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9931 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9932 NewFD->setInvalidDecl(); 9933 } 9934 9935 // If we're adding a template to a dependent context, we may need to 9936 // rebuilding some of the types used within the template parameter list, 9937 // now that we know what the current instantiation is. 9938 if (DC->isDependentContext()) { 9939 ContextRAII SavedContext(*this, DC); 9940 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9941 Invalid = true; 9942 } 9943 9944 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9945 NewFD->getLocation(), 9946 Name, TemplateParams, 9947 NewFD); 9948 FunctionTemplate->setLexicalDeclContext(CurContext); 9949 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9950 9951 // For source fidelity, store the other template param lists. 9952 if (TemplateParamLists.size() > 1) { 9953 NewFD->setTemplateParameterListsInfo(Context, 9954 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9955 .drop_back(1)); 9956 } 9957 } else { 9958 // This is a function template specialization. 9959 isFunctionTemplateSpecialization = true; 9960 // For source fidelity, store all the template param lists. 9961 if (TemplateParamLists.size() > 0) 9962 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9963 9964 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9965 if (isFriend) { 9966 // We want to remove the "template<>", found here. 9967 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9968 9969 // If we remove the template<> and the name is not a 9970 // template-id, we're actually silently creating a problem: 9971 // the friend declaration will refer to an untemplated decl, 9972 // and clearly the user wants a template specialization. So 9973 // we need to insert '<>' after the name. 9974 SourceLocation InsertLoc; 9975 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9976 InsertLoc = D.getName().getSourceRange().getEnd(); 9977 InsertLoc = getLocForEndOfToken(InsertLoc); 9978 } 9979 9980 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9981 << Name << RemoveRange 9982 << FixItHint::CreateRemoval(RemoveRange) 9983 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9984 Invalid = true; 9985 9986 // Recover by faking up an empty template argument list. 9987 HasExplicitTemplateArgs = true; 9988 TemplateArgs.setLAngleLoc(InsertLoc); 9989 TemplateArgs.setRAngleLoc(InsertLoc); 9990 } 9991 } 9992 } else { 9993 // Check that we can declare a template here. 9994 if (!TemplateParamLists.empty() && isMemberSpecialization && 9995 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9996 NewFD->setInvalidDecl(); 9997 9998 // All template param lists were matched against the scope specifier: 9999 // this is NOT (an explicit specialization of) a template. 10000 if (TemplateParamLists.size() > 0) 10001 // For source fidelity, store all the template param lists. 10002 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 10003 10004 // "friend void foo<>(int);" is an implicit specialization decl. 10005 if (isFriend && TemplateId) 10006 isFunctionTemplateSpecialization = true; 10007 } 10008 10009 // If this is a function template specialization and the unqualified-id of 10010 // the declarator-id is a template-id, convert the template argument list 10011 // into our AST format and check for unexpanded packs. 10012 if (isFunctionTemplateSpecialization && TemplateId) { 10013 HasExplicitTemplateArgs = true; 10014 10015 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 10016 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 10017 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 10018 TemplateId->NumArgs); 10019 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 10020 10021 // FIXME: Should we check for unexpanded packs if this was an (invalid) 10022 // declaration of a function template partial specialization? Should we 10023 // consider the unexpanded pack context to be a partial specialization? 10024 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs.arguments()) { 10025 if (DiagnoseUnexpandedParameterPack( 10026 ArgLoc, isFriend ? UPPC_FriendDeclaration 10027 : UPPC_ExplicitSpecialization)) 10028 NewFD->setInvalidDecl(); 10029 } 10030 } 10031 10032 if (Invalid) { 10033 NewFD->setInvalidDecl(); 10034 if (FunctionTemplate) 10035 FunctionTemplate->setInvalidDecl(); 10036 } 10037 10038 // C++ [dcl.fct.spec]p5: 10039 // The virtual specifier shall only be used in declarations of 10040 // nonstatic class member functions that appear within a 10041 // member-specification of a class declaration; see 10.3. 10042 // 10043 if (isVirtual && !NewFD->isInvalidDecl()) { 10044 if (!isVirtualOkay) { 10045 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10046 diag::err_virtual_non_function); 10047 } else if (!CurContext->isRecord()) { 10048 // 'virtual' was specified outside of the class. 10049 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10050 diag::err_virtual_out_of_class) 10051 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10052 } else if (NewFD->getDescribedFunctionTemplate()) { 10053 // C++ [temp.mem]p3: 10054 // A member function template shall not be virtual. 10055 Diag(D.getDeclSpec().getVirtualSpecLoc(), 10056 diag::err_virtual_member_function_template) 10057 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 10058 } else { 10059 // Okay: Add virtual to the method. 10060 NewFD->setVirtualAsWritten(true); 10061 } 10062 10063 if (getLangOpts().CPlusPlus14 && 10064 NewFD->getReturnType()->isUndeducedType()) 10065 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 10066 } 10067 10068 if (getLangOpts().CPlusPlus14 && 10069 (NewFD->isDependentContext() || 10070 (isFriend && CurContext->isDependentContext())) && 10071 NewFD->getReturnType()->isUndeducedType()) { 10072 // If the function template is referenced directly (for instance, as a 10073 // member of the current instantiation), pretend it has a dependent type. 10074 // This is not really justified by the standard, but is the only sane 10075 // thing to do. 10076 // FIXME: For a friend function, we have not marked the function as being 10077 // a friend yet, so 'isDependentContext' on the FD doesn't work. 10078 const FunctionProtoType *FPT = 10079 NewFD->getType()->castAs<FunctionProtoType>(); 10080 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 10081 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 10082 FPT->getExtProtoInfo())); 10083 } 10084 10085 // C++ [dcl.fct.spec]p3: 10086 // The inline specifier shall not appear on a block scope function 10087 // declaration. 10088 if (isInline && !NewFD->isInvalidDecl()) { 10089 if (CurContext->isFunctionOrMethod()) { 10090 // 'inline' is not allowed on block scope function declaration. 10091 Diag(D.getDeclSpec().getInlineSpecLoc(), 10092 diag::err_inline_declaration_block_scope) << Name 10093 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 10094 } 10095 } 10096 10097 // C++ [dcl.fct.spec]p6: 10098 // The explicit specifier shall be used only in the declaration of a 10099 // constructor or conversion function within its class definition; 10100 // see 12.3.1 and 12.3.2. 10101 if (hasExplicit && !NewFD->isInvalidDecl() && 10102 !isa<CXXDeductionGuideDecl>(NewFD)) { 10103 if (!CurContext->isRecord()) { 10104 // 'explicit' was specified outside of the class. 10105 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10106 diag::err_explicit_out_of_class) 10107 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10108 } else if (!isa<CXXConstructorDecl>(NewFD) && 10109 !isa<CXXConversionDecl>(NewFD)) { 10110 // 'explicit' was specified on a function that wasn't a constructor 10111 // or conversion function. 10112 Diag(D.getDeclSpec().getExplicitSpecLoc(), 10113 diag::err_explicit_non_ctor_or_conv_function) 10114 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 10115 } 10116 } 10117 10118 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 10119 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 10120 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 10121 // are implicitly inline. 10122 NewFD->setImplicitlyInline(); 10123 10124 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 10125 // be either constructors or to return a literal type. Therefore, 10126 // destructors cannot be declared constexpr. 10127 if (isa<CXXDestructorDecl>(NewFD) && 10128 (!getLangOpts().CPlusPlus20 || 10129 ConstexprKind == ConstexprSpecKind::Consteval)) { 10130 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 10131 << static_cast<int>(ConstexprKind); 10132 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 10133 ? ConstexprSpecKind::Unspecified 10134 : ConstexprSpecKind::Constexpr); 10135 } 10136 // C++20 [dcl.constexpr]p2: An allocation function, or a 10137 // deallocation function shall not be declared with the consteval 10138 // specifier. 10139 if (ConstexprKind == ConstexprSpecKind::Consteval && 10140 (NewFD->getOverloadedOperator() == OO_New || 10141 NewFD->getOverloadedOperator() == OO_Array_New || 10142 NewFD->getOverloadedOperator() == OO_Delete || 10143 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 10144 Diag(D.getDeclSpec().getConstexprSpecLoc(), 10145 diag::err_invalid_consteval_decl_kind) 10146 << NewFD; 10147 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 10148 } 10149 } 10150 10151 // If __module_private__ was specified, mark the function accordingly. 10152 if (D.getDeclSpec().isModulePrivateSpecified()) { 10153 if (isFunctionTemplateSpecialization) { 10154 SourceLocation ModulePrivateLoc 10155 = D.getDeclSpec().getModulePrivateSpecLoc(); 10156 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 10157 << 0 10158 << FixItHint::CreateRemoval(ModulePrivateLoc); 10159 } else { 10160 NewFD->setModulePrivate(); 10161 if (FunctionTemplate) 10162 FunctionTemplate->setModulePrivate(); 10163 } 10164 } 10165 10166 if (isFriend) { 10167 if (FunctionTemplate) { 10168 FunctionTemplate->setObjectOfFriendDecl(); 10169 FunctionTemplate->setAccess(AS_public); 10170 } 10171 NewFD->setObjectOfFriendDecl(); 10172 NewFD->setAccess(AS_public); 10173 } 10174 10175 // If a function is defined as defaulted or deleted, mark it as such now. 10176 // We'll do the relevant checks on defaulted / deleted functions later. 10177 switch (D.getFunctionDefinitionKind()) { 10178 case FunctionDefinitionKind::Declaration: 10179 case FunctionDefinitionKind::Definition: 10180 break; 10181 10182 case FunctionDefinitionKind::Defaulted: 10183 NewFD->setDefaulted(); 10184 break; 10185 10186 case FunctionDefinitionKind::Deleted: 10187 NewFD->setDeletedAsWritten(); 10188 break; 10189 } 10190 10191 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 10192 D.isFunctionDefinition() && !isInline) { 10193 // Pre C++20 [class.mfct]p2: 10194 // A member function may be defined (8.4) in its class definition, in 10195 // which case it is an inline member function (7.1.2) 10196 // Post C++20 [class.mfct]p1: 10197 // If a member function is attached to the global module and is defined 10198 // in its class definition, it is inline. 10199 NewFD->setImplicitlyInline(ImplicitInlineCXX20); 10200 } 10201 10202 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 10203 !CurContext->isRecord()) { 10204 // C++ [class.static]p1: 10205 // A data or function member of a class may be declared static 10206 // in a class definition, in which case it is a static member of 10207 // the class. 10208 10209 // Complain about the 'static' specifier if it's on an out-of-line 10210 // member function definition. 10211 10212 // MSVC permits the use of a 'static' storage specifier on an out-of-line 10213 // member function template declaration and class member template 10214 // declaration (MSVC versions before 2015), warn about this. 10215 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 10216 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 10217 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 10218 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 10219 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 10220 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10221 } 10222 10223 // C++11 [except.spec]p15: 10224 // A deallocation function with no exception-specification is treated 10225 // as if it were specified with noexcept(true). 10226 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 10227 if ((Name.getCXXOverloadedOperator() == OO_Delete || 10228 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 10229 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 10230 NewFD->setType(Context.getFunctionType( 10231 FPT->getReturnType(), FPT->getParamTypes(), 10232 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 10233 10234 // C++20 [dcl.inline]/7 10235 // If an inline function or variable that is attached to a named module 10236 // is declared in a definition domain, it shall be defined in that 10237 // domain. 10238 // So, if the current declaration does not have a definition, we must 10239 // check at the end of the TU (or when the PMF starts) to see that we 10240 // have a definition at that point. 10241 if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 && 10242 NewFD->hasOwningModule() && NewFD->getOwningModule()->isNamedModule()) { 10243 PendingInlineFuncDecls.insert(NewFD); 10244 } 10245 } 10246 10247 // Filter out previous declarations that don't match the scope. 10248 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 10249 D.getCXXScopeSpec().isNotEmpty() || 10250 isMemberSpecialization || 10251 isFunctionTemplateSpecialization); 10252 10253 // Handle GNU asm-label extension (encoded as an attribute). 10254 if (Expr *E = (Expr*) D.getAsmLabel()) { 10255 // The parser guarantees this is a string. 10256 StringLiteral *SE = cast<StringLiteral>(E); 10257 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 10258 /*IsLiteralLabel=*/true, 10259 SE->getStrTokenLoc(0))); 10260 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 10261 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 10262 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 10263 if (I != ExtnameUndeclaredIdentifiers.end()) { 10264 if (isDeclExternC(NewFD)) { 10265 NewFD->addAttr(I->second); 10266 ExtnameUndeclaredIdentifiers.erase(I); 10267 } else 10268 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 10269 << /*Variable*/0 << NewFD; 10270 } 10271 } 10272 10273 // Copy the parameter declarations from the declarator D to the function 10274 // declaration NewFD, if they are available. First scavenge them into Params. 10275 SmallVector<ParmVarDecl*, 16> Params; 10276 unsigned FTIIdx; 10277 if (D.isFunctionDeclarator(FTIIdx)) { 10278 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 10279 10280 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 10281 // function that takes no arguments, not a function that takes a 10282 // single void argument. 10283 // We let through "const void" here because Sema::GetTypeForDeclarator 10284 // already checks for that case. 10285 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 10286 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 10287 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 10288 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 10289 Param->setDeclContext(NewFD); 10290 Params.push_back(Param); 10291 10292 if (Param->isInvalidDecl()) 10293 NewFD->setInvalidDecl(); 10294 } 10295 } 10296 10297 if (!getLangOpts().CPlusPlus) { 10298 // In C, find all the tag declarations from the prototype and move them 10299 // into the function DeclContext. Remove them from the surrounding tag 10300 // injection context of the function, which is typically but not always 10301 // the TU. 10302 DeclContext *PrototypeTagContext = 10303 getTagInjectionContext(NewFD->getLexicalDeclContext()); 10304 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 10305 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 10306 10307 // We don't want to reparent enumerators. Look at their parent enum 10308 // instead. 10309 if (!TD) { 10310 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 10311 TD = cast<EnumDecl>(ECD->getDeclContext()); 10312 } 10313 if (!TD) 10314 continue; 10315 DeclContext *TagDC = TD->getLexicalDeclContext(); 10316 if (!TagDC->containsDecl(TD)) 10317 continue; 10318 TagDC->removeDecl(TD); 10319 TD->setDeclContext(NewFD); 10320 NewFD->addDecl(TD); 10321 10322 // Preserve the lexical DeclContext if it is not the surrounding tag 10323 // injection context of the FD. In this example, the semantic context of 10324 // E will be f and the lexical context will be S, while both the 10325 // semantic and lexical contexts of S will be f: 10326 // void f(struct S { enum E { a } f; } s); 10327 if (TagDC != PrototypeTagContext) 10328 TD->setLexicalDeclContext(TagDC); 10329 } 10330 } 10331 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 10332 // When we're declaring a function with a typedef, typeof, etc as in the 10333 // following example, we'll need to synthesize (unnamed) 10334 // parameters for use in the declaration. 10335 // 10336 // @code 10337 // typedef void fn(int); 10338 // fn f; 10339 // @endcode 10340 10341 // Synthesize a parameter for each argument type. 10342 for (const auto &AI : FT->param_types()) { 10343 ParmVarDecl *Param = 10344 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 10345 Param->setScopeInfo(0, Params.size()); 10346 Params.push_back(Param); 10347 } 10348 } else { 10349 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 10350 "Should not need args for typedef of non-prototype fn"); 10351 } 10352 10353 // Finally, we know we have the right number of parameters, install them. 10354 NewFD->setParams(Params); 10355 10356 if (D.getDeclSpec().isNoreturnSpecified()) 10357 NewFD->addAttr( 10358 C11NoReturnAttr::Create(Context, D.getDeclSpec().getNoreturnSpecLoc())); 10359 10360 // Functions returning a variably modified type violate C99 6.7.5.2p2 10361 // because all functions have linkage. 10362 if (!NewFD->isInvalidDecl() && 10363 NewFD->getReturnType()->isVariablyModifiedType()) { 10364 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 10365 NewFD->setInvalidDecl(); 10366 } 10367 10368 // Apply an implicit SectionAttr if '#pragma clang section text' is active 10369 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 10370 !NewFD->hasAttr<SectionAttr>()) 10371 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 10372 Context, PragmaClangTextSection.SectionName, 10373 PragmaClangTextSection.PragmaLocation)); 10374 10375 // Apply an implicit SectionAttr if #pragma code_seg is active. 10376 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 10377 !NewFD->hasAttr<SectionAttr>()) { 10378 NewFD->addAttr(SectionAttr::CreateImplicit( 10379 Context, CodeSegStack.CurrentValue->getString(), 10380 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate)); 10381 if (UnifySection(CodeSegStack.CurrentValue->getString(), 10382 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 10383 ASTContext::PSF_Read, 10384 NewFD)) 10385 NewFD->dropAttr<SectionAttr>(); 10386 } 10387 10388 // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is 10389 // active. 10390 if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() && 10391 !NewFD->hasAttr<StrictGuardStackCheckAttr>()) 10392 NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit( 10393 Context, PragmaClangTextSection.PragmaLocation)); 10394 10395 // Apply an implicit CodeSegAttr from class declspec or 10396 // apply an implicit SectionAttr from #pragma code_seg if active. 10397 if (!NewFD->hasAttr<CodeSegAttr>()) { 10398 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 10399 D.isFunctionDefinition())) { 10400 NewFD->addAttr(SAttr); 10401 } 10402 } 10403 10404 // Handle attributes. 10405 ProcessDeclAttributes(S, NewFD, D); 10406 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 10407 if (NewTVA && !NewTVA->isDefaultVersion() && 10408 !Context.getTargetInfo().hasFeature("fmv")) { 10409 // Don't add to scope fmv functions declarations if fmv disabled 10410 AddToScope = false; 10411 return NewFD; 10412 } 10413 10414 if (getLangOpts().OpenCL || getLangOpts().HLSL) { 10415 // Neither OpenCL nor HLSL allow an address space qualifyer on a return 10416 // type. 10417 // 10418 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 10419 // type declaration will generate a compilation error. 10420 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 10421 if (AddressSpace != LangAS::Default) { 10422 Diag(NewFD->getLocation(), diag::err_return_value_with_address_space); 10423 NewFD->setInvalidDecl(); 10424 } 10425 } 10426 10427 if (!getLangOpts().CPlusPlus) { 10428 // Perform semantic checking on the function declaration. 10429 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10430 CheckMain(NewFD, D.getDeclSpec()); 10431 10432 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10433 CheckMSVCRTEntryPoint(NewFD); 10434 10435 if (!NewFD->isInvalidDecl()) 10436 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10437 isMemberSpecialization, 10438 D.isFunctionDefinition())); 10439 else if (!Previous.empty()) 10440 // Recover gracefully from an invalid redeclaration. 10441 D.setRedeclaration(true); 10442 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10443 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10444 "previous declaration set still overloaded"); 10445 10446 // Diagnose no-prototype function declarations with calling conventions that 10447 // don't support variadic calls. Only do this in C and do it after merging 10448 // possibly prototyped redeclarations. 10449 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 10450 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 10451 CallingConv CC = FT->getExtInfo().getCC(); 10452 if (!supportsVariadicCall(CC)) { 10453 // Windows system headers sometimes accidentally use stdcall without 10454 // (void) parameters, so we relax this to a warning. 10455 int DiagID = 10456 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 10457 Diag(NewFD->getLocation(), DiagID) 10458 << FunctionType::getNameForCallConv(CC); 10459 } 10460 } 10461 10462 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 10463 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 10464 checkNonTrivialCUnion(NewFD->getReturnType(), 10465 NewFD->getReturnTypeSourceRange().getBegin(), 10466 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 10467 } else { 10468 // C++11 [replacement.functions]p3: 10469 // The program's definitions shall not be specified as inline. 10470 // 10471 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 10472 // 10473 // Suppress the diagnostic if the function is __attribute__((used)), since 10474 // that forces an external definition to be emitted. 10475 if (D.getDeclSpec().isInlineSpecified() && 10476 NewFD->isReplaceableGlobalAllocationFunction() && 10477 !NewFD->hasAttr<UsedAttr>()) 10478 Diag(D.getDeclSpec().getInlineSpecLoc(), 10479 diag::ext_operator_new_delete_declared_inline) 10480 << NewFD->getDeclName(); 10481 10482 // We do not add HD attributes to specializations here because 10483 // they may have different constexpr-ness compared to their 10484 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 10485 // may end up with different effective targets. Instead, a 10486 // specialization inherits its target attributes from its template 10487 // in the CheckFunctionTemplateSpecialization() call below. 10488 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 10489 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 10490 10491 // Handle explict specializations of function templates 10492 // and friend function declarations with an explicit 10493 // template argument list. 10494 if (isFunctionTemplateSpecialization) { 10495 bool isDependentSpecialization = false; 10496 if (isFriend) { 10497 // For friend function specializations, this is a dependent 10498 // specialization if its semantic context is dependent, its 10499 // type is dependent, or if its template-id is dependent. 10500 isDependentSpecialization = 10501 DC->isDependentContext() || NewFD->getType()->isDependentType() || 10502 (HasExplicitTemplateArgs && 10503 TemplateSpecializationType:: 10504 anyInstantiationDependentTemplateArguments( 10505 TemplateArgs.arguments())); 10506 assert((!isDependentSpecialization || 10507 (HasExplicitTemplateArgs == isDependentSpecialization)) && 10508 "dependent friend function specialization without template " 10509 "args"); 10510 } else { 10511 // For class-scope explicit specializations of function templates, 10512 // if the lexical context is dependent, then the specialization 10513 // is dependent. 10514 isDependentSpecialization = 10515 CurContext->isRecord() && CurContext->isDependentContext(); 10516 } 10517 10518 TemplateArgumentListInfo *ExplicitTemplateArgs = 10519 HasExplicitTemplateArgs ? &TemplateArgs : nullptr; 10520 if (isDependentSpecialization) { 10521 // If it's a dependent specialization, it may not be possible 10522 // to determine the primary template (for explicit specializations) 10523 // or befriended declaration (for friends) until the enclosing 10524 // template is instantiated. In such cases, we store the declarations 10525 // found by name lookup and defer resolution until instantiation. 10526 if (CheckDependentFunctionTemplateSpecialization( 10527 NewFD, ExplicitTemplateArgs, Previous)) 10528 NewFD->setInvalidDecl(); 10529 } else if (!NewFD->isInvalidDecl()) { 10530 if (CheckFunctionTemplateSpecialization(NewFD, ExplicitTemplateArgs, 10531 Previous)) 10532 NewFD->setInvalidDecl(); 10533 } 10534 10535 // C++ [dcl.stc]p1: 10536 // A storage-class-specifier shall not be specified in an explicit 10537 // specialization (14.7.3) 10538 // FIXME: We should be checking this for dependent specializations. 10539 FunctionTemplateSpecializationInfo *Info = 10540 NewFD->getTemplateSpecializationInfo(); 10541 if (Info && SC != SC_None) { 10542 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 10543 Diag(NewFD->getLocation(), 10544 diag::err_explicit_specialization_inconsistent_storage_class) 10545 << SC 10546 << FixItHint::CreateRemoval( 10547 D.getDeclSpec().getStorageClassSpecLoc()); 10548 10549 else 10550 Diag(NewFD->getLocation(), 10551 diag::ext_explicit_specialization_storage_class) 10552 << FixItHint::CreateRemoval( 10553 D.getDeclSpec().getStorageClassSpecLoc()); 10554 } 10555 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10556 if (CheckMemberSpecialization(NewFD, Previous)) 10557 NewFD->setInvalidDecl(); 10558 } 10559 10560 // Perform semantic checking on the function declaration. 10561 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10562 CheckMain(NewFD, D.getDeclSpec()); 10563 10564 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10565 CheckMSVCRTEntryPoint(NewFD); 10566 10567 if (!NewFD->isInvalidDecl()) 10568 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10569 isMemberSpecialization, 10570 D.isFunctionDefinition())); 10571 else if (!Previous.empty()) 10572 // Recover gracefully from an invalid redeclaration. 10573 D.setRedeclaration(true); 10574 10575 assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() || 10576 !D.isRedeclaration() || 10577 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10578 "previous declaration set still overloaded"); 10579 10580 NamedDecl *PrincipalDecl = (FunctionTemplate 10581 ? cast<NamedDecl>(FunctionTemplate) 10582 : NewFD); 10583 10584 if (isFriend && NewFD->getPreviousDecl()) { 10585 AccessSpecifier Access = AS_public; 10586 if (!NewFD->isInvalidDecl()) 10587 Access = NewFD->getPreviousDecl()->getAccess(); 10588 10589 NewFD->setAccess(Access); 10590 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10591 } 10592 10593 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10594 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10595 PrincipalDecl->setNonMemberOperator(); 10596 10597 // If we have a function template, check the template parameter 10598 // list. This will check and merge default template arguments. 10599 if (FunctionTemplate) { 10600 FunctionTemplateDecl *PrevTemplate = 10601 FunctionTemplate->getPreviousDecl(); 10602 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10603 PrevTemplate ? PrevTemplate->getTemplateParameters() 10604 : nullptr, 10605 D.getDeclSpec().isFriendSpecified() 10606 ? (D.isFunctionDefinition() 10607 ? TPC_FriendFunctionTemplateDefinition 10608 : TPC_FriendFunctionTemplate) 10609 : (D.getCXXScopeSpec().isSet() && 10610 DC && DC->isRecord() && 10611 DC->isDependentContext()) 10612 ? TPC_ClassTemplateMember 10613 : TPC_FunctionTemplate); 10614 } 10615 10616 if (NewFD->isInvalidDecl()) { 10617 // Ignore all the rest of this. 10618 } else if (!D.isRedeclaration()) { 10619 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10620 AddToScope }; 10621 // Fake up an access specifier if it's supposed to be a class member. 10622 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10623 NewFD->setAccess(AS_public); 10624 10625 // Qualified decls generally require a previous declaration. 10626 if (D.getCXXScopeSpec().isSet()) { 10627 // ...with the major exception of templated-scope or 10628 // dependent-scope friend declarations. 10629 10630 // TODO: we currently also suppress this check in dependent 10631 // contexts because (1) the parameter depth will be off when 10632 // matching friend templates and (2) we might actually be 10633 // selecting a friend based on a dependent factor. But there 10634 // are situations where these conditions don't apply and we 10635 // can actually do this check immediately. 10636 // 10637 // Unless the scope is dependent, it's always an error if qualified 10638 // redeclaration lookup found nothing at all. Diagnose that now; 10639 // nothing will diagnose that error later. 10640 if (isFriend && 10641 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10642 (!Previous.empty() && CurContext->isDependentContext()))) { 10643 // ignore these 10644 } else if (NewFD->isCPUDispatchMultiVersion() || 10645 NewFD->isCPUSpecificMultiVersion()) { 10646 // ignore this, we allow the redeclaration behavior here to create new 10647 // versions of the function. 10648 } else { 10649 // The user tried to provide an out-of-line definition for a 10650 // function that is a member of a class or namespace, but there 10651 // was no such member function declared (C++ [class.mfct]p2, 10652 // C++ [namespace.memdef]p2). For example: 10653 // 10654 // class X { 10655 // void f() const; 10656 // }; 10657 // 10658 // void X::f() { } // ill-formed 10659 // 10660 // Complain about this problem, and attempt to suggest close 10661 // matches (e.g., those that differ only in cv-qualifiers and 10662 // whether the parameter types are references). 10663 10664 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10665 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10666 AddToScope = ExtraArgs.AddToScope; 10667 return Result; 10668 } 10669 } 10670 10671 // Unqualified local friend declarations are required to resolve 10672 // to something. 10673 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10674 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10675 *this, Previous, NewFD, ExtraArgs, true, S)) { 10676 AddToScope = ExtraArgs.AddToScope; 10677 return Result; 10678 } 10679 } 10680 } else if (!D.isFunctionDefinition() && 10681 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10682 !isFriend && !isFunctionTemplateSpecialization && 10683 !isMemberSpecialization) { 10684 // An out-of-line member function declaration must also be a 10685 // definition (C++ [class.mfct]p2). 10686 // Note that this is not the case for explicit specializations of 10687 // function templates or member functions of class templates, per 10688 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10689 // extension for compatibility with old SWIG code which likes to 10690 // generate them. 10691 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10692 << D.getCXXScopeSpec().getRange(); 10693 } 10694 } 10695 10696 if (getLangOpts().HLSL && D.isFunctionDefinition()) { 10697 // Any top level function could potentially be specified as an entry. 10698 if (!NewFD->isInvalidDecl() && S->getDepth() == 0 && Name.isIdentifier()) 10699 ActOnHLSLTopLevelFunction(NewFD); 10700 10701 if (NewFD->hasAttr<HLSLShaderAttr>()) 10702 CheckHLSLEntryPoint(NewFD); 10703 } 10704 10705 // If this is the first declaration of a library builtin function, add 10706 // attributes as appropriate. 10707 if (!D.isRedeclaration()) { 10708 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10709 if (unsigned BuiltinID = II->getBuiltinID()) { 10710 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10711 if (!InStdNamespace && 10712 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10713 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10714 // Validate the type matches unless this builtin is specified as 10715 // matching regardless of its declared type. 10716 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10717 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10718 } else { 10719 ASTContext::GetBuiltinTypeError Error; 10720 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10721 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10722 10723 if (!Error && !BuiltinType.isNull() && 10724 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10725 NewFD->getType(), BuiltinType)) 10726 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10727 } 10728 } 10729 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10730 isStdBuiltin(Context, NewFD, BuiltinID)) { 10731 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10732 } 10733 } 10734 } 10735 } 10736 10737 ProcessPragmaWeak(S, NewFD); 10738 checkAttributesAfterMerging(*this, *NewFD); 10739 10740 AddKnownFunctionAttributes(NewFD); 10741 10742 if (NewFD->hasAttr<OverloadableAttr>() && 10743 !NewFD->getType()->getAs<FunctionProtoType>()) { 10744 Diag(NewFD->getLocation(), 10745 diag::err_attribute_overloadable_no_prototype) 10746 << NewFD; 10747 NewFD->dropAttr<OverloadableAttr>(); 10748 } 10749 10750 // If there's a #pragma GCC visibility in scope, and this isn't a class 10751 // member, set the visibility of this function. 10752 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10753 AddPushedVisibilityAttribute(NewFD); 10754 10755 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10756 // marking the function. 10757 AddCFAuditedAttribute(NewFD); 10758 10759 // If this is a function definition, check if we have to apply any 10760 // attributes (i.e. optnone and no_builtin) due to a pragma. 10761 if (D.isFunctionDefinition()) { 10762 AddRangeBasedOptnone(NewFD); 10763 AddImplicitMSFunctionNoBuiltinAttr(NewFD); 10764 AddSectionMSAllocText(NewFD); 10765 ModifyFnAttributesMSPragmaOptimize(NewFD); 10766 } 10767 10768 // If this is the first declaration of an extern C variable, update 10769 // the map of such variables. 10770 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10771 isIncompleteDeclExternC(*this, NewFD)) 10772 RegisterLocallyScopedExternCDecl(NewFD, S); 10773 10774 // Set this FunctionDecl's range up to the right paren. 10775 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10776 10777 if (D.isRedeclaration() && !Previous.empty()) { 10778 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10779 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10780 isMemberSpecialization || 10781 isFunctionTemplateSpecialization, 10782 D.isFunctionDefinition()); 10783 } 10784 10785 if (getLangOpts().CUDA) { 10786 IdentifierInfo *II = NewFD->getIdentifier(); 10787 if (II && II->isStr(getCudaConfigureFuncName()) && 10788 !NewFD->isInvalidDecl() && 10789 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10790 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10791 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10792 << getCudaConfigureFuncName(); 10793 Context.setcudaConfigureCallDecl(NewFD); 10794 } 10795 10796 // Variadic functions, other than a *declaration* of printf, are not allowed 10797 // in device-side CUDA code, unless someone passed 10798 // -fcuda-allow-variadic-functions. 10799 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10800 (NewFD->hasAttr<CUDADeviceAttr>() || 10801 NewFD->hasAttr<CUDAGlobalAttr>()) && 10802 !(II && II->isStr("printf") && NewFD->isExternC() && 10803 !D.isFunctionDefinition())) { 10804 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10805 } 10806 } 10807 10808 MarkUnusedFileScopedDecl(NewFD); 10809 10810 10811 10812 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10813 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10814 if (SC == SC_Static) { 10815 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10816 D.setInvalidType(); 10817 } 10818 10819 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10820 if (!NewFD->getReturnType()->isVoidType()) { 10821 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10822 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10823 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10824 : FixItHint()); 10825 D.setInvalidType(); 10826 } 10827 10828 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10829 for (auto *Param : NewFD->parameters()) 10830 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10831 10832 if (getLangOpts().OpenCLCPlusPlus) { 10833 if (DC->isRecord()) { 10834 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10835 D.setInvalidType(); 10836 } 10837 if (FunctionTemplate) { 10838 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10839 D.setInvalidType(); 10840 } 10841 } 10842 } 10843 10844 if (getLangOpts().CPlusPlus) { 10845 // Precalculate whether this is a friend function template with a constraint 10846 // that depends on an enclosing template, per [temp.friend]p9. 10847 if (isFriend && FunctionTemplate && 10848 FriendConstraintsDependOnEnclosingTemplate(NewFD)) { 10849 NewFD->setFriendConstraintRefersToEnclosingTemplate(true); 10850 10851 // C++ [temp.friend]p9: 10852 // A friend function template with a constraint that depends on a 10853 // template parameter from an enclosing template shall be a definition. 10854 if (!D.isFunctionDefinition()) { 10855 Diag(NewFD->getBeginLoc(), 10856 diag::err_friend_decl_with_enclosing_temp_constraint_must_be_def); 10857 NewFD->setInvalidDecl(); 10858 } 10859 } 10860 10861 if (FunctionTemplate) { 10862 if (NewFD->isInvalidDecl()) 10863 FunctionTemplate->setInvalidDecl(); 10864 return FunctionTemplate; 10865 } 10866 10867 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10868 CompleteMemberSpecialization(NewFD, Previous); 10869 } 10870 10871 for (const ParmVarDecl *Param : NewFD->parameters()) { 10872 QualType PT = Param->getType(); 10873 10874 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10875 // types. 10876 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10877 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10878 QualType ElemTy = PipeTy->getElementType(); 10879 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10880 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10881 D.setInvalidType(); 10882 } 10883 } 10884 } 10885 // WebAssembly tables can't be used as function parameters. 10886 if (Context.getTargetInfo().getTriple().isWasm()) { 10887 if (PT->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) { 10888 Diag(Param->getTypeSpecStartLoc(), 10889 diag::err_wasm_table_as_function_parameter); 10890 D.setInvalidType(); 10891 } 10892 } 10893 } 10894 10895 // Diagnose availability attributes. Availability cannot be used on functions 10896 // that are run during load/unload. 10897 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10898 if (NewFD->hasAttr<ConstructorAttr>()) { 10899 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10900 << 1; 10901 NewFD->dropAttr<AvailabilityAttr>(); 10902 } 10903 if (NewFD->hasAttr<DestructorAttr>()) { 10904 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10905 << 2; 10906 NewFD->dropAttr<AvailabilityAttr>(); 10907 } 10908 } 10909 10910 // Diagnose no_builtin attribute on function declaration that are not a 10911 // definition. 10912 // FIXME: We should really be doing this in 10913 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10914 // the FunctionDecl and at this point of the code 10915 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10916 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10917 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10918 switch (D.getFunctionDefinitionKind()) { 10919 case FunctionDefinitionKind::Defaulted: 10920 case FunctionDefinitionKind::Deleted: 10921 Diag(NBA->getLocation(), 10922 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10923 << NBA->getSpelling(); 10924 break; 10925 case FunctionDefinitionKind::Declaration: 10926 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10927 << NBA->getSpelling(); 10928 break; 10929 case FunctionDefinitionKind::Definition: 10930 break; 10931 } 10932 10933 return NewFD; 10934 } 10935 10936 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10937 /// when __declspec(code_seg) "is applied to a class, all member functions of 10938 /// the class and nested classes -- this includes compiler-generated special 10939 /// member functions -- are put in the specified segment." 10940 /// The actual behavior is a little more complicated. The Microsoft compiler 10941 /// won't check outer classes if there is an active value from #pragma code_seg. 10942 /// The CodeSeg is always applied from the direct parent but only from outer 10943 /// classes when the #pragma code_seg stack is empty. See: 10944 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10945 /// available since MS has removed the page. 10946 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10947 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10948 if (!Method) 10949 return nullptr; 10950 const CXXRecordDecl *Parent = Method->getParent(); 10951 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10952 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10953 NewAttr->setImplicit(true); 10954 return NewAttr; 10955 } 10956 10957 // The Microsoft compiler won't check outer classes for the CodeSeg 10958 // when the #pragma code_seg stack is active. 10959 if (S.CodeSegStack.CurrentValue) 10960 return nullptr; 10961 10962 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10963 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10964 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10965 NewAttr->setImplicit(true); 10966 return NewAttr; 10967 } 10968 } 10969 return nullptr; 10970 } 10971 10972 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10973 /// containing class. Otherwise it will return implicit SectionAttr if the 10974 /// function is a definition and there is an active value on CodeSegStack 10975 /// (from the current #pragma code-seg value). 10976 /// 10977 /// \param FD Function being declared. 10978 /// \param IsDefinition Whether it is a definition or just a declaration. 10979 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10980 /// nullptr if no attribute should be added. 10981 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10982 bool IsDefinition) { 10983 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10984 return A; 10985 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10986 CodeSegStack.CurrentValue) 10987 return SectionAttr::CreateImplicit( 10988 getASTContext(), CodeSegStack.CurrentValue->getString(), 10989 CodeSegStack.CurrentPragmaLocation, SectionAttr::Declspec_allocate); 10990 return nullptr; 10991 } 10992 10993 /// Determines if we can perform a correct type check for \p D as a 10994 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10995 /// best-effort check. 10996 /// 10997 /// \param NewD The new declaration. 10998 /// \param OldD The old declaration. 10999 /// \param NewT The portion of the type of the new declaration to check. 11000 /// \param OldT The portion of the type of the old declaration to check. 11001 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 11002 QualType NewT, QualType OldT) { 11003 if (!NewD->getLexicalDeclContext()->isDependentContext()) 11004 return true; 11005 11006 // For dependently-typed local extern declarations and friends, we can't 11007 // perform a correct type check in general until instantiation: 11008 // 11009 // int f(); 11010 // template<typename T> void g() { T f(); } 11011 // 11012 // (valid if g() is only instantiated with T = int). 11013 if (NewT->isDependentType() && 11014 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 11015 return false; 11016 11017 // Similarly, if the previous declaration was a dependent local extern 11018 // declaration, we don't really know its type yet. 11019 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 11020 return false; 11021 11022 return true; 11023 } 11024 11025 /// Checks if the new declaration declared in dependent context must be 11026 /// put in the same redeclaration chain as the specified declaration. 11027 /// 11028 /// \param D Declaration that is checked. 11029 /// \param PrevDecl Previous declaration found with proper lookup method for the 11030 /// same declaration name. 11031 /// \returns True if D must be added to the redeclaration chain which PrevDecl 11032 /// belongs to. 11033 /// 11034 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 11035 if (!D->getLexicalDeclContext()->isDependentContext()) 11036 return true; 11037 11038 // Don't chain dependent friend function definitions until instantiation, to 11039 // permit cases like 11040 // 11041 // void func(); 11042 // template<typename T> class C1 { friend void func() {} }; 11043 // template<typename T> class C2 { friend void func() {} }; 11044 // 11045 // ... which is valid if only one of C1 and C2 is ever instantiated. 11046 // 11047 // FIXME: This need only apply to function definitions. For now, we proxy 11048 // this by checking for a file-scope function. We do not want this to apply 11049 // to friend declarations nominating member functions, because that gets in 11050 // the way of access checks. 11051 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 11052 return false; 11053 11054 auto *VD = dyn_cast<ValueDecl>(D); 11055 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 11056 return !VD || !PrevVD || 11057 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 11058 PrevVD->getType()); 11059 } 11060 11061 /// Check the target or target_version attribute of the function for 11062 /// MultiVersion validity. 11063 /// 11064 /// Returns true if there was an error, false otherwise. 11065 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 11066 const auto *TA = FD->getAttr<TargetAttr>(); 11067 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11068 assert( 11069 (TA || TVA) && 11070 "MultiVersion candidate requires a target or target_version attribute"); 11071 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 11072 enum ErrType { Feature = 0, Architecture = 1 }; 11073 11074 if (TA) { 11075 ParsedTargetAttr ParseInfo = 11076 S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr()); 11077 if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) { 11078 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11079 << Architecture << ParseInfo.CPU; 11080 return true; 11081 } 11082 for (const auto &Feat : ParseInfo.Features) { 11083 auto BareFeat = StringRef{Feat}.substr(1); 11084 if (Feat[0] == '-') { 11085 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11086 << Feature << ("no-" + BareFeat).str(); 11087 return true; 11088 } 11089 11090 if (!TargetInfo.validateCpuSupports(BareFeat) || 11091 !TargetInfo.isValidFeatureName(BareFeat)) { 11092 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11093 << Feature << BareFeat; 11094 return true; 11095 } 11096 } 11097 } 11098 11099 if (TVA) { 11100 llvm::SmallVector<StringRef, 8> Feats; 11101 TVA->getFeatures(Feats); 11102 for (const auto &Feat : Feats) { 11103 if (!TargetInfo.validateCpuSupports(Feat)) { 11104 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 11105 << Feature << Feat; 11106 return true; 11107 } 11108 } 11109 } 11110 return false; 11111 } 11112 11113 // Provide a white-list of attributes that are allowed to be combined with 11114 // multiversion functions. 11115 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 11116 MultiVersionKind MVKind) { 11117 // Note: this list/diagnosis must match the list in 11118 // checkMultiversionAttributesAllSame. 11119 switch (Kind) { 11120 default: 11121 return false; 11122 case attr::Used: 11123 return MVKind == MultiVersionKind::Target; 11124 case attr::NonNull: 11125 case attr::NoThrow: 11126 return true; 11127 } 11128 } 11129 11130 static bool checkNonMultiVersionCompatAttributes(Sema &S, 11131 const FunctionDecl *FD, 11132 const FunctionDecl *CausedFD, 11133 MultiVersionKind MVKind) { 11134 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 11135 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 11136 << static_cast<unsigned>(MVKind) << A; 11137 if (CausedFD) 11138 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 11139 return true; 11140 }; 11141 11142 for (const Attr *A : FD->attrs()) { 11143 switch (A->getKind()) { 11144 case attr::CPUDispatch: 11145 case attr::CPUSpecific: 11146 if (MVKind != MultiVersionKind::CPUDispatch && 11147 MVKind != MultiVersionKind::CPUSpecific) 11148 return Diagnose(S, A); 11149 break; 11150 case attr::Target: 11151 if (MVKind != MultiVersionKind::Target) 11152 return Diagnose(S, A); 11153 break; 11154 case attr::TargetVersion: 11155 if (MVKind != MultiVersionKind::TargetVersion) 11156 return Diagnose(S, A); 11157 break; 11158 case attr::TargetClones: 11159 if (MVKind != MultiVersionKind::TargetClones) 11160 return Diagnose(S, A); 11161 break; 11162 default: 11163 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 11164 return Diagnose(S, A); 11165 break; 11166 } 11167 } 11168 return false; 11169 } 11170 11171 bool Sema::areMultiversionVariantFunctionsCompatible( 11172 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 11173 const PartialDiagnostic &NoProtoDiagID, 11174 const PartialDiagnosticAt &NoteCausedDiagIDAt, 11175 const PartialDiagnosticAt &NoSupportDiagIDAt, 11176 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 11177 bool ConstexprSupported, bool CLinkageMayDiffer) { 11178 enum DoesntSupport { 11179 FuncTemplates = 0, 11180 VirtFuncs = 1, 11181 DeducedReturn = 2, 11182 Constructors = 3, 11183 Destructors = 4, 11184 DeletedFuncs = 5, 11185 DefaultedFuncs = 6, 11186 ConstexprFuncs = 7, 11187 ConstevalFuncs = 8, 11188 Lambda = 9, 11189 }; 11190 enum Different { 11191 CallingConv = 0, 11192 ReturnType = 1, 11193 ConstexprSpec = 2, 11194 InlineSpec = 3, 11195 Linkage = 4, 11196 LanguageLinkage = 5, 11197 }; 11198 11199 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 11200 !OldFD->getType()->getAs<FunctionProtoType>()) { 11201 Diag(OldFD->getLocation(), NoProtoDiagID); 11202 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 11203 return true; 11204 } 11205 11206 if (NoProtoDiagID.getDiagID() != 0 && 11207 !NewFD->getType()->getAs<FunctionProtoType>()) 11208 return Diag(NewFD->getLocation(), NoProtoDiagID); 11209 11210 if (!TemplatesSupported && 11211 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11212 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11213 << FuncTemplates; 11214 11215 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 11216 if (NewCXXFD->isVirtual()) 11217 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11218 << VirtFuncs; 11219 11220 if (isa<CXXConstructorDecl>(NewCXXFD)) 11221 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11222 << Constructors; 11223 11224 if (isa<CXXDestructorDecl>(NewCXXFD)) 11225 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11226 << Destructors; 11227 } 11228 11229 if (NewFD->isDeleted()) 11230 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11231 << DeletedFuncs; 11232 11233 if (NewFD->isDefaulted()) 11234 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11235 << DefaultedFuncs; 11236 11237 if (!ConstexprSupported && NewFD->isConstexpr()) 11238 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11239 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 11240 11241 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 11242 const auto *NewType = cast<FunctionType>(NewQType); 11243 QualType NewReturnType = NewType->getReturnType(); 11244 11245 if (NewReturnType->isUndeducedType()) 11246 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 11247 << DeducedReturn; 11248 11249 // Ensure the return type is identical. 11250 if (OldFD) { 11251 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 11252 const auto *OldType = cast<FunctionType>(OldQType); 11253 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 11254 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 11255 11256 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 11257 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 11258 11259 QualType OldReturnType = OldType->getReturnType(); 11260 11261 if (OldReturnType != NewReturnType) 11262 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 11263 11264 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 11265 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 11266 11267 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 11268 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 11269 11270 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 11271 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 11272 11273 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 11274 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 11275 11276 if (CheckEquivalentExceptionSpec( 11277 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 11278 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 11279 return true; 11280 } 11281 return false; 11282 } 11283 11284 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 11285 const FunctionDecl *NewFD, 11286 bool CausesMV, 11287 MultiVersionKind MVKind) { 11288 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 11289 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 11290 if (OldFD) 11291 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11292 return true; 11293 } 11294 11295 bool IsCPUSpecificCPUDispatchMVKind = 11296 MVKind == MultiVersionKind::CPUDispatch || 11297 MVKind == MultiVersionKind::CPUSpecific; 11298 11299 if (CausesMV && OldFD && 11300 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 11301 return true; 11302 11303 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 11304 return true; 11305 11306 // Only allow transition to MultiVersion if it hasn't been used. 11307 if (OldFD && CausesMV && OldFD->isUsed(false)) 11308 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11309 11310 return S.areMultiversionVariantFunctionsCompatible( 11311 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 11312 PartialDiagnosticAt(NewFD->getLocation(), 11313 S.PDiag(diag::note_multiversioning_caused_here)), 11314 PartialDiagnosticAt(NewFD->getLocation(), 11315 S.PDiag(diag::err_multiversion_doesnt_support) 11316 << static_cast<unsigned>(MVKind)), 11317 PartialDiagnosticAt(NewFD->getLocation(), 11318 S.PDiag(diag::err_multiversion_diff)), 11319 /*TemplatesSupported=*/false, 11320 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 11321 /*CLinkageMayDiffer=*/false); 11322 } 11323 11324 /// Check the validity of a multiversion function declaration that is the 11325 /// first of its kind. Also sets the multiversion'ness' of the function itself. 11326 /// 11327 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11328 /// 11329 /// Returns true if there was an error, false otherwise. 11330 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) { 11331 MultiVersionKind MVKind = FD->getMultiVersionKind(); 11332 assert(MVKind != MultiVersionKind::None && 11333 "Function lacks multiversion attribute"); 11334 const auto *TA = FD->getAttr<TargetAttr>(); 11335 const auto *TVA = FD->getAttr<TargetVersionAttr>(); 11336 // Target and target_version only causes MV if it is default, otherwise this 11337 // is a normal function. 11338 if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion())) 11339 return false; 11340 11341 if ((TA || TVA) && CheckMultiVersionValue(S, FD)) { 11342 FD->setInvalidDecl(); 11343 return true; 11344 } 11345 11346 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 11347 FD->setInvalidDecl(); 11348 return true; 11349 } 11350 11351 FD->setIsMultiVersion(); 11352 return false; 11353 } 11354 11355 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 11356 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 11357 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 11358 return true; 11359 } 11360 11361 return false; 11362 } 11363 11364 static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, 11365 FunctionDecl *NewFD, 11366 bool &Redeclaration, 11367 NamedDecl *&OldDecl, 11368 LookupResult &Previous) { 11369 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11370 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11371 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 11372 const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>(); 11373 // If the old decl is NOT MultiVersioned yet, and we don't cause that 11374 // to change, this is a simple redeclaration. 11375 if ((NewTA && !NewTA->isDefaultVersion() && 11376 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) || 11377 (NewTVA && !NewTVA->isDefaultVersion() && 11378 (!OldTVA || OldTVA->getName() == NewTVA->getName()))) 11379 return false; 11380 11381 // Otherwise, this decl causes MultiVersioning. 11382 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 11383 NewTVA ? MultiVersionKind::TargetVersion 11384 : MultiVersionKind::Target)) { 11385 NewFD->setInvalidDecl(); 11386 return true; 11387 } 11388 11389 if (CheckMultiVersionValue(S, NewFD)) { 11390 NewFD->setInvalidDecl(); 11391 return true; 11392 } 11393 11394 // If this is 'default', permit the forward declaration. 11395 if (!OldFD->isMultiVersion() && 11396 ((NewTA && NewTA->isDefaultVersion() && !OldTA) || 11397 (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) { 11398 Redeclaration = true; 11399 OldDecl = OldFD; 11400 OldFD->setIsMultiVersion(); 11401 NewFD->setIsMultiVersion(); 11402 return false; 11403 } 11404 11405 if (CheckMultiVersionValue(S, OldFD)) { 11406 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11407 NewFD->setInvalidDecl(); 11408 return true; 11409 } 11410 11411 if (NewTA) { 11412 ParsedTargetAttr OldParsed = 11413 S.getASTContext().getTargetInfo().parseTargetAttr( 11414 OldTA->getFeaturesStr()); 11415 llvm::sort(OldParsed.Features); 11416 ParsedTargetAttr NewParsed = 11417 S.getASTContext().getTargetInfo().parseTargetAttr( 11418 NewTA->getFeaturesStr()); 11419 // Sort order doesn't matter, it just needs to be consistent. 11420 llvm::sort(NewParsed.Features); 11421 if (OldParsed == NewParsed) { 11422 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11423 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11424 NewFD->setInvalidDecl(); 11425 return true; 11426 } 11427 } 11428 11429 if (NewTVA) { 11430 llvm::SmallVector<StringRef, 8> Feats; 11431 OldTVA->getFeatures(Feats); 11432 llvm::sort(Feats); 11433 llvm::SmallVector<StringRef, 8> NewFeats; 11434 NewTVA->getFeatures(NewFeats); 11435 llvm::sort(NewFeats); 11436 11437 if (Feats == NewFeats) { 11438 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11439 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11440 NewFD->setInvalidDecl(); 11441 return true; 11442 } 11443 } 11444 11445 for (const auto *FD : OldFD->redecls()) { 11446 const auto *CurTA = FD->getAttr<TargetAttr>(); 11447 const auto *CurTVA = FD->getAttr<TargetVersionAttr>(); 11448 // We allow forward declarations before ANY multiversioning attributes, but 11449 // nothing after the fact. 11450 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 11451 ((NewTA && (!CurTA || CurTA->isInherited())) || 11452 (NewTVA && (!CurTVA || CurTVA->isInherited())))) { 11453 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 11454 << (NewTA ? 0 : 2); 11455 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 11456 NewFD->setInvalidDecl(); 11457 return true; 11458 } 11459 } 11460 11461 OldFD->setIsMultiVersion(); 11462 NewFD->setIsMultiVersion(); 11463 Redeclaration = false; 11464 OldDecl = nullptr; 11465 Previous.clear(); 11466 return false; 11467 } 11468 11469 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 11470 MultiVersionKind New) { 11471 if (Old == New || Old == MultiVersionKind::None || 11472 New == MultiVersionKind::None) 11473 return true; 11474 11475 return (Old == MultiVersionKind::CPUDispatch && 11476 New == MultiVersionKind::CPUSpecific) || 11477 (Old == MultiVersionKind::CPUSpecific && 11478 New == MultiVersionKind::CPUDispatch); 11479 } 11480 11481 /// Check the validity of a new function declaration being added to an existing 11482 /// multiversioned declaration collection. 11483 static bool CheckMultiVersionAdditionalDecl( 11484 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 11485 MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp, 11486 const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, 11487 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 11488 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11489 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11490 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 11491 // Disallow mixing of multiversioning types. 11492 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 11493 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 11494 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 11495 NewFD->setInvalidDecl(); 11496 return true; 11497 } 11498 11499 ParsedTargetAttr NewParsed; 11500 if (NewTA) { 11501 NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr( 11502 NewTA->getFeaturesStr()); 11503 llvm::sort(NewParsed.Features); 11504 } 11505 llvm::SmallVector<StringRef, 8> NewFeats; 11506 if (NewTVA) { 11507 NewTVA->getFeatures(NewFeats); 11508 llvm::sort(NewFeats); 11509 } 11510 11511 bool UseMemberUsingDeclRules = 11512 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 11513 11514 bool MayNeedOverloadableChecks = 11515 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 11516 11517 // Next, check ALL non-invalid non-overloads to see if this is a redeclaration 11518 // of a previous member of the MultiVersion set. 11519 for (NamedDecl *ND : Previous) { 11520 FunctionDecl *CurFD = ND->getAsFunction(); 11521 if (!CurFD || CurFD->isInvalidDecl()) 11522 continue; 11523 if (MayNeedOverloadableChecks && 11524 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 11525 continue; 11526 11527 if (NewMVKind == MultiVersionKind::None && 11528 OldMVKind == MultiVersionKind::TargetVersion) { 11529 NewFD->addAttr(TargetVersionAttr::CreateImplicit( 11530 S.Context, "default", NewFD->getSourceRange())); 11531 NewFD->setIsMultiVersion(); 11532 NewMVKind = MultiVersionKind::TargetVersion; 11533 if (!NewTVA) { 11534 NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11535 NewTVA->getFeatures(NewFeats); 11536 llvm::sort(NewFeats); 11537 } 11538 } 11539 11540 switch (NewMVKind) { 11541 case MultiVersionKind::None: 11542 assert(OldMVKind == MultiVersionKind::TargetClones && 11543 "Only target_clones can be omitted in subsequent declarations"); 11544 break; 11545 case MultiVersionKind::Target: { 11546 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 11547 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 11548 NewFD->setIsMultiVersion(); 11549 Redeclaration = true; 11550 OldDecl = ND; 11551 return false; 11552 } 11553 11554 ParsedTargetAttr CurParsed = 11555 S.getASTContext().getTargetInfo().parseTargetAttr( 11556 CurTA->getFeaturesStr()); 11557 llvm::sort(CurParsed.Features); 11558 if (CurParsed == NewParsed) { 11559 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11560 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11561 NewFD->setInvalidDecl(); 11562 return true; 11563 } 11564 break; 11565 } 11566 case MultiVersionKind::TargetVersion: { 11567 const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>(); 11568 if (CurTVA->getName() == NewTVA->getName()) { 11569 NewFD->setIsMultiVersion(); 11570 Redeclaration = true; 11571 OldDecl = ND; 11572 return false; 11573 } 11574 llvm::SmallVector<StringRef, 8> CurFeats; 11575 if (CurTVA) { 11576 CurTVA->getFeatures(CurFeats); 11577 llvm::sort(CurFeats); 11578 } 11579 if (CurFeats == NewFeats) { 11580 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 11581 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11582 NewFD->setInvalidDecl(); 11583 return true; 11584 } 11585 break; 11586 } 11587 case MultiVersionKind::TargetClones: { 11588 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 11589 Redeclaration = true; 11590 OldDecl = CurFD; 11591 NewFD->setIsMultiVersion(); 11592 11593 if (CurClones && NewClones && 11594 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 11595 !std::equal(CurClones->featuresStrs_begin(), 11596 CurClones->featuresStrs_end(), 11597 NewClones->featuresStrs_begin()))) { 11598 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 11599 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11600 NewFD->setInvalidDecl(); 11601 return true; 11602 } 11603 11604 return false; 11605 } 11606 case MultiVersionKind::CPUSpecific: 11607 case MultiVersionKind::CPUDispatch: { 11608 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 11609 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 11610 // Handle CPUDispatch/CPUSpecific versions. 11611 // Only 1 CPUDispatch function is allowed, this will make it go through 11612 // the redeclaration errors. 11613 if (NewMVKind == MultiVersionKind::CPUDispatch && 11614 CurFD->hasAttr<CPUDispatchAttr>()) { 11615 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 11616 std::equal( 11617 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 11618 NewCPUDisp->cpus_begin(), 11619 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11620 return Cur->getName() == New->getName(); 11621 })) { 11622 NewFD->setIsMultiVersion(); 11623 Redeclaration = true; 11624 OldDecl = ND; 11625 return false; 11626 } 11627 11628 // If the declarations don't match, this is an error condition. 11629 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 11630 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11631 NewFD->setInvalidDecl(); 11632 return true; 11633 } 11634 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 11635 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 11636 std::equal( 11637 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 11638 NewCPUSpec->cpus_begin(), 11639 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11640 return Cur->getName() == New->getName(); 11641 })) { 11642 NewFD->setIsMultiVersion(); 11643 Redeclaration = true; 11644 OldDecl = ND; 11645 return false; 11646 } 11647 11648 // Only 1 version of CPUSpecific is allowed for each CPU. 11649 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 11650 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11651 if (CurII == NewII) { 11652 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11653 << NewII; 11654 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11655 NewFD->setInvalidDecl(); 11656 return true; 11657 } 11658 } 11659 } 11660 } 11661 break; 11662 } 11663 } 11664 } 11665 11666 // Else, this is simply a non-redecl case. Checking the 'value' is only 11667 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11668 // handled in the attribute adding step. 11669 if ((NewMVKind == MultiVersionKind::TargetVersion || 11670 NewMVKind == MultiVersionKind::Target) && 11671 CheckMultiVersionValue(S, NewFD)) { 11672 NewFD->setInvalidDecl(); 11673 return true; 11674 } 11675 11676 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11677 !OldFD->isMultiVersion(), NewMVKind)) { 11678 NewFD->setInvalidDecl(); 11679 return true; 11680 } 11681 11682 // Permit forward declarations in the case where these two are compatible. 11683 if (!OldFD->isMultiVersion()) { 11684 OldFD->setIsMultiVersion(); 11685 NewFD->setIsMultiVersion(); 11686 Redeclaration = true; 11687 OldDecl = OldFD; 11688 return false; 11689 } 11690 11691 NewFD->setIsMultiVersion(); 11692 Redeclaration = false; 11693 OldDecl = nullptr; 11694 Previous.clear(); 11695 return false; 11696 } 11697 11698 /// Check the validity of a mulitversion function declaration. 11699 /// Also sets the multiversion'ness' of the function itself. 11700 /// 11701 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11702 /// 11703 /// Returns true if there was an error, false otherwise. 11704 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11705 bool &Redeclaration, NamedDecl *&OldDecl, 11706 LookupResult &Previous) { 11707 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11708 const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>(); 11709 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11710 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11711 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11712 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11713 11714 // Main isn't allowed to become a multiversion function, however it IS 11715 // permitted to have 'main' be marked with the 'target' optimization hint, 11716 // for 'target_version' only default is allowed. 11717 if (NewFD->isMain()) { 11718 if (MVKind != MultiVersionKind::None && 11719 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) && 11720 !(MVKind == MultiVersionKind::TargetVersion && 11721 NewTVA->isDefaultVersion())) { 11722 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11723 NewFD->setInvalidDecl(); 11724 return true; 11725 } 11726 return false; 11727 } 11728 11729 // Target attribute on AArch64 is not used for multiversioning 11730 if (NewTA && S.getASTContext().getTargetInfo().getTriple().isAArch64()) 11731 return false; 11732 11733 if (!OldDecl || !OldDecl->getAsFunction() || 11734 OldDecl->getDeclContext()->getRedeclContext() != 11735 NewFD->getDeclContext()->getRedeclContext()) { 11736 // If there's no previous declaration, AND this isn't attempting to cause 11737 // multiversioning, this isn't an error condition. 11738 if (MVKind == MultiVersionKind::None) 11739 return false; 11740 return CheckMultiVersionFirstFunction(S, NewFD); 11741 } 11742 11743 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11744 11745 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) { 11746 if (NewTVA || !OldFD->getAttr<TargetVersionAttr>()) 11747 return false; 11748 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 11749 // Multiversion declaration doesn't have prototype. 11750 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 11751 NewFD->setInvalidDecl(); 11752 } else { 11753 // No "target_version" attribute is equivalent to "default" attribute. 11754 NewFD->addAttr(TargetVersionAttr::CreateImplicit( 11755 S.Context, "default", NewFD->getSourceRange())); 11756 NewFD->setIsMultiVersion(); 11757 OldFD->setIsMultiVersion(); 11758 OldDecl = OldFD; 11759 Redeclaration = true; 11760 } 11761 return true; 11762 } 11763 11764 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11765 // for target_clones and target_version. 11766 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11767 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones && 11768 OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) { 11769 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11770 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11771 NewFD->setInvalidDecl(); 11772 return true; 11773 } 11774 11775 if (!OldFD->isMultiVersion()) { 11776 switch (MVKind) { 11777 case MultiVersionKind::Target: 11778 case MultiVersionKind::TargetVersion: 11779 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration, 11780 OldDecl, Previous); 11781 case MultiVersionKind::TargetClones: 11782 if (OldFD->isUsed(false)) { 11783 NewFD->setInvalidDecl(); 11784 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11785 } 11786 OldFD->setIsMultiVersion(); 11787 break; 11788 11789 case MultiVersionKind::CPUDispatch: 11790 case MultiVersionKind::CPUSpecific: 11791 case MultiVersionKind::None: 11792 break; 11793 } 11794 } 11795 11796 // At this point, we have a multiversion function decl (in OldFD) AND an 11797 // appropriate attribute in the current function decl. Resolve that these are 11798 // still compatible with previous declarations. 11799 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp, 11800 NewCPUSpec, NewClones, Redeclaration, 11801 OldDecl, Previous); 11802 } 11803 11804 static void CheckConstPureAttributesUsage(Sema &S, FunctionDecl *NewFD) { 11805 bool IsPure = NewFD->hasAttr<PureAttr>(); 11806 bool IsConst = NewFD->hasAttr<ConstAttr>(); 11807 11808 // If there are no pure or const attributes, there's nothing to check. 11809 if (!IsPure && !IsConst) 11810 return; 11811 11812 // If the function is marked both pure and const, we retain the const 11813 // attribute because it makes stronger guarantees than the pure attribute, and 11814 // we drop the pure attribute explicitly to prevent later confusion about 11815 // semantics. 11816 if (IsPure && IsConst) { 11817 S.Diag(NewFD->getLocation(), diag::warn_const_attr_with_pure_attr); 11818 NewFD->dropAttrs<PureAttr>(); 11819 } 11820 11821 // Constructors and destructors are functions which return void, so are 11822 // handled here as well. 11823 if (NewFD->getReturnType()->isVoidType()) { 11824 S.Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void) 11825 << IsConst; 11826 NewFD->dropAttrs<PureAttr, ConstAttr>(); 11827 } 11828 } 11829 11830 /// Perform semantic checking of a new function declaration. 11831 /// 11832 /// Performs semantic analysis of the new function declaration 11833 /// NewFD. This routine performs all semantic checking that does not 11834 /// require the actual declarator involved in the declaration, and is 11835 /// used both for the declaration of functions as they are parsed 11836 /// (called via ActOnDeclarator) and for the declaration of functions 11837 /// that have been instantiated via C++ template instantiation (called 11838 /// via InstantiateDecl). 11839 /// 11840 /// \param IsMemberSpecialization whether this new function declaration is 11841 /// a member specialization (that replaces any definition provided by the 11842 /// previous declaration). 11843 /// 11844 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11845 /// 11846 /// \returns true if the function declaration is a redeclaration. 11847 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11848 LookupResult &Previous, 11849 bool IsMemberSpecialization, 11850 bool DeclIsDefn) { 11851 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11852 "Variably modified return types are not handled here"); 11853 11854 // Determine whether the type of this function should be merged with 11855 // a previous visible declaration. This never happens for functions in C++, 11856 // and always happens in C if the previous declaration was visible. 11857 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11858 !Previous.isShadowed(); 11859 11860 bool Redeclaration = false; 11861 NamedDecl *OldDecl = nullptr; 11862 bool MayNeedOverloadableChecks = false; 11863 11864 // Merge or overload the declaration with an existing declaration of 11865 // the same name, if appropriate. 11866 if (!Previous.empty()) { 11867 // Determine whether NewFD is an overload of PrevDecl or 11868 // a declaration that requires merging. If it's an overload, 11869 // there's no more work to do here; we'll just add the new 11870 // function to the scope. 11871 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11872 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11873 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11874 Redeclaration = true; 11875 OldDecl = Candidate; 11876 } 11877 } else { 11878 MayNeedOverloadableChecks = true; 11879 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11880 /*NewIsUsingDecl*/ false)) { 11881 case Ovl_Match: 11882 Redeclaration = true; 11883 break; 11884 11885 case Ovl_NonFunction: 11886 Redeclaration = true; 11887 break; 11888 11889 case Ovl_Overload: 11890 Redeclaration = false; 11891 break; 11892 } 11893 } 11894 } 11895 11896 // Check for a previous extern "C" declaration with this name. 11897 if (!Redeclaration && 11898 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11899 if (!Previous.empty()) { 11900 // This is an extern "C" declaration with the same name as a previous 11901 // declaration, and thus redeclares that entity... 11902 Redeclaration = true; 11903 OldDecl = Previous.getFoundDecl(); 11904 MergeTypeWithPrevious = false; 11905 11906 // ... except in the presence of __attribute__((overloadable)). 11907 if (OldDecl->hasAttr<OverloadableAttr>() || 11908 NewFD->hasAttr<OverloadableAttr>()) { 11909 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11910 MayNeedOverloadableChecks = true; 11911 Redeclaration = false; 11912 OldDecl = nullptr; 11913 } 11914 } 11915 } 11916 } 11917 11918 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11919 return Redeclaration; 11920 11921 // PPC MMA non-pointer types are not allowed as function return types. 11922 if (Context.getTargetInfo().getTriple().isPPC64() && 11923 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11924 NewFD->setInvalidDecl(); 11925 } 11926 11927 CheckConstPureAttributesUsage(*this, NewFD); 11928 11929 // C++11 [dcl.constexpr]p8: 11930 // A constexpr specifier for a non-static member function that is not 11931 // a constructor declares that member function to be const. 11932 // 11933 // This needs to be delayed until we know whether this is an out-of-line 11934 // definition of a static member function. 11935 // 11936 // This rule is not present in C++1y, so we produce a backwards 11937 // compatibility warning whenever it happens in C++11. 11938 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11939 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11940 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11941 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11942 CXXMethodDecl *OldMD = nullptr; 11943 if (OldDecl) 11944 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11945 if (!OldMD || !OldMD->isStatic()) { 11946 const FunctionProtoType *FPT = 11947 MD->getType()->castAs<FunctionProtoType>(); 11948 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11949 EPI.TypeQuals.addConst(); 11950 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11951 FPT->getParamTypes(), EPI)); 11952 11953 // Warn that we did this, if we're not performing template instantiation. 11954 // In that case, we'll have warned already when the template was defined. 11955 if (!inTemplateInstantiation()) { 11956 SourceLocation AddConstLoc; 11957 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11958 .IgnoreParens().getAs<FunctionTypeLoc>()) 11959 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11960 11961 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11962 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11963 } 11964 } 11965 } 11966 11967 if (Redeclaration) { 11968 // NewFD and OldDecl represent declarations that need to be 11969 // merged. 11970 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11971 DeclIsDefn)) { 11972 NewFD->setInvalidDecl(); 11973 return Redeclaration; 11974 } 11975 11976 Previous.clear(); 11977 Previous.addDecl(OldDecl); 11978 11979 if (FunctionTemplateDecl *OldTemplateDecl = 11980 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11981 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11982 FunctionTemplateDecl *NewTemplateDecl 11983 = NewFD->getDescribedFunctionTemplate(); 11984 assert(NewTemplateDecl && "Template/non-template mismatch"); 11985 11986 // The call to MergeFunctionDecl above may have created some state in 11987 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11988 // can add it as a redeclaration. 11989 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11990 11991 NewFD->setPreviousDeclaration(OldFD); 11992 if (NewFD->isCXXClassMember()) { 11993 NewFD->setAccess(OldTemplateDecl->getAccess()); 11994 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11995 } 11996 11997 // If this is an explicit specialization of a member that is a function 11998 // template, mark it as a member specialization. 11999 if (IsMemberSpecialization && 12000 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 12001 NewTemplateDecl->setMemberSpecialization(); 12002 assert(OldTemplateDecl->isMemberSpecialization()); 12003 // Explicit specializations of a member template do not inherit deleted 12004 // status from the parent member template that they are specializing. 12005 if (OldFD->isDeleted()) { 12006 // FIXME: This assert will not hold in the presence of modules. 12007 assert(OldFD->getCanonicalDecl() == OldFD); 12008 // FIXME: We need an update record for this AST mutation. 12009 OldFD->setDeletedAsWritten(false); 12010 } 12011 } 12012 12013 } else { 12014 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 12015 auto *OldFD = cast<FunctionDecl>(OldDecl); 12016 // This needs to happen first so that 'inline' propagates. 12017 NewFD->setPreviousDeclaration(OldFD); 12018 if (NewFD->isCXXClassMember()) 12019 NewFD->setAccess(OldFD->getAccess()); 12020 } 12021 } 12022 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 12023 !NewFD->getAttr<OverloadableAttr>()) { 12024 assert((Previous.empty() || 12025 llvm::any_of(Previous, 12026 [](const NamedDecl *ND) { 12027 return ND->hasAttr<OverloadableAttr>(); 12028 })) && 12029 "Non-redecls shouldn't happen without overloadable present"); 12030 12031 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 12032 const auto *FD = dyn_cast<FunctionDecl>(ND); 12033 return FD && !FD->hasAttr<OverloadableAttr>(); 12034 }); 12035 12036 if (OtherUnmarkedIter != Previous.end()) { 12037 Diag(NewFD->getLocation(), 12038 diag::err_attribute_overloadable_multiple_unmarked_overloads); 12039 Diag((*OtherUnmarkedIter)->getLocation(), 12040 diag::note_attribute_overloadable_prev_overload) 12041 << false; 12042 12043 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 12044 } 12045 } 12046 12047 if (LangOpts.OpenMP) 12048 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 12049 12050 // Semantic checking for this function declaration (in isolation). 12051 12052 if (getLangOpts().CPlusPlus) { 12053 // C++-specific checks. 12054 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 12055 CheckConstructor(Constructor); 12056 } else if (CXXDestructorDecl *Destructor = 12057 dyn_cast<CXXDestructorDecl>(NewFD)) { 12058 // We check here for invalid destructor names. 12059 // If we have a friend destructor declaration that is dependent, we can't 12060 // diagnose right away because cases like this are still valid: 12061 // template <class T> struct A { friend T::X::~Y(); }; 12062 // struct B { struct Y { ~Y(); }; using X = Y; }; 12063 // template struct A<B>; 12064 if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None || 12065 !Destructor->getFunctionObjectParameterType()->isDependentType()) { 12066 CXXRecordDecl *Record = Destructor->getParent(); 12067 QualType ClassType = Context.getTypeDeclType(Record); 12068 12069 DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( 12070 Context.getCanonicalType(ClassType)); 12071 if (NewFD->getDeclName() != Name) { 12072 Diag(NewFD->getLocation(), diag::err_destructor_name); 12073 NewFD->setInvalidDecl(); 12074 return Redeclaration; 12075 } 12076 } 12077 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 12078 if (auto *TD = Guide->getDescribedFunctionTemplate()) 12079 CheckDeductionGuideTemplate(TD); 12080 12081 // A deduction guide is not on the list of entities that can be 12082 // explicitly specialized. 12083 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 12084 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 12085 << /*explicit specialization*/ 1; 12086 } 12087 12088 // Find any virtual functions that this function overrides. 12089 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 12090 if (!Method->isFunctionTemplateSpecialization() && 12091 !Method->getDescribedFunctionTemplate() && 12092 Method->isCanonicalDecl()) { 12093 AddOverriddenMethods(Method->getParent(), Method); 12094 } 12095 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 12096 // C++2a [class.virtual]p6 12097 // A virtual method shall not have a requires-clause. 12098 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 12099 diag::err_constrained_virtual_method); 12100 12101 if (Method->isStatic()) 12102 checkThisInStaticMemberFunctionType(Method); 12103 } 12104 12105 if (Expr *TRC = NewFD->getTrailingRequiresClause()) { 12106 // C++20: dcl.decl.general p4: 12107 // The optional requires-clause ([temp.pre]) in an init-declarator or 12108 // member-declarator shall be present only if the declarator declares a 12109 // templated function ([dcl.fct]). 12110 // 12111 // [temp.pre]/8: 12112 // An entity is templated if it is 12113 // - a template, 12114 // - an entity defined ([basic.def]) or created ([class.temporary]) in a 12115 // templated entity, 12116 // - a member of a templated entity, 12117 // - an enumerator for an enumeration that is a templated entity, or 12118 // - the closure type of a lambda-expression ([expr.prim.lambda.closure]) 12119 // appearing in the declaration of a templated entity. [Note 6: A local 12120 // class, a local or block variable, or a friend function defined in a 12121 // templated entity is a templated entity. — end note] 12122 // 12123 // A templated function is a function template or a function that is 12124 // templated. A templated class is a class template or a class that is 12125 // templated. A templated variable is a variable template or a variable 12126 // that is templated. 12127 12128 bool IsTemplate = NewFD->getDescribedFunctionTemplate(); 12129 bool IsFriend = NewFD->getFriendObjectKind(); 12130 if (!IsTemplate && // -a template 12131 // defined... in a templated entity 12132 !(DeclIsDefn && NewFD->isTemplated()) && 12133 // a member of a templated entity 12134 !(isa<CXXMethodDecl>(NewFD) && NewFD->isTemplated()) && 12135 // Don't complain about instantiations, they've already had these 12136 // rules + others enforced. 12137 !NewFD->isTemplateInstantiation() && 12138 // If the function violates [temp.friend]p9 because it is missing 12139 // a definition, and adding a definition would make it templated, 12140 // then let that error take precedence. 12141 !(!DeclIsDefn && IsFriend && NewFD->isTemplated())) { 12142 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); 12143 } else if (!DeclIsDefn && !IsTemplate && IsFriend && 12144 !NewFD->isTemplateInstantiation()) { 12145 // C++ [temp.friend]p9: 12146 // A non-template friend declaration with a requires-clause shall be a 12147 // definition. 12148 Diag(NewFD->getBeginLoc(), 12149 diag::err_non_temp_friend_decl_with_requires_clause_must_be_def); 12150 NewFD->setInvalidDecl(); 12151 } 12152 } 12153 12154 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 12155 ActOnConversionDeclarator(Conversion); 12156 12157 // Extra checking for C++ overloaded operators (C++ [over.oper]). 12158 if (NewFD->isOverloadedOperator() && 12159 CheckOverloadedOperatorDeclaration(NewFD)) { 12160 NewFD->setInvalidDecl(); 12161 return Redeclaration; 12162 } 12163 12164 // Extra checking for C++0x literal operators (C++0x [over.literal]). 12165 if (NewFD->getLiteralIdentifier() && 12166 CheckLiteralOperatorDeclaration(NewFD)) { 12167 NewFD->setInvalidDecl(); 12168 return Redeclaration; 12169 } 12170 12171 // In C++, check default arguments now that we have merged decls. Unless 12172 // the lexical context is the class, because in this case this is done 12173 // during delayed parsing anyway. 12174 if (!CurContext->isRecord()) 12175 CheckCXXDefaultArguments(NewFD); 12176 12177 // If this function is declared as being extern "C", then check to see if 12178 // the function returns a UDT (class, struct, or union type) that is not C 12179 // compatible, and if it does, warn the user. 12180 // But, issue any diagnostic on the first declaration only. 12181 if (Previous.empty() && NewFD->isExternC()) { 12182 QualType R = NewFD->getReturnType(); 12183 if (R->isIncompleteType() && !R->isVoidType()) 12184 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 12185 << NewFD << R; 12186 else if (!R.isPODType(Context) && !R->isVoidType() && 12187 !R->isObjCObjectPointerType()) 12188 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 12189 } 12190 12191 // C++1z [dcl.fct]p6: 12192 // [...] whether the function has a non-throwing exception-specification 12193 // [is] part of the function type 12194 // 12195 // This results in an ABI break between C++14 and C++17 for functions whose 12196 // declared type includes an exception-specification in a parameter or 12197 // return type. (Exception specifications on the function itself are OK in 12198 // most cases, and exception specifications are not permitted in most other 12199 // contexts where they could make it into a mangling.) 12200 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 12201 auto HasNoexcept = [&](QualType T) -> bool { 12202 // Strip off declarator chunks that could be between us and a function 12203 // type. We don't need to look far, exception specifications are very 12204 // restricted prior to C++17. 12205 if (auto *RT = T->getAs<ReferenceType>()) 12206 T = RT->getPointeeType(); 12207 else if (T->isAnyPointerType()) 12208 T = T->getPointeeType(); 12209 else if (auto *MPT = T->getAs<MemberPointerType>()) 12210 T = MPT->getPointeeType(); 12211 if (auto *FPT = T->getAs<FunctionProtoType>()) 12212 if (FPT->isNothrow()) 12213 return true; 12214 return false; 12215 }; 12216 12217 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 12218 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 12219 for (QualType T : FPT->param_types()) 12220 AnyNoexcept |= HasNoexcept(T); 12221 if (AnyNoexcept) 12222 Diag(NewFD->getLocation(), 12223 diag::warn_cxx17_compat_exception_spec_in_signature) 12224 << NewFD; 12225 } 12226 12227 if (!Redeclaration && LangOpts.CUDA) 12228 checkCUDATargetOverload(NewFD, Previous); 12229 } 12230 12231 // Check if the function definition uses any AArch64 SME features without 12232 // having the '+sme' feature enabled. 12233 if (DeclIsDefn) { 12234 const auto *Attr = NewFD->getAttr<ArmNewAttr>(); 12235 bool UsesSM = NewFD->hasAttr<ArmLocallyStreamingAttr>(); 12236 bool UsesZA = Attr && Attr->isNewZA(); 12237 bool UsesZT0 = Attr && Attr->isNewZT0(); 12238 if (const auto *FPT = NewFD->getType()->getAs<FunctionProtoType>()) { 12239 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12240 UsesSM |= 12241 EPI.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask; 12242 UsesZA |= FunctionType::getArmZAState(EPI.AArch64SMEAttributes) != 12243 FunctionType::ARM_None; 12244 UsesZT0 |= FunctionType::getArmZT0State(EPI.AArch64SMEAttributes) != 12245 FunctionType::ARM_None; 12246 } 12247 12248 if (UsesSM || UsesZA) { 12249 llvm::StringMap<bool> FeatureMap; 12250 Context.getFunctionFeatureMap(FeatureMap, NewFD); 12251 if (!FeatureMap.contains("sme")) { 12252 if (UsesSM) 12253 Diag(NewFD->getLocation(), 12254 diag::err_sme_definition_using_sm_in_non_sme_target); 12255 else 12256 Diag(NewFD->getLocation(), 12257 diag::err_sme_definition_using_za_in_non_sme_target); 12258 } 12259 } 12260 if (UsesZT0) { 12261 llvm::StringMap<bool> FeatureMap; 12262 Context.getFunctionFeatureMap(FeatureMap, NewFD); 12263 if (!FeatureMap.contains("sme2")) { 12264 Diag(NewFD->getLocation(), 12265 diag::err_sme_definition_using_zt0_in_non_sme2_target); 12266 } 12267 } 12268 } 12269 12270 return Redeclaration; 12271 } 12272 12273 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 12274 // C++11 [basic.start.main]p3: 12275 // A program that [...] declares main to be inline, static or 12276 // constexpr is ill-formed. 12277 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 12278 // appear in a declaration of main. 12279 // static main is not an error under C99, but we should warn about it. 12280 // We accept _Noreturn main as an extension. 12281 if (FD->getStorageClass() == SC_Static) 12282 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 12283 ? diag::err_static_main : diag::warn_static_main) 12284 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12285 if (FD->isInlineSpecified()) 12286 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 12287 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 12288 if (DS.isNoreturnSpecified()) { 12289 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 12290 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 12291 Diag(NoreturnLoc, diag::ext_noreturn_main); 12292 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 12293 << FixItHint::CreateRemoval(NoreturnRange); 12294 } 12295 if (FD->isConstexpr()) { 12296 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 12297 << FD->isConsteval() 12298 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 12299 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 12300 } 12301 12302 if (getLangOpts().OpenCL) { 12303 Diag(FD->getLocation(), diag::err_opencl_no_main) 12304 << FD->hasAttr<OpenCLKernelAttr>(); 12305 FD->setInvalidDecl(); 12306 return; 12307 } 12308 12309 // Functions named main in hlsl are default entries, but don't have specific 12310 // signatures they are required to conform to. 12311 if (getLangOpts().HLSL) 12312 return; 12313 12314 QualType T = FD->getType(); 12315 assert(T->isFunctionType() && "function decl is not of function type"); 12316 const FunctionType* FT = T->castAs<FunctionType>(); 12317 12318 // Set default calling convention for main() 12319 if (FT->getCallConv() != CC_C) { 12320 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 12321 FD->setType(QualType(FT, 0)); 12322 T = Context.getCanonicalType(FD->getType()); 12323 } 12324 12325 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 12326 // In C with GNU extensions we allow main() to have non-integer return 12327 // type, but we should warn about the extension, and we disable the 12328 // implicit-return-zero rule. 12329 12330 // GCC in C mode accepts qualified 'int'. 12331 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 12332 FD->setHasImplicitReturnZero(true); 12333 else { 12334 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 12335 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12336 if (RTRange.isValid()) 12337 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 12338 << FixItHint::CreateReplacement(RTRange, "int"); 12339 } 12340 } else { 12341 // In C and C++, main magically returns 0 if you fall off the end; 12342 // set the flag which tells us that. 12343 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 12344 12345 // All the standards say that main() should return 'int'. 12346 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 12347 FD->setHasImplicitReturnZero(true); 12348 else { 12349 // Otherwise, this is just a flat-out error. 12350 SourceRange RTRange = FD->getReturnTypeSourceRange(); 12351 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 12352 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 12353 : FixItHint()); 12354 FD->setInvalidDecl(true); 12355 } 12356 } 12357 12358 // Treat protoless main() as nullary. 12359 if (isa<FunctionNoProtoType>(FT)) return; 12360 12361 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 12362 unsigned nparams = FTP->getNumParams(); 12363 assert(FD->getNumParams() == nparams); 12364 12365 bool HasExtraParameters = (nparams > 3); 12366 12367 if (FTP->isVariadic()) { 12368 Diag(FD->getLocation(), diag::ext_variadic_main); 12369 // FIXME: if we had information about the location of the ellipsis, we 12370 // could add a FixIt hint to remove it as a parameter. 12371 } 12372 12373 // Darwin passes an undocumented fourth argument of type char**. If 12374 // other platforms start sprouting these, the logic below will start 12375 // getting shifty. 12376 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 12377 HasExtraParameters = false; 12378 12379 if (HasExtraParameters) { 12380 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 12381 FD->setInvalidDecl(true); 12382 nparams = 3; 12383 } 12384 12385 // FIXME: a lot of the following diagnostics would be improved 12386 // if we had some location information about types. 12387 12388 QualType CharPP = 12389 Context.getPointerType(Context.getPointerType(Context.CharTy)); 12390 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 12391 12392 for (unsigned i = 0; i < nparams; ++i) { 12393 QualType AT = FTP->getParamType(i); 12394 12395 bool mismatch = true; 12396 12397 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 12398 mismatch = false; 12399 else if (Expected[i] == CharPP) { 12400 // As an extension, the following forms are okay: 12401 // char const ** 12402 // char const * const * 12403 // char * const * 12404 12405 QualifierCollector qs; 12406 const PointerType* PT; 12407 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 12408 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 12409 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 12410 Context.CharTy)) { 12411 qs.removeConst(); 12412 mismatch = !qs.empty(); 12413 } 12414 } 12415 12416 if (mismatch) { 12417 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 12418 // TODO: suggest replacing given type with expected type 12419 FD->setInvalidDecl(true); 12420 } 12421 } 12422 12423 if (nparams == 1 && !FD->isInvalidDecl()) { 12424 Diag(FD->getLocation(), diag::warn_main_one_arg); 12425 } 12426 12427 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12428 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12429 FD->setInvalidDecl(); 12430 } 12431 } 12432 12433 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 12434 12435 // Default calling convention for main and wmain is __cdecl 12436 if (FD->getName() == "main" || FD->getName() == "wmain") 12437 return false; 12438 12439 // Default calling convention for MinGW is __cdecl 12440 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 12441 if (T.isWindowsGNUEnvironment()) 12442 return false; 12443 12444 // Default calling convention for WinMain, wWinMain and DllMain 12445 // is __stdcall on 32 bit Windows 12446 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 12447 return true; 12448 12449 return false; 12450 } 12451 12452 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 12453 QualType T = FD->getType(); 12454 assert(T->isFunctionType() && "function decl is not of function type"); 12455 const FunctionType *FT = T->castAs<FunctionType>(); 12456 12457 // Set an implicit return of 'zero' if the function can return some integral, 12458 // enumeration, pointer or nullptr type. 12459 if (FT->getReturnType()->isIntegralOrEnumerationType() || 12460 FT->getReturnType()->isAnyPointerType() || 12461 FT->getReturnType()->isNullPtrType()) 12462 // DllMain is exempt because a return value of zero means it failed. 12463 if (FD->getName() != "DllMain") 12464 FD->setHasImplicitReturnZero(true); 12465 12466 // Explicity specified calling conventions are applied to MSVC entry points 12467 if (!hasExplicitCallingConv(T)) { 12468 if (isDefaultStdCall(FD, *this)) { 12469 if (FT->getCallConv() != CC_X86StdCall) { 12470 FT = Context.adjustFunctionType( 12471 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 12472 FD->setType(QualType(FT, 0)); 12473 } 12474 } else if (FT->getCallConv() != CC_C) { 12475 FT = Context.adjustFunctionType(FT, 12476 FT->getExtInfo().withCallingConv(CC_C)); 12477 FD->setType(QualType(FT, 0)); 12478 } 12479 } 12480 12481 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 12482 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 12483 FD->setInvalidDecl(); 12484 } 12485 } 12486 12487 void Sema::ActOnHLSLTopLevelFunction(FunctionDecl *FD) { 12488 auto &TargetInfo = getASTContext().getTargetInfo(); 12489 12490 if (FD->getName() != TargetInfo.getTargetOpts().HLSLEntry) 12491 return; 12492 12493 StringRef Env = TargetInfo.getTriple().getEnvironmentName(); 12494 HLSLShaderAttr::ShaderType ShaderType; 12495 if (HLSLShaderAttr::ConvertStrToShaderType(Env, ShaderType)) { 12496 if (const auto *Shader = FD->getAttr<HLSLShaderAttr>()) { 12497 // The entry point is already annotated - check that it matches the 12498 // triple. 12499 if (Shader->getType() != ShaderType) { 12500 Diag(Shader->getLocation(), diag::err_hlsl_entry_shader_attr_mismatch) 12501 << Shader; 12502 FD->setInvalidDecl(); 12503 } 12504 } else { 12505 // Implicitly add the shader attribute if the entry function isn't 12506 // explicitly annotated. 12507 FD->addAttr(HLSLShaderAttr::CreateImplicit(Context, ShaderType, 12508 FD->getBeginLoc())); 12509 } 12510 } else { 12511 switch (TargetInfo.getTriple().getEnvironment()) { 12512 case llvm::Triple::UnknownEnvironment: 12513 case llvm::Triple::Library: 12514 break; 12515 default: 12516 llvm_unreachable("Unhandled environment in triple"); 12517 } 12518 } 12519 } 12520 12521 void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) { 12522 const auto *ShaderAttr = FD->getAttr<HLSLShaderAttr>(); 12523 assert(ShaderAttr && "Entry point has no shader attribute"); 12524 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType(); 12525 12526 switch (ST) { 12527 case HLSLShaderAttr::Pixel: 12528 case HLSLShaderAttr::Vertex: 12529 case HLSLShaderAttr::Geometry: 12530 case HLSLShaderAttr::Hull: 12531 case HLSLShaderAttr::Domain: 12532 case HLSLShaderAttr::RayGeneration: 12533 case HLSLShaderAttr::Intersection: 12534 case HLSLShaderAttr::AnyHit: 12535 case HLSLShaderAttr::ClosestHit: 12536 case HLSLShaderAttr::Miss: 12537 case HLSLShaderAttr::Callable: 12538 if (const auto *NT = FD->getAttr<HLSLNumThreadsAttr>()) { 12539 DiagnoseHLSLAttrStageMismatch(NT, ST, 12540 {HLSLShaderAttr::Compute, 12541 HLSLShaderAttr::Amplification, 12542 HLSLShaderAttr::Mesh}); 12543 FD->setInvalidDecl(); 12544 } 12545 break; 12546 12547 case HLSLShaderAttr::Compute: 12548 case HLSLShaderAttr::Amplification: 12549 case HLSLShaderAttr::Mesh: 12550 if (!FD->hasAttr<HLSLNumThreadsAttr>()) { 12551 Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads) 12552 << HLSLShaderAttr::ConvertShaderTypeToStr(ST); 12553 FD->setInvalidDecl(); 12554 } 12555 break; 12556 } 12557 12558 for (ParmVarDecl *Param : FD->parameters()) { 12559 if (const auto *AnnotationAttr = Param->getAttr<HLSLAnnotationAttr>()) { 12560 CheckHLSLSemanticAnnotation(FD, Param, AnnotationAttr); 12561 } else { 12562 // FIXME: Handle struct parameters where annotations are on struct fields. 12563 // See: https://github.com/llvm/llvm-project/issues/57875 12564 Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation); 12565 Diag(Param->getLocation(), diag::note_previous_decl) << Param; 12566 FD->setInvalidDecl(); 12567 } 12568 } 12569 // FIXME: Verify return type semantic annotation. 12570 } 12571 12572 void Sema::CheckHLSLSemanticAnnotation( 12573 FunctionDecl *EntryPoint, const Decl *Param, 12574 const HLSLAnnotationAttr *AnnotationAttr) { 12575 auto *ShaderAttr = EntryPoint->getAttr<HLSLShaderAttr>(); 12576 assert(ShaderAttr && "Entry point has no shader attribute"); 12577 HLSLShaderAttr::ShaderType ST = ShaderAttr->getType(); 12578 12579 switch (AnnotationAttr->getKind()) { 12580 case attr::HLSLSV_DispatchThreadID: 12581 case attr::HLSLSV_GroupIndex: 12582 if (ST == HLSLShaderAttr::Compute) 12583 return; 12584 DiagnoseHLSLAttrStageMismatch(AnnotationAttr, ST, 12585 {HLSLShaderAttr::Compute}); 12586 break; 12587 default: 12588 llvm_unreachable("Unknown HLSLAnnotationAttr"); 12589 } 12590 } 12591 12592 void Sema::DiagnoseHLSLAttrStageMismatch( 12593 const Attr *A, HLSLShaderAttr::ShaderType Stage, 12594 std::initializer_list<HLSLShaderAttr::ShaderType> AllowedStages) { 12595 SmallVector<StringRef, 8> StageStrings; 12596 llvm::transform(AllowedStages, std::back_inserter(StageStrings), 12597 [](HLSLShaderAttr::ShaderType ST) { 12598 return StringRef( 12599 HLSLShaderAttr::ConvertShaderTypeToStr(ST)); 12600 }); 12601 Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage) 12602 << A << HLSLShaderAttr::ConvertShaderTypeToStr(Stage) 12603 << (AllowedStages.size() != 1) << join(StageStrings, ", "); 12604 } 12605 12606 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 12607 // FIXME: Need strict checking. In C89, we need to check for 12608 // any assignment, increment, decrement, function-calls, or 12609 // commas outside of a sizeof. In C99, it's the same list, 12610 // except that the aforementioned are allowed in unevaluated 12611 // expressions. Everything else falls under the 12612 // "may accept other forms of constant expressions" exception. 12613 // 12614 // Regular C++ code will not end up here (exceptions: language extensions, 12615 // OpenCL C++ etc), so the constant expression rules there don't matter. 12616 if (Init->isValueDependent()) { 12617 assert(Init->containsErrors() && 12618 "Dependent code should only occur in error-recovery path."); 12619 return true; 12620 } 12621 const Expr *Culprit; 12622 if (Init->isConstantInitializer(Context, false, &Culprit)) 12623 return false; 12624 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 12625 << Culprit->getSourceRange(); 12626 return true; 12627 } 12628 12629 namespace { 12630 // Visits an initialization expression to see if OrigDecl is evaluated in 12631 // its own initialization and throws a warning if it does. 12632 class SelfReferenceChecker 12633 : public EvaluatedExprVisitor<SelfReferenceChecker> { 12634 Sema &S; 12635 Decl *OrigDecl; 12636 bool isRecordType; 12637 bool isPODType; 12638 bool isReferenceType; 12639 12640 bool isInitList; 12641 llvm::SmallVector<unsigned, 4> InitFieldIndex; 12642 12643 public: 12644 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 12645 12646 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 12647 S(S), OrigDecl(OrigDecl) { 12648 isPODType = false; 12649 isRecordType = false; 12650 isReferenceType = false; 12651 isInitList = false; 12652 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 12653 isPODType = VD->getType().isPODType(S.Context); 12654 isRecordType = VD->getType()->isRecordType(); 12655 isReferenceType = VD->getType()->isReferenceType(); 12656 } 12657 } 12658 12659 // For most expressions, just call the visitor. For initializer lists, 12660 // track the index of the field being initialized since fields are 12661 // initialized in order allowing use of previously initialized fields. 12662 void CheckExpr(Expr *E) { 12663 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 12664 if (!InitList) { 12665 Visit(E); 12666 return; 12667 } 12668 12669 // Track and increment the index here. 12670 isInitList = true; 12671 InitFieldIndex.push_back(0); 12672 for (auto *Child : InitList->children()) { 12673 CheckExpr(cast<Expr>(Child)); 12674 ++InitFieldIndex.back(); 12675 } 12676 InitFieldIndex.pop_back(); 12677 } 12678 12679 // Returns true if MemberExpr is checked and no further checking is needed. 12680 // Returns false if additional checking is required. 12681 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 12682 llvm::SmallVector<FieldDecl*, 4> Fields; 12683 Expr *Base = E; 12684 bool ReferenceField = false; 12685 12686 // Get the field members used. 12687 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12688 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 12689 if (!FD) 12690 return false; 12691 Fields.push_back(FD); 12692 if (FD->getType()->isReferenceType()) 12693 ReferenceField = true; 12694 Base = ME->getBase()->IgnoreParenImpCasts(); 12695 } 12696 12697 // Keep checking only if the base Decl is the same. 12698 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 12699 if (!DRE || DRE->getDecl() != OrigDecl) 12700 return false; 12701 12702 // A reference field can be bound to an unininitialized field. 12703 if (CheckReference && !ReferenceField) 12704 return true; 12705 12706 // Convert FieldDecls to their index number. 12707 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 12708 for (const FieldDecl *I : llvm::reverse(Fields)) 12709 UsedFieldIndex.push_back(I->getFieldIndex()); 12710 12711 // See if a warning is needed by checking the first difference in index 12712 // numbers. If field being used has index less than the field being 12713 // initialized, then the use is safe. 12714 for (auto UsedIter = UsedFieldIndex.begin(), 12715 UsedEnd = UsedFieldIndex.end(), 12716 OrigIter = InitFieldIndex.begin(), 12717 OrigEnd = InitFieldIndex.end(); 12718 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 12719 if (*UsedIter < *OrigIter) 12720 return true; 12721 if (*UsedIter > *OrigIter) 12722 break; 12723 } 12724 12725 // TODO: Add a different warning which will print the field names. 12726 HandleDeclRefExpr(DRE); 12727 return true; 12728 } 12729 12730 // For most expressions, the cast is directly above the DeclRefExpr. 12731 // For conditional operators, the cast can be outside the conditional 12732 // operator if both expressions are DeclRefExpr's. 12733 void HandleValue(Expr *E) { 12734 E = E->IgnoreParens(); 12735 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 12736 HandleDeclRefExpr(DRE); 12737 return; 12738 } 12739 12740 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 12741 Visit(CO->getCond()); 12742 HandleValue(CO->getTrueExpr()); 12743 HandleValue(CO->getFalseExpr()); 12744 return; 12745 } 12746 12747 if (BinaryConditionalOperator *BCO = 12748 dyn_cast<BinaryConditionalOperator>(E)) { 12749 Visit(BCO->getCond()); 12750 HandleValue(BCO->getFalseExpr()); 12751 return; 12752 } 12753 12754 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 12755 if (Expr *SE = OVE->getSourceExpr()) 12756 HandleValue(SE); 12757 return; 12758 } 12759 12760 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12761 if (BO->getOpcode() == BO_Comma) { 12762 Visit(BO->getLHS()); 12763 HandleValue(BO->getRHS()); 12764 return; 12765 } 12766 } 12767 12768 if (isa<MemberExpr>(E)) { 12769 if (isInitList) { 12770 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 12771 false /*CheckReference*/)) 12772 return; 12773 } 12774 12775 Expr *Base = E->IgnoreParenImpCasts(); 12776 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12777 // Check for static member variables and don't warn on them. 12778 if (!isa<FieldDecl>(ME->getMemberDecl())) 12779 return; 12780 Base = ME->getBase()->IgnoreParenImpCasts(); 12781 } 12782 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 12783 HandleDeclRefExpr(DRE); 12784 return; 12785 } 12786 12787 Visit(E); 12788 } 12789 12790 // Reference types not handled in HandleValue are handled here since all 12791 // uses of references are bad, not just r-value uses. 12792 void VisitDeclRefExpr(DeclRefExpr *E) { 12793 if (isReferenceType) 12794 HandleDeclRefExpr(E); 12795 } 12796 12797 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12798 if (E->getCastKind() == CK_LValueToRValue) { 12799 HandleValue(E->getSubExpr()); 12800 return; 12801 } 12802 12803 Inherited::VisitImplicitCastExpr(E); 12804 } 12805 12806 void VisitMemberExpr(MemberExpr *E) { 12807 if (isInitList) { 12808 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 12809 return; 12810 } 12811 12812 // Don't warn on arrays since they can be treated as pointers. 12813 if (E->getType()->canDecayToPointerType()) return; 12814 12815 // Warn when a non-static method call is followed by non-static member 12816 // field accesses, which is followed by a DeclRefExpr. 12817 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 12818 bool Warn = (MD && !MD->isStatic()); 12819 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 12820 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 12821 if (!isa<FieldDecl>(ME->getMemberDecl())) 12822 Warn = false; 12823 Base = ME->getBase()->IgnoreParenImpCasts(); 12824 } 12825 12826 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 12827 if (Warn) 12828 HandleDeclRefExpr(DRE); 12829 return; 12830 } 12831 12832 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 12833 // Visit that expression. 12834 Visit(Base); 12835 } 12836 12837 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 12838 Expr *Callee = E->getCallee(); 12839 12840 if (isa<UnresolvedLookupExpr>(Callee)) 12841 return Inherited::VisitCXXOperatorCallExpr(E); 12842 12843 Visit(Callee); 12844 for (auto Arg: E->arguments()) 12845 HandleValue(Arg->IgnoreParenImpCasts()); 12846 } 12847 12848 void VisitUnaryOperator(UnaryOperator *E) { 12849 // For POD record types, addresses of its own members are well-defined. 12850 if (E->getOpcode() == UO_AddrOf && isRecordType && 12851 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 12852 if (!isPODType) 12853 HandleValue(E->getSubExpr()); 12854 return; 12855 } 12856 12857 if (E->isIncrementDecrementOp()) { 12858 HandleValue(E->getSubExpr()); 12859 return; 12860 } 12861 12862 Inherited::VisitUnaryOperator(E); 12863 } 12864 12865 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 12866 12867 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12868 if (E->getConstructor()->isCopyConstructor()) { 12869 Expr *ArgExpr = E->getArg(0); 12870 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 12871 if (ILE->getNumInits() == 1) 12872 ArgExpr = ILE->getInit(0); 12873 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 12874 if (ICE->getCastKind() == CK_NoOp) 12875 ArgExpr = ICE->getSubExpr(); 12876 HandleValue(ArgExpr); 12877 return; 12878 } 12879 Inherited::VisitCXXConstructExpr(E); 12880 } 12881 12882 void VisitCallExpr(CallExpr *E) { 12883 // Treat std::move as a use. 12884 if (E->isCallToStdMove()) { 12885 HandleValue(E->getArg(0)); 12886 return; 12887 } 12888 12889 Inherited::VisitCallExpr(E); 12890 } 12891 12892 void VisitBinaryOperator(BinaryOperator *E) { 12893 if (E->isCompoundAssignmentOp()) { 12894 HandleValue(E->getLHS()); 12895 Visit(E->getRHS()); 12896 return; 12897 } 12898 12899 Inherited::VisitBinaryOperator(E); 12900 } 12901 12902 // A custom visitor for BinaryConditionalOperator is needed because the 12903 // regular visitor would check the condition and true expression separately 12904 // but both point to the same place giving duplicate diagnostics. 12905 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 12906 Visit(E->getCond()); 12907 Visit(E->getFalseExpr()); 12908 } 12909 12910 void HandleDeclRefExpr(DeclRefExpr *DRE) { 12911 Decl* ReferenceDecl = DRE->getDecl(); 12912 if (OrigDecl != ReferenceDecl) return; 12913 unsigned diag; 12914 if (isReferenceType) { 12915 diag = diag::warn_uninit_self_reference_in_reference_init; 12916 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 12917 diag = diag::warn_static_self_reference_in_init; 12918 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 12919 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12920 DRE->getDecl()->getType()->isRecordType()) { 12921 diag = diag::warn_uninit_self_reference_in_init; 12922 } else { 12923 // Local variables will be handled by the CFG analysis. 12924 return; 12925 } 12926 12927 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12928 S.PDiag(diag) 12929 << DRE->getDecl() << OrigDecl->getLocation() 12930 << DRE->getSourceRange()); 12931 } 12932 }; 12933 12934 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12935 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12936 bool DirectInit) { 12937 // Parameters arguments are occassionially constructed with itself, 12938 // for instance, in recursive functions. Skip them. 12939 if (isa<ParmVarDecl>(OrigDecl)) 12940 return; 12941 12942 E = E->IgnoreParens(); 12943 12944 // Skip checking T a = a where T is not a record or reference type. 12945 // Doing so is a way to silence uninitialized warnings. 12946 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12947 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12948 if (ICE->getCastKind() == CK_LValueToRValue) 12949 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12950 if (DRE->getDecl() == OrigDecl) 12951 return; 12952 12953 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12954 } 12955 } // end anonymous namespace 12956 12957 namespace { 12958 // Simple wrapper to add the name of a variable or (if no variable is 12959 // available) a DeclarationName into a diagnostic. 12960 struct VarDeclOrName { 12961 VarDecl *VDecl; 12962 DeclarationName Name; 12963 12964 friend const Sema::SemaDiagnosticBuilder & 12965 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12966 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12967 } 12968 }; 12969 } // end anonymous namespace 12970 12971 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12972 DeclarationName Name, QualType Type, 12973 TypeSourceInfo *TSI, 12974 SourceRange Range, bool DirectInit, 12975 Expr *Init) { 12976 bool IsInitCapture = !VDecl; 12977 assert((!VDecl || !VDecl->isInitCapture()) && 12978 "init captures are expected to be deduced prior to initialization"); 12979 12980 VarDeclOrName VN{VDecl, Name}; 12981 12982 DeducedType *Deduced = Type->getContainedDeducedType(); 12983 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12984 12985 // Diagnose auto array declarations in C23, unless it's a supported extension. 12986 if (getLangOpts().C23 && Type->isArrayType() && 12987 !isa_and_present<StringLiteral, InitListExpr>(Init)) { 12988 Diag(Range.getBegin(), diag::err_auto_not_allowed) 12989 << (int)Deduced->getContainedAutoType()->getKeyword() 12990 << /*in array decl*/ 23 << Range; 12991 return QualType(); 12992 } 12993 12994 // C++11 [dcl.spec.auto]p3 12995 if (!Init) { 12996 assert(VDecl && "no init for init capture deduction?"); 12997 12998 // Except for class argument deduction, and then for an initializing 12999 // declaration only, i.e. no static at class scope or extern. 13000 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 13001 VDecl->hasExternalStorage() || 13002 VDecl->isStaticDataMember()) { 13003 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 13004 << VDecl->getDeclName() << Type; 13005 return QualType(); 13006 } 13007 } 13008 13009 ArrayRef<Expr*> DeduceInits; 13010 if (Init) 13011 DeduceInits = Init; 13012 13013 auto *PL = dyn_cast_if_present<ParenListExpr>(Init); 13014 if (DirectInit && PL) 13015 DeduceInits = PL->exprs(); 13016 13017 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 13018 assert(VDecl && "non-auto type for init capture deduction?"); 13019 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 13020 InitializationKind Kind = InitializationKind::CreateForInit( 13021 VDecl->getLocation(), DirectInit, Init); 13022 // FIXME: Initialization should not be taking a mutable list of inits. 13023 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 13024 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 13025 InitsCopy); 13026 } 13027 13028 if (DirectInit) { 13029 if (auto *IL = dyn_cast<InitListExpr>(Init)) 13030 DeduceInits = IL->inits(); 13031 } 13032 13033 // Deduction only works if we have exactly one source expression. 13034 if (DeduceInits.empty()) { 13035 // It isn't possible to write this directly, but it is possible to 13036 // end up in this situation with "auto x(some_pack...);" 13037 Diag(Init->getBeginLoc(), IsInitCapture 13038 ? diag::err_init_capture_no_expression 13039 : diag::err_auto_var_init_no_expression) 13040 << VN << Type << Range; 13041 return QualType(); 13042 } 13043 13044 if (DeduceInits.size() > 1) { 13045 Diag(DeduceInits[1]->getBeginLoc(), 13046 IsInitCapture ? diag::err_init_capture_multiple_expressions 13047 : diag::err_auto_var_init_multiple_expressions) 13048 << VN << Type << Range; 13049 return QualType(); 13050 } 13051 13052 Expr *DeduceInit = DeduceInits[0]; 13053 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 13054 Diag(Init->getBeginLoc(), IsInitCapture 13055 ? diag::err_init_capture_paren_braces 13056 : diag::err_auto_var_init_paren_braces) 13057 << isa<InitListExpr>(Init) << VN << Type << Range; 13058 return QualType(); 13059 } 13060 13061 // Expressions default to 'id' when we're in a debugger. 13062 bool DefaultedAnyToId = false; 13063 if (getLangOpts().DebuggerCastResultToId && 13064 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 13065 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13066 if (Result.isInvalid()) { 13067 return QualType(); 13068 } 13069 Init = Result.get(); 13070 DefaultedAnyToId = true; 13071 } 13072 13073 // C++ [dcl.decomp]p1: 13074 // If the assignment-expression [...] has array type A and no ref-qualifier 13075 // is present, e has type cv A 13076 if (VDecl && isa<DecompositionDecl>(VDecl) && 13077 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 13078 DeduceInit->getType()->isConstantArrayType()) 13079 return Context.getQualifiedType(DeduceInit->getType(), 13080 Type.getQualifiers()); 13081 13082 QualType DeducedType; 13083 TemplateDeductionInfo Info(DeduceInit->getExprLoc()); 13084 TemplateDeductionResult Result = 13085 DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info); 13086 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) { 13087 if (!IsInitCapture) 13088 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 13089 else if (isa<InitListExpr>(Init)) 13090 Diag(Range.getBegin(), 13091 diag::err_init_capture_deduction_failure_from_init_list) 13092 << VN 13093 << (DeduceInit->getType().isNull() ? TSI->getType() 13094 : DeduceInit->getType()) 13095 << DeduceInit->getSourceRange(); 13096 else 13097 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 13098 << VN << TSI->getType() 13099 << (DeduceInit->getType().isNull() ? TSI->getType() 13100 : DeduceInit->getType()) 13101 << DeduceInit->getSourceRange(); 13102 } 13103 13104 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 13105 // 'id' instead of a specific object type prevents most of our usual 13106 // checks. 13107 // We only want to warn outside of template instantiations, though: 13108 // inside a template, the 'id' could have come from a parameter. 13109 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 13110 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 13111 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 13112 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 13113 } 13114 13115 return DeducedType; 13116 } 13117 13118 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 13119 Expr *Init) { 13120 assert(!Init || !Init->containsErrors()); 13121 QualType DeducedType = deduceVarTypeFromInitializer( 13122 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 13123 VDecl->getSourceRange(), DirectInit, Init); 13124 if (DeducedType.isNull()) { 13125 VDecl->setInvalidDecl(); 13126 return true; 13127 } 13128 13129 VDecl->setType(DeducedType); 13130 assert(VDecl->isLinkageValid()); 13131 13132 // In ARC, infer lifetime. 13133 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 13134 VDecl->setInvalidDecl(); 13135 13136 if (getLangOpts().OpenCL) 13137 deduceOpenCLAddressSpace(VDecl); 13138 13139 // If this is a redeclaration, check that the type we just deduced matches 13140 // the previously declared type. 13141 if (VarDecl *Old = VDecl->getPreviousDecl()) { 13142 // We never need to merge the type, because we cannot form an incomplete 13143 // array of auto, nor deduce such a type. 13144 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 13145 } 13146 13147 // Check the deduced type is valid for a variable declaration. 13148 CheckVariableDeclarationType(VDecl); 13149 return VDecl->isInvalidDecl(); 13150 } 13151 13152 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 13153 SourceLocation Loc) { 13154 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 13155 Init = EWC->getSubExpr(); 13156 13157 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 13158 Init = CE->getSubExpr(); 13159 13160 QualType InitType = Init->getType(); 13161 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13162 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 13163 "shouldn't be called if type doesn't have a non-trivial C struct"); 13164 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 13165 for (auto *I : ILE->inits()) { 13166 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 13167 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13168 continue; 13169 SourceLocation SL = I->getExprLoc(); 13170 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 13171 } 13172 return; 13173 } 13174 13175 if (isa<ImplicitValueInitExpr>(Init)) { 13176 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13177 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 13178 NTCUK_Init); 13179 } else { 13180 // Assume all other explicit initializers involving copying some existing 13181 // object. 13182 // TODO: ignore any explicit initializers where we can guarantee 13183 // copy-elision. 13184 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 13185 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 13186 } 13187 } 13188 13189 namespace { 13190 13191 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 13192 // Ignore unavailable fields. A field can be marked as unavailable explicitly 13193 // in the source code or implicitly by the compiler if it is in a union 13194 // defined in a system header and has non-trivial ObjC ownership 13195 // qualifications. We don't want those fields to participate in determining 13196 // whether the containing union is non-trivial. 13197 return FD->hasAttr<UnavailableAttr>(); 13198 } 13199 13200 struct DiagNonTrivalCUnionDefaultInitializeVisitor 13201 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13202 void> { 13203 using Super = 13204 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 13205 void>; 13206 13207 DiagNonTrivalCUnionDefaultInitializeVisitor( 13208 QualType OrigTy, SourceLocation OrigLoc, 13209 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13210 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13211 13212 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 13213 const FieldDecl *FD, bool InNonTrivialUnion) { 13214 if (const auto *AT = S.Context.getAsArrayType(QT)) 13215 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13216 InNonTrivialUnion); 13217 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 13218 } 13219 13220 void visitARCStrong(QualType QT, const FieldDecl *FD, 13221 bool InNonTrivialUnion) { 13222 if (InNonTrivialUnion) 13223 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13224 << 1 << 0 << QT << FD->getName(); 13225 } 13226 13227 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13228 if (InNonTrivialUnion) 13229 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13230 << 1 << 0 << QT << FD->getName(); 13231 } 13232 13233 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13234 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13235 if (RD->isUnion()) { 13236 if (OrigLoc.isValid()) { 13237 bool IsUnion = false; 13238 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13239 IsUnion = OrigRD->isUnion(); 13240 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13241 << 0 << OrigTy << IsUnion << UseContext; 13242 // Reset OrigLoc so that this diagnostic is emitted only once. 13243 OrigLoc = SourceLocation(); 13244 } 13245 InNonTrivialUnion = true; 13246 } 13247 13248 if (InNonTrivialUnion) 13249 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13250 << 0 << 0 << QT.getUnqualifiedType() << ""; 13251 13252 for (const FieldDecl *FD : RD->fields()) 13253 if (!shouldIgnoreForRecordTriviality(FD)) 13254 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13255 } 13256 13257 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13258 13259 // The non-trivial C union type or the struct/union type that contains a 13260 // non-trivial C union. 13261 QualType OrigTy; 13262 SourceLocation OrigLoc; 13263 Sema::NonTrivialCUnionContext UseContext; 13264 Sema &S; 13265 }; 13266 13267 struct DiagNonTrivalCUnionDestructedTypeVisitor 13268 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 13269 using Super = 13270 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 13271 13272 DiagNonTrivalCUnionDestructedTypeVisitor( 13273 QualType OrigTy, SourceLocation OrigLoc, 13274 Sema::NonTrivialCUnionContext UseContext, Sema &S) 13275 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13276 13277 void visitWithKind(QualType::DestructionKind DK, QualType QT, 13278 const FieldDecl *FD, bool InNonTrivialUnion) { 13279 if (const auto *AT = S.Context.getAsArrayType(QT)) 13280 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13281 InNonTrivialUnion); 13282 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 13283 } 13284 13285 void visitARCStrong(QualType QT, const FieldDecl *FD, 13286 bool InNonTrivialUnion) { 13287 if (InNonTrivialUnion) 13288 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13289 << 1 << 1 << QT << FD->getName(); 13290 } 13291 13292 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13293 if (InNonTrivialUnion) 13294 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13295 << 1 << 1 << QT << FD->getName(); 13296 } 13297 13298 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13299 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13300 if (RD->isUnion()) { 13301 if (OrigLoc.isValid()) { 13302 bool IsUnion = false; 13303 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13304 IsUnion = OrigRD->isUnion(); 13305 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13306 << 1 << OrigTy << IsUnion << UseContext; 13307 // Reset OrigLoc so that this diagnostic is emitted only once. 13308 OrigLoc = SourceLocation(); 13309 } 13310 InNonTrivialUnion = true; 13311 } 13312 13313 if (InNonTrivialUnion) 13314 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13315 << 0 << 1 << QT.getUnqualifiedType() << ""; 13316 13317 for (const FieldDecl *FD : RD->fields()) 13318 if (!shouldIgnoreForRecordTriviality(FD)) 13319 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13320 } 13321 13322 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13323 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 13324 bool InNonTrivialUnion) {} 13325 13326 // The non-trivial C union type or the struct/union type that contains a 13327 // non-trivial C union. 13328 QualType OrigTy; 13329 SourceLocation OrigLoc; 13330 Sema::NonTrivialCUnionContext UseContext; 13331 Sema &S; 13332 }; 13333 13334 struct DiagNonTrivalCUnionCopyVisitor 13335 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 13336 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 13337 13338 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 13339 Sema::NonTrivialCUnionContext UseContext, 13340 Sema &S) 13341 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 13342 13343 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 13344 const FieldDecl *FD, bool InNonTrivialUnion) { 13345 if (const auto *AT = S.Context.getAsArrayType(QT)) 13346 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 13347 InNonTrivialUnion); 13348 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 13349 } 13350 13351 void visitARCStrong(QualType QT, const FieldDecl *FD, 13352 bool InNonTrivialUnion) { 13353 if (InNonTrivialUnion) 13354 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13355 << 1 << 2 << QT << FD->getName(); 13356 } 13357 13358 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13359 if (InNonTrivialUnion) 13360 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 13361 << 1 << 2 << QT << FD->getName(); 13362 } 13363 13364 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 13365 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 13366 if (RD->isUnion()) { 13367 if (OrigLoc.isValid()) { 13368 bool IsUnion = false; 13369 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 13370 IsUnion = OrigRD->isUnion(); 13371 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 13372 << 2 << OrigTy << IsUnion << UseContext; 13373 // Reset OrigLoc so that this diagnostic is emitted only once. 13374 OrigLoc = SourceLocation(); 13375 } 13376 InNonTrivialUnion = true; 13377 } 13378 13379 if (InNonTrivialUnion) 13380 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 13381 << 0 << 2 << QT.getUnqualifiedType() << ""; 13382 13383 for (const FieldDecl *FD : RD->fields()) 13384 if (!shouldIgnoreForRecordTriviality(FD)) 13385 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 13386 } 13387 13388 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 13389 const FieldDecl *FD, bool InNonTrivialUnion) {} 13390 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 13391 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 13392 bool InNonTrivialUnion) {} 13393 13394 // The non-trivial C union type or the struct/union type that contains a 13395 // non-trivial C union. 13396 QualType OrigTy; 13397 SourceLocation OrigLoc; 13398 Sema::NonTrivialCUnionContext UseContext; 13399 Sema &S; 13400 }; 13401 13402 } // namespace 13403 13404 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 13405 NonTrivialCUnionContext UseContext, 13406 unsigned NonTrivialKind) { 13407 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13408 QT.hasNonTrivialToPrimitiveDestructCUnion() || 13409 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 13410 "shouldn't be called if type doesn't have a non-trivial C union"); 13411 13412 if ((NonTrivialKind & NTCUK_Init) && 13413 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13414 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 13415 .visit(QT, nullptr, false); 13416 if ((NonTrivialKind & NTCUK_Destruct) && 13417 QT.hasNonTrivialToPrimitiveDestructCUnion()) 13418 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 13419 .visit(QT, nullptr, false); 13420 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 13421 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 13422 .visit(QT, nullptr, false); 13423 } 13424 13425 /// AddInitializerToDecl - Adds the initializer Init to the 13426 /// declaration dcl. If DirectInit is true, this is C++ direct 13427 /// initialization rather than copy initialization. 13428 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 13429 // If there is no declaration, there was an error parsing it. Just ignore 13430 // the initializer. 13431 if (!RealDecl || RealDecl->isInvalidDecl()) { 13432 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 13433 return; 13434 } 13435 13436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 13437 // Pure-specifiers are handled in ActOnPureSpecifier. 13438 Diag(Method->getLocation(), diag::err_member_function_initialization) 13439 << Method->getDeclName() << Init->getSourceRange(); 13440 Method->setInvalidDecl(); 13441 return; 13442 } 13443 13444 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 13445 if (!VDecl) { 13446 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 13447 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 13448 RealDecl->setInvalidDecl(); 13449 return; 13450 } 13451 13452 // WebAssembly tables can't be used to initialise a variable. 13453 if (Init && !Init->getType().isNull() && 13454 Init->getType()->isWebAssemblyTableType()) { 13455 Diag(Init->getExprLoc(), diag::err_wasm_table_art) << 0; 13456 VDecl->setInvalidDecl(); 13457 return; 13458 } 13459 13460 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 13461 if (VDecl->getType()->isUndeducedType()) { 13462 // Attempt typo correction early so that the type of the init expression can 13463 // be deduced based on the chosen correction if the original init contains a 13464 // TypoExpr. 13465 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 13466 if (!Res.isUsable()) { 13467 // There are unresolved typos in Init, just drop them. 13468 // FIXME: improve the recovery strategy to preserve the Init. 13469 RealDecl->setInvalidDecl(); 13470 return; 13471 } 13472 if (Res.get()->containsErrors()) { 13473 // Invalidate the decl as we don't know the type for recovery-expr yet. 13474 RealDecl->setInvalidDecl(); 13475 VDecl->setInit(Res.get()); 13476 return; 13477 } 13478 Init = Res.get(); 13479 13480 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 13481 return; 13482 } 13483 13484 // dllimport cannot be used on variable definitions. 13485 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 13486 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 13487 VDecl->setInvalidDecl(); 13488 return; 13489 } 13490 13491 // C99 6.7.8p5. If the declaration of an identifier has block scope, and 13492 // the identifier has external or internal linkage, the declaration shall 13493 // have no initializer for the identifier. 13494 // C++14 [dcl.init]p5 is the same restriction for C++. 13495 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 13496 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 13497 VDecl->setInvalidDecl(); 13498 return; 13499 } 13500 13501 if (!VDecl->getType()->isDependentType()) { 13502 // A definition must end up with a complete type, which means it must be 13503 // complete with the restriction that an array type might be completed by 13504 // the initializer; note that later code assumes this restriction. 13505 QualType BaseDeclType = VDecl->getType(); 13506 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 13507 BaseDeclType = Array->getElementType(); 13508 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 13509 diag::err_typecheck_decl_incomplete_type)) { 13510 RealDecl->setInvalidDecl(); 13511 return; 13512 } 13513 13514 // The variable can not have an abstract class type. 13515 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 13516 diag::err_abstract_type_in_decl, 13517 AbstractVariableType)) 13518 VDecl->setInvalidDecl(); 13519 } 13520 13521 // C++ [module.import/6] external definitions are not permitted in header 13522 // units. 13523 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 13524 !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() && 13525 VDecl->getFormalLinkage() == Linkage::External && !VDecl->isInline() && 13526 !VDecl->isTemplated() && !isa<VarTemplateSpecializationDecl>(VDecl)) { 13527 Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit); 13528 VDecl->setInvalidDecl(); 13529 } 13530 13531 // If adding the initializer will turn this declaration into a definition, 13532 // and we already have a definition for this variable, diagnose or otherwise 13533 // handle the situation. 13534 if (VarDecl *Def = VDecl->getDefinition()) 13535 if (Def != VDecl && 13536 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 13537 !VDecl->isThisDeclarationADemotedDefinition() && 13538 checkVarDeclRedefinition(Def, VDecl)) 13539 return; 13540 13541 if (getLangOpts().CPlusPlus) { 13542 // C++ [class.static.data]p4 13543 // If a static data member is of const integral or const 13544 // enumeration type, its declaration in the class definition can 13545 // specify a constant-initializer which shall be an integral 13546 // constant expression (5.19). In that case, the member can appear 13547 // in integral constant expressions. The member shall still be 13548 // defined in a namespace scope if it is used in the program and the 13549 // namespace scope definition shall not contain an initializer. 13550 // 13551 // We already performed a redefinition check above, but for static 13552 // data members we also need to check whether there was an in-class 13553 // declaration with an initializer. 13554 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 13555 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 13556 << VDecl->getDeclName(); 13557 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 13558 diag::note_previous_initializer) 13559 << 0; 13560 return; 13561 } 13562 13563 if (VDecl->hasLocalStorage()) 13564 setFunctionHasBranchProtectedScope(); 13565 13566 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 13567 VDecl->setInvalidDecl(); 13568 return; 13569 } 13570 } 13571 13572 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 13573 // a kernel function cannot be initialized." 13574 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 13575 Diag(VDecl->getLocation(), diag::err_local_cant_init); 13576 VDecl->setInvalidDecl(); 13577 return; 13578 } 13579 13580 // The LoaderUninitialized attribute acts as a definition (of undef). 13581 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 13582 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 13583 VDecl->setInvalidDecl(); 13584 return; 13585 } 13586 13587 // Get the decls type and save a reference for later, since 13588 // CheckInitializerTypes may change it. 13589 QualType DclT = VDecl->getType(), SavT = DclT; 13590 13591 // Expressions default to 'id' when we're in a debugger 13592 // and we are assigning it to a variable of Objective-C pointer type. 13593 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 13594 Init->getType() == Context.UnknownAnyTy) { 13595 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 13596 if (Result.isInvalid()) { 13597 VDecl->setInvalidDecl(); 13598 return; 13599 } 13600 Init = Result.get(); 13601 } 13602 13603 // Perform the initialization. 13604 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 13605 bool IsParenListInit = false; 13606 if (!VDecl->isInvalidDecl()) { 13607 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 13608 InitializationKind Kind = InitializationKind::CreateForInit( 13609 VDecl->getLocation(), DirectInit, Init); 13610 13611 MultiExprArg Args = Init; 13612 if (CXXDirectInit) 13613 Args = MultiExprArg(CXXDirectInit->getExprs(), 13614 CXXDirectInit->getNumExprs()); 13615 13616 // Try to correct any TypoExprs in the initialization arguments. 13617 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 13618 ExprResult Res = CorrectDelayedTyposInExpr( 13619 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 13620 [this, Entity, Kind](Expr *E) { 13621 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 13622 return Init.Failed() ? ExprError() : E; 13623 }); 13624 if (Res.isInvalid()) { 13625 VDecl->setInvalidDecl(); 13626 } else if (Res.get() != Args[Idx]) { 13627 Args[Idx] = Res.get(); 13628 } 13629 } 13630 if (VDecl->isInvalidDecl()) 13631 return; 13632 13633 InitializationSequence InitSeq(*this, Entity, Kind, Args, 13634 /*TopLevelOfInitList=*/false, 13635 /*TreatUnavailableAsInvalid=*/false); 13636 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 13637 if (Result.isInvalid()) { 13638 // If the provided initializer fails to initialize the var decl, 13639 // we attach a recovery expr for better recovery. 13640 auto RecoveryExpr = 13641 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 13642 if (RecoveryExpr.get()) 13643 VDecl->setInit(RecoveryExpr.get()); 13644 // In general, for error recovery purposes, the initalizer doesn't play 13645 // part in the valid bit of the declaration. There are a few exceptions: 13646 // 1) if the var decl has a deduced auto type, and the type cannot be 13647 // deduced by an invalid initializer; 13648 // 2) if the var decl is decompsition decl with a non-deduced type, and 13649 // the initialization fails (e.g. `int [a] = {1, 2};`); 13650 // Case 1) was already handled elsewhere. 13651 if (isa<DecompositionDecl>(VDecl)) // Case 2) 13652 VDecl->setInvalidDecl(); 13653 return; 13654 } 13655 13656 Init = Result.getAs<Expr>(); 13657 IsParenListInit = !InitSeq.steps().empty() && 13658 InitSeq.step_begin()->Kind == 13659 InitializationSequence::SK_ParenthesizedListInit; 13660 QualType VDeclType = VDecl->getType(); 13661 if (Init && !Init->getType().isNull() && 13662 !Init->getType()->isDependentType() && !VDeclType->isDependentType() && 13663 Context.getAsIncompleteArrayType(VDeclType) && 13664 Context.getAsIncompleteArrayType(Init->getType())) { 13665 // Bail out if it is not possible to deduce array size from the 13666 // initializer. 13667 Diag(VDecl->getLocation(), diag::err_typecheck_decl_incomplete_type) 13668 << VDeclType; 13669 VDecl->setInvalidDecl(); 13670 return; 13671 } 13672 } 13673 13674 // Check for self-references within variable initializers. 13675 // Variables declared within a function/method body (except for references) 13676 // are handled by a dataflow analysis. 13677 // This is undefined behavior in C++, but valid in C. 13678 if (getLangOpts().CPlusPlus) 13679 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 13680 VDecl->getType()->isReferenceType()) 13681 CheckSelfReference(*this, RealDecl, Init, DirectInit); 13682 13683 // If the type changed, it means we had an incomplete type that was 13684 // completed by the initializer. For example: 13685 // int ary[] = { 1, 3, 5 }; 13686 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 13687 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 13688 VDecl->setType(DclT); 13689 13690 if (!VDecl->isInvalidDecl()) { 13691 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 13692 13693 if (VDecl->hasAttr<BlocksAttr>()) 13694 checkRetainCycles(VDecl, Init); 13695 13696 // It is safe to assign a weak reference into a strong variable. 13697 // Although this code can still have problems: 13698 // id x = self.weakProp; 13699 // id y = self.weakProp; 13700 // we do not warn to warn spuriously when 'x' and 'y' are on separate 13701 // paths through the function. This should be revisited if 13702 // -Wrepeated-use-of-weak is made flow-sensitive. 13703 if (FunctionScopeInfo *FSI = getCurFunction()) 13704 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 13705 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 13706 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 13707 Init->getBeginLoc())) 13708 FSI->markSafeWeakUse(Init); 13709 } 13710 13711 // The initialization is usually a full-expression. 13712 // 13713 // FIXME: If this is a braced initialization of an aggregate, it is not 13714 // an expression, and each individual field initializer is a separate 13715 // full-expression. For instance, in: 13716 // 13717 // struct Temp { ~Temp(); }; 13718 // struct S { S(Temp); }; 13719 // struct T { S a, b; } t = { Temp(), Temp() } 13720 // 13721 // we should destroy the first Temp before constructing the second. 13722 ExprResult Result = 13723 ActOnFinishFullExpr(Init, VDecl->getLocation(), 13724 /*DiscardedValue*/ false, VDecl->isConstexpr()); 13725 if (Result.isInvalid()) { 13726 VDecl->setInvalidDecl(); 13727 return; 13728 } 13729 Init = Result.get(); 13730 13731 // Attach the initializer to the decl. 13732 VDecl->setInit(Init); 13733 13734 if (VDecl->isLocalVarDecl()) { 13735 // Don't check the initializer if the declaration is malformed. 13736 if (VDecl->isInvalidDecl()) { 13737 // do nothing 13738 13739 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 13740 // This is true even in C++ for OpenCL. 13741 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 13742 CheckForConstantInitializer(Init, DclT); 13743 13744 // Otherwise, C++ does not restrict the initializer. 13745 } else if (getLangOpts().CPlusPlus) { 13746 // do nothing 13747 13748 // C99 6.7.8p4: All the expressions in an initializer for an object that has 13749 // static storage duration shall be constant expressions or string literals. 13750 } else if (VDecl->getStorageClass() == SC_Static) { 13751 CheckForConstantInitializer(Init, DclT); 13752 13753 // C89 is stricter than C99 for aggregate initializers. 13754 // C89 6.5.7p3: All the expressions [...] in an initializer list 13755 // for an object that has aggregate or union type shall be 13756 // constant expressions. 13757 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 13758 isa<InitListExpr>(Init)) { 13759 const Expr *Culprit; 13760 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 13761 Diag(Culprit->getExprLoc(), 13762 diag::ext_aggregate_init_not_constant) 13763 << Culprit->getSourceRange(); 13764 } 13765 } 13766 13767 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 13768 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 13769 if (VDecl->hasLocalStorage()) 13770 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 13771 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 13772 VDecl->getLexicalDeclContext()->isRecord()) { 13773 // This is an in-class initialization for a static data member, e.g., 13774 // 13775 // struct S { 13776 // static const int value = 17; 13777 // }; 13778 13779 // C++ [class.mem]p4: 13780 // A member-declarator can contain a constant-initializer only 13781 // if it declares a static member (9.4) of const integral or 13782 // const enumeration type, see 9.4.2. 13783 // 13784 // C++11 [class.static.data]p3: 13785 // If a non-volatile non-inline const static data member is of integral 13786 // or enumeration type, its declaration in the class definition can 13787 // specify a brace-or-equal-initializer in which every initializer-clause 13788 // that is an assignment-expression is a constant expression. A static 13789 // data member of literal type can be declared in the class definition 13790 // with the constexpr specifier; if so, its declaration shall specify a 13791 // brace-or-equal-initializer in which every initializer-clause that is 13792 // an assignment-expression is a constant expression. 13793 13794 // Do nothing on dependent types. 13795 if (DclT->isDependentType()) { 13796 13797 // Allow any 'static constexpr' members, whether or not they are of literal 13798 // type. We separately check that every constexpr variable is of literal 13799 // type. 13800 } else if (VDecl->isConstexpr()) { 13801 13802 // Require constness. 13803 } else if (!DclT.isConstQualified()) { 13804 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 13805 << Init->getSourceRange(); 13806 VDecl->setInvalidDecl(); 13807 13808 // We allow integer constant expressions in all cases. 13809 } else if (DclT->isIntegralOrEnumerationType()) { 13810 // Check whether the expression is a constant expression. 13811 SourceLocation Loc; 13812 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 13813 // In C++11, a non-constexpr const static data member with an 13814 // in-class initializer cannot be volatile. 13815 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 13816 else if (Init->isValueDependent()) 13817 ; // Nothing to check. 13818 else if (Init->isIntegerConstantExpr(Context, &Loc)) 13819 ; // Ok, it's an ICE! 13820 else if (Init->getType()->isScopedEnumeralType() && 13821 Init->isCXX11ConstantExpr(Context)) 13822 ; // Ok, it is a scoped-enum constant expression. 13823 else if (Init->isEvaluatable(Context)) { 13824 // If we can constant fold the initializer through heroics, accept it, 13825 // but report this as a use of an extension for -pedantic. 13826 Diag(Loc, diag::ext_in_class_initializer_non_constant) 13827 << Init->getSourceRange(); 13828 } else { 13829 // Otherwise, this is some crazy unknown case. Report the issue at the 13830 // location provided by the isIntegerConstantExpr failed check. 13831 Diag(Loc, diag::err_in_class_initializer_non_constant) 13832 << Init->getSourceRange(); 13833 VDecl->setInvalidDecl(); 13834 } 13835 13836 // We allow foldable floating-point constants as an extension. 13837 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 13838 // In C++98, this is a GNU extension. In C++11, it is not, but we support 13839 // it anyway and provide a fixit to add the 'constexpr'. 13840 if (getLangOpts().CPlusPlus11) { 13841 Diag(VDecl->getLocation(), 13842 diag::ext_in_class_initializer_float_type_cxx11) 13843 << DclT << Init->getSourceRange(); 13844 Diag(VDecl->getBeginLoc(), 13845 diag::note_in_class_initializer_float_type_cxx11) 13846 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13847 } else { 13848 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 13849 << DclT << Init->getSourceRange(); 13850 13851 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 13852 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 13853 << Init->getSourceRange(); 13854 VDecl->setInvalidDecl(); 13855 } 13856 } 13857 13858 // Suggest adding 'constexpr' in C++11 for literal types. 13859 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 13860 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 13861 << DclT << Init->getSourceRange() 13862 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 13863 VDecl->setConstexpr(true); 13864 13865 } else { 13866 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 13867 << DclT << Init->getSourceRange(); 13868 VDecl->setInvalidDecl(); 13869 } 13870 } else if (VDecl->isFileVarDecl()) { 13871 // In C, extern is typically used to avoid tentative definitions when 13872 // declaring variables in headers, but adding an intializer makes it a 13873 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 13874 // In C++, extern is often used to give implictly static const variables 13875 // external linkage, so don't warn in that case. If selectany is present, 13876 // this might be header code intended for C and C++ inclusion, so apply the 13877 // C++ rules. 13878 if (VDecl->getStorageClass() == SC_Extern && 13879 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 13880 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 13881 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 13882 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 13883 Diag(VDecl->getLocation(), diag::warn_extern_init); 13884 13885 // In Microsoft C++ mode, a const variable defined in namespace scope has 13886 // external linkage by default if the variable is declared with 13887 // __declspec(dllexport). 13888 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 13889 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 13890 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 13891 VDecl->setStorageClass(SC_Extern); 13892 13893 // C99 6.7.8p4. All file scoped initializers need to be constant. 13894 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 13895 CheckForConstantInitializer(Init, DclT); 13896 } 13897 13898 QualType InitType = Init->getType(); 13899 if (!InitType.isNull() && 13900 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 13901 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 13902 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 13903 13904 // We will represent direct-initialization similarly to copy-initialization: 13905 // int x(1); -as-> int x = 1; 13906 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 13907 // 13908 // Clients that want to distinguish between the two forms, can check for 13909 // direct initializer using VarDecl::getInitStyle(). 13910 // A major benefit is that clients that don't particularly care about which 13911 // exactly form was it (like the CodeGen) can handle both cases without 13912 // special case code. 13913 13914 // C++ 8.5p11: 13915 // The form of initialization (using parentheses or '=') is generally 13916 // insignificant, but does matter when the entity being initialized has a 13917 // class type. 13918 if (CXXDirectInit) { 13919 assert(DirectInit && "Call-style initializer must be direct init."); 13920 VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit 13921 : VarDecl::CallInit); 13922 } else if (DirectInit) { 13923 // This must be list-initialization. No other way is direct-initialization. 13924 VDecl->setInitStyle(VarDecl::ListInit); 13925 } 13926 13927 if (LangOpts.OpenMP && 13928 (LangOpts.OpenMPIsTargetDevice || !LangOpts.OMPTargetTriples.empty()) && 13929 VDecl->isFileVarDecl()) 13930 DeclsToCheckForDeferredDiags.insert(VDecl); 13931 CheckCompleteVariableDeclaration(VDecl); 13932 } 13933 13934 /// ActOnInitializerError - Given that there was an error parsing an 13935 /// initializer for the given declaration, try to at least re-establish 13936 /// invariants such as whether a variable's type is either dependent or 13937 /// complete. 13938 void Sema::ActOnInitializerError(Decl *D) { 13939 // Our main concern here is re-establishing invariants like "a 13940 // variable's type is either dependent or complete". 13941 if (!D || D->isInvalidDecl()) return; 13942 13943 VarDecl *VD = dyn_cast<VarDecl>(D); 13944 if (!VD) return; 13945 13946 // Bindings are not usable if we can't make sense of the initializer. 13947 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 13948 for (auto *BD : DD->bindings()) 13949 BD->setInvalidDecl(); 13950 13951 // Auto types are meaningless if we can't make sense of the initializer. 13952 if (VD->getType()->isUndeducedType()) { 13953 D->setInvalidDecl(); 13954 return; 13955 } 13956 13957 QualType Ty = VD->getType(); 13958 if (Ty->isDependentType()) return; 13959 13960 // Require a complete type. 13961 if (RequireCompleteType(VD->getLocation(), 13962 Context.getBaseElementType(Ty), 13963 diag::err_typecheck_decl_incomplete_type)) { 13964 VD->setInvalidDecl(); 13965 return; 13966 } 13967 13968 // Require a non-abstract type. 13969 if (RequireNonAbstractType(VD->getLocation(), Ty, 13970 diag::err_abstract_type_in_decl, 13971 AbstractVariableType)) { 13972 VD->setInvalidDecl(); 13973 return; 13974 } 13975 13976 // Don't bother complaining about constructors or destructors, 13977 // though. 13978 } 13979 13980 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13981 // If there is no declaration, there was an error parsing it. Just ignore it. 13982 if (!RealDecl) 13983 return; 13984 13985 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13986 QualType Type = Var->getType(); 13987 13988 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13989 if (isa<DecompositionDecl>(RealDecl)) { 13990 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13991 Var->setInvalidDecl(); 13992 return; 13993 } 13994 13995 if (Type->isUndeducedType() && 13996 DeduceVariableDeclarationType(Var, false, nullptr)) 13997 return; 13998 13999 // C++11 [class.static.data]p3: A static data member can be declared with 14000 // the constexpr specifier; if so, its declaration shall specify 14001 // a brace-or-equal-initializer. 14002 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 14003 // the definition of a variable [...] or the declaration of a static data 14004 // member. 14005 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 14006 !Var->isThisDeclarationADemotedDefinition()) { 14007 if (Var->isStaticDataMember()) { 14008 // C++1z removes the relevant rule; the in-class declaration is always 14009 // a definition there. 14010 if (!getLangOpts().CPlusPlus17 && 14011 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14012 Diag(Var->getLocation(), 14013 diag::err_constexpr_static_mem_var_requires_init) 14014 << Var; 14015 Var->setInvalidDecl(); 14016 return; 14017 } 14018 } else { 14019 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 14020 Var->setInvalidDecl(); 14021 return; 14022 } 14023 } 14024 14025 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 14026 // be initialized. 14027 if (!Var->isInvalidDecl() && 14028 Var->getType().getAddressSpace() == LangAS::opencl_constant && 14029 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 14030 bool HasConstExprDefaultConstructor = false; 14031 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 14032 for (auto *Ctor : RD->ctors()) { 14033 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 14034 Ctor->getMethodQualifiers().getAddressSpace() == 14035 LangAS::opencl_constant) { 14036 HasConstExprDefaultConstructor = true; 14037 } 14038 } 14039 } 14040 if (!HasConstExprDefaultConstructor) { 14041 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 14042 Var->setInvalidDecl(); 14043 return; 14044 } 14045 } 14046 14047 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 14048 if (Var->getStorageClass() == SC_Extern) { 14049 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 14050 << Var; 14051 Var->setInvalidDecl(); 14052 return; 14053 } 14054 if (RequireCompleteType(Var->getLocation(), Var->getType(), 14055 diag::err_typecheck_decl_incomplete_type)) { 14056 Var->setInvalidDecl(); 14057 return; 14058 } 14059 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 14060 if (!RD->hasTrivialDefaultConstructor()) { 14061 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 14062 Var->setInvalidDecl(); 14063 return; 14064 } 14065 } 14066 // The declaration is unitialized, no need for further checks. 14067 return; 14068 } 14069 14070 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 14071 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 14072 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 14073 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 14074 NTCUC_DefaultInitializedObject, NTCUK_Init); 14075 14076 14077 switch (DefKind) { 14078 case VarDecl::Definition: 14079 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 14080 break; 14081 14082 // We have an out-of-line definition of a static data member 14083 // that has an in-class initializer, so we type-check this like 14084 // a declaration. 14085 // 14086 [[fallthrough]]; 14087 14088 case VarDecl::DeclarationOnly: 14089 // It's only a declaration. 14090 14091 // Block scope. C99 6.7p7: If an identifier for an object is 14092 // declared with no linkage (C99 6.2.2p6), the type for the 14093 // object shall be complete. 14094 if (!Type->isDependentType() && Var->isLocalVarDecl() && 14095 !Var->hasLinkage() && !Var->isInvalidDecl() && 14096 RequireCompleteType(Var->getLocation(), Type, 14097 diag::err_typecheck_decl_incomplete_type)) 14098 Var->setInvalidDecl(); 14099 14100 // Make sure that the type is not abstract. 14101 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14102 RequireNonAbstractType(Var->getLocation(), Type, 14103 diag::err_abstract_type_in_decl, 14104 AbstractVariableType)) 14105 Var->setInvalidDecl(); 14106 if (!Type->isDependentType() && !Var->isInvalidDecl() && 14107 Var->getStorageClass() == SC_PrivateExtern) { 14108 Diag(Var->getLocation(), diag::warn_private_extern); 14109 Diag(Var->getLocation(), diag::note_private_extern); 14110 } 14111 14112 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 14113 !Var->isInvalidDecl()) 14114 ExternalDeclarations.push_back(Var); 14115 14116 return; 14117 14118 case VarDecl::TentativeDefinition: 14119 // File scope. C99 6.9.2p2: A declaration of an identifier for an 14120 // object that has file scope without an initializer, and without a 14121 // storage-class specifier or with the storage-class specifier "static", 14122 // constitutes a tentative definition. Note: A tentative definition with 14123 // external linkage is valid (C99 6.2.2p5). 14124 if (!Var->isInvalidDecl()) { 14125 if (const IncompleteArrayType *ArrayT 14126 = Context.getAsIncompleteArrayType(Type)) { 14127 if (RequireCompleteSizedType( 14128 Var->getLocation(), ArrayT->getElementType(), 14129 diag::err_array_incomplete_or_sizeless_type)) 14130 Var->setInvalidDecl(); 14131 } else if (Var->getStorageClass() == SC_Static) { 14132 // C99 6.9.2p3: If the declaration of an identifier for an object is 14133 // a tentative definition and has internal linkage (C99 6.2.2p3), the 14134 // declared type shall not be an incomplete type. 14135 // NOTE: code such as the following 14136 // static struct s; 14137 // struct s { int a; }; 14138 // is accepted by gcc. Hence here we issue a warning instead of 14139 // an error and we do not invalidate the static declaration. 14140 // NOTE: to avoid multiple warnings, only check the first declaration. 14141 if (Var->isFirstDecl()) 14142 RequireCompleteType(Var->getLocation(), Type, 14143 diag::ext_typecheck_decl_incomplete_type); 14144 } 14145 } 14146 14147 // Record the tentative definition; we're done. 14148 if (!Var->isInvalidDecl()) 14149 TentativeDefinitions.push_back(Var); 14150 return; 14151 } 14152 14153 // Provide a specific diagnostic for uninitialized variable 14154 // definitions with incomplete array type. 14155 if (Type->isIncompleteArrayType()) { 14156 if (Var->isConstexpr()) 14157 Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init) 14158 << Var; 14159 else 14160 Diag(Var->getLocation(), 14161 diag::err_typecheck_incomplete_array_needs_initializer); 14162 Var->setInvalidDecl(); 14163 return; 14164 } 14165 14166 // Provide a specific diagnostic for uninitialized variable 14167 // definitions with reference type. 14168 if (Type->isReferenceType()) { 14169 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 14170 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 14171 return; 14172 } 14173 14174 // Do not attempt to type-check the default initializer for a 14175 // variable with dependent type. 14176 if (Type->isDependentType()) 14177 return; 14178 14179 if (Var->isInvalidDecl()) 14180 return; 14181 14182 if (!Var->hasAttr<AliasAttr>()) { 14183 if (RequireCompleteType(Var->getLocation(), 14184 Context.getBaseElementType(Type), 14185 diag::err_typecheck_decl_incomplete_type)) { 14186 Var->setInvalidDecl(); 14187 return; 14188 } 14189 } else { 14190 return; 14191 } 14192 14193 // The variable can not have an abstract class type. 14194 if (RequireNonAbstractType(Var->getLocation(), Type, 14195 diag::err_abstract_type_in_decl, 14196 AbstractVariableType)) { 14197 Var->setInvalidDecl(); 14198 return; 14199 } 14200 14201 // Check for jumps past the implicit initializer. C++0x 14202 // clarifies that this applies to a "variable with automatic 14203 // storage duration", not a "local variable". 14204 // C++11 [stmt.dcl]p3 14205 // A program that jumps from a point where a variable with automatic 14206 // storage duration is not in scope to a point where it is in scope is 14207 // ill-formed unless the variable has scalar type, class type with a 14208 // trivial default constructor and a trivial destructor, a cv-qualified 14209 // version of one of these types, or an array of one of the preceding 14210 // types and is declared without an initializer. 14211 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 14212 if (const RecordType *Record 14213 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 14214 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 14215 // Mark the function (if we're in one) for further checking even if the 14216 // looser rules of C++11 do not require such checks, so that we can 14217 // diagnose incompatibilities with C++98. 14218 if (!CXXRecord->isPOD()) 14219 setFunctionHasBranchProtectedScope(); 14220 } 14221 } 14222 // In OpenCL, we can't initialize objects in the __local address space, 14223 // even implicitly, so don't synthesize an implicit initializer. 14224 if (getLangOpts().OpenCL && 14225 Var->getType().getAddressSpace() == LangAS::opencl_local) 14226 return; 14227 // C++03 [dcl.init]p9: 14228 // If no initializer is specified for an object, and the 14229 // object is of (possibly cv-qualified) non-POD class type (or 14230 // array thereof), the object shall be default-initialized; if 14231 // the object is of const-qualified type, the underlying class 14232 // type shall have a user-declared default 14233 // constructor. Otherwise, if no initializer is specified for 14234 // a non- static object, the object and its subobjects, if 14235 // any, have an indeterminate initial value); if the object 14236 // or any of its subobjects are of const-qualified type, the 14237 // program is ill-formed. 14238 // C++0x [dcl.init]p11: 14239 // If no initializer is specified for an object, the object is 14240 // default-initialized; [...]. 14241 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 14242 InitializationKind Kind 14243 = InitializationKind::CreateDefault(Var->getLocation()); 14244 14245 InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt); 14246 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt); 14247 14248 if (Init.get()) { 14249 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 14250 // This is important for template substitution. 14251 Var->setInitStyle(VarDecl::CallInit); 14252 } else if (Init.isInvalid()) { 14253 // If default-init fails, attach a recovery-expr initializer to track 14254 // that initialization was attempted and failed. 14255 auto RecoveryExpr = 14256 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 14257 if (RecoveryExpr.get()) 14258 Var->setInit(RecoveryExpr.get()); 14259 } 14260 14261 CheckCompleteVariableDeclaration(Var); 14262 } 14263 } 14264 14265 void Sema::ActOnCXXForRangeDecl(Decl *D) { 14266 // If there is no declaration, there was an error parsing it. Ignore it. 14267 if (!D) 14268 return; 14269 14270 VarDecl *VD = dyn_cast<VarDecl>(D); 14271 if (!VD) { 14272 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 14273 D->setInvalidDecl(); 14274 return; 14275 } 14276 14277 VD->setCXXForRangeDecl(true); 14278 14279 // for-range-declaration cannot be given a storage class specifier. 14280 int Error = -1; 14281 switch (VD->getStorageClass()) { 14282 case SC_None: 14283 break; 14284 case SC_Extern: 14285 Error = 0; 14286 break; 14287 case SC_Static: 14288 Error = 1; 14289 break; 14290 case SC_PrivateExtern: 14291 Error = 2; 14292 break; 14293 case SC_Auto: 14294 Error = 3; 14295 break; 14296 case SC_Register: 14297 Error = 4; 14298 break; 14299 } 14300 14301 // for-range-declaration cannot be given a storage class specifier con't. 14302 switch (VD->getTSCSpec()) { 14303 case TSCS_thread_local: 14304 Error = 6; 14305 break; 14306 case TSCS___thread: 14307 case TSCS__Thread_local: 14308 case TSCS_unspecified: 14309 break; 14310 } 14311 14312 if (Error != -1) { 14313 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 14314 << VD << Error; 14315 D->setInvalidDecl(); 14316 } 14317 } 14318 14319 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 14320 IdentifierInfo *Ident, 14321 ParsedAttributes &Attrs) { 14322 // C++1y [stmt.iter]p1: 14323 // A range-based for statement of the form 14324 // for ( for-range-identifier : for-range-initializer ) statement 14325 // is equivalent to 14326 // for ( auto&& for-range-identifier : for-range-initializer ) statement 14327 DeclSpec DS(Attrs.getPool().getFactory()); 14328 14329 const char *PrevSpec; 14330 unsigned DiagID; 14331 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 14332 getPrintingPolicy()); 14333 14334 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); 14335 D.SetIdentifier(Ident, IdentLoc); 14336 D.takeAttributes(Attrs); 14337 14338 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 14339 IdentLoc); 14340 Decl *Var = ActOnDeclarator(S, D); 14341 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 14342 FinalizeDeclaration(Var); 14343 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 14344 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 14345 : IdentLoc); 14346 } 14347 14348 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 14349 if (var->isInvalidDecl()) return; 14350 14351 MaybeAddCUDAConstantAttr(var); 14352 14353 if (getLangOpts().OpenCL) { 14354 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 14355 // initialiser 14356 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 14357 !var->hasInit()) { 14358 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 14359 << 1 /*Init*/; 14360 var->setInvalidDecl(); 14361 return; 14362 } 14363 } 14364 14365 // In Objective-C, don't allow jumps past the implicit initialization of a 14366 // local retaining variable. 14367 if (getLangOpts().ObjC && 14368 var->hasLocalStorage()) { 14369 switch (var->getType().getObjCLifetime()) { 14370 case Qualifiers::OCL_None: 14371 case Qualifiers::OCL_ExplicitNone: 14372 case Qualifiers::OCL_Autoreleasing: 14373 break; 14374 14375 case Qualifiers::OCL_Weak: 14376 case Qualifiers::OCL_Strong: 14377 setFunctionHasBranchProtectedScope(); 14378 break; 14379 } 14380 } 14381 14382 if (var->hasLocalStorage() && 14383 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 14384 setFunctionHasBranchProtectedScope(); 14385 14386 // Warn about externally-visible variables being defined without a 14387 // prior declaration. We only want to do this for global 14388 // declarations, but we also specifically need to avoid doing it for 14389 // class members because the linkage of an anonymous class can 14390 // change if it's later given a typedef name. 14391 if (var->isThisDeclarationADefinition() && 14392 var->getDeclContext()->getRedeclContext()->isFileContext() && 14393 var->isExternallyVisible() && var->hasLinkage() && 14394 !var->isInline() && !var->getDescribedVarTemplate() && 14395 var->getStorageClass() != SC_Register && 14396 !isa<VarTemplatePartialSpecializationDecl>(var) && 14397 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 14398 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 14399 var->getLocation())) { 14400 // Find a previous declaration that's not a definition. 14401 VarDecl *prev = var->getPreviousDecl(); 14402 while (prev && prev->isThisDeclarationADefinition()) 14403 prev = prev->getPreviousDecl(); 14404 14405 if (!prev) { 14406 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 14407 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14408 << /* variable */ 0; 14409 } 14410 } 14411 14412 // Cache the result of checking for constant initialization. 14413 std::optional<bool> CacheHasConstInit; 14414 const Expr *CacheCulprit = nullptr; 14415 auto checkConstInit = [&]() mutable { 14416 if (!CacheHasConstInit) 14417 CacheHasConstInit = var->getInit()->isConstantInitializer( 14418 Context, var->getType()->isReferenceType(), &CacheCulprit); 14419 return *CacheHasConstInit; 14420 }; 14421 14422 if (var->getTLSKind() == VarDecl::TLS_Static) { 14423 if (var->getType().isDestructedType()) { 14424 // GNU C++98 edits for __thread, [basic.start.term]p3: 14425 // The type of an object with thread storage duration shall not 14426 // have a non-trivial destructor. 14427 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 14428 if (getLangOpts().CPlusPlus11) 14429 Diag(var->getLocation(), diag::note_use_thread_local); 14430 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 14431 if (!checkConstInit()) { 14432 // GNU C++98 edits for __thread, [basic.start.init]p4: 14433 // An object of thread storage duration shall not require dynamic 14434 // initialization. 14435 // FIXME: Need strict checking here. 14436 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 14437 << CacheCulprit->getSourceRange(); 14438 if (getLangOpts().CPlusPlus11) 14439 Diag(var->getLocation(), diag::note_use_thread_local); 14440 } 14441 } 14442 } 14443 14444 14445 if (!var->getType()->isStructureType() && var->hasInit() && 14446 isa<InitListExpr>(var->getInit())) { 14447 const auto *ILE = cast<InitListExpr>(var->getInit()); 14448 unsigned NumInits = ILE->getNumInits(); 14449 if (NumInits > 2) 14450 for (unsigned I = 0; I < NumInits; ++I) { 14451 const auto *Init = ILE->getInit(I); 14452 if (!Init) 14453 break; 14454 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14455 if (!SL) 14456 break; 14457 14458 unsigned NumConcat = SL->getNumConcatenated(); 14459 // Diagnose missing comma in string array initialization. 14460 // Do not warn when all the elements in the initializer are concatenated 14461 // together. Do not warn for macros too. 14462 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 14463 bool OnlyOneMissingComma = true; 14464 for (unsigned J = I + 1; J < NumInits; ++J) { 14465 const auto *Init = ILE->getInit(J); 14466 if (!Init) 14467 break; 14468 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 14469 if (!SLJ || SLJ->getNumConcatenated() > 1) { 14470 OnlyOneMissingComma = false; 14471 break; 14472 } 14473 } 14474 14475 if (OnlyOneMissingComma) { 14476 SmallVector<FixItHint, 1> Hints; 14477 for (unsigned i = 0; i < NumConcat - 1; ++i) 14478 Hints.push_back(FixItHint::CreateInsertion( 14479 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 14480 14481 Diag(SL->getStrTokenLoc(1), 14482 diag::warn_concatenated_literal_array_init) 14483 << Hints; 14484 Diag(SL->getBeginLoc(), 14485 diag::note_concatenated_string_literal_silence); 14486 } 14487 // In any case, stop now. 14488 break; 14489 } 14490 } 14491 } 14492 14493 14494 QualType type = var->getType(); 14495 14496 if (var->hasAttr<BlocksAttr>()) 14497 getCurFunction()->addByrefBlockVar(var); 14498 14499 Expr *Init = var->getInit(); 14500 bool GlobalStorage = var->hasGlobalStorage(); 14501 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 14502 QualType baseType = Context.getBaseElementType(type); 14503 bool HasConstInit = true; 14504 14505 // Check whether the initializer is sufficiently constant. 14506 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 14507 !Init->isValueDependent() && 14508 (GlobalStorage || var->isConstexpr() || 14509 var->mightBeUsableInConstantExpressions(Context))) { 14510 // If this variable might have a constant initializer or might be usable in 14511 // constant expressions, check whether or not it actually is now. We can't 14512 // do this lazily, because the result might depend on things that change 14513 // later, such as which constexpr functions happen to be defined. 14514 SmallVector<PartialDiagnosticAt, 8> Notes; 14515 if (!getLangOpts().CPlusPlus11) { 14516 // Prior to C++11, in contexts where a constant initializer is required, 14517 // the set of valid constant initializers is described by syntactic rules 14518 // in [expr.const]p2-6. 14519 // FIXME: Stricter checking for these rules would be useful for constinit / 14520 // -Wglobal-constructors. 14521 HasConstInit = checkConstInit(); 14522 14523 // Compute and cache the constant value, and remember that we have a 14524 // constant initializer. 14525 if (HasConstInit) { 14526 (void)var->checkForConstantInitialization(Notes); 14527 Notes.clear(); 14528 } else if (CacheCulprit) { 14529 Notes.emplace_back(CacheCulprit->getExprLoc(), 14530 PDiag(diag::note_invalid_subexpr_in_const_expr)); 14531 Notes.back().second << CacheCulprit->getSourceRange(); 14532 } 14533 } else { 14534 // Evaluate the initializer to see if it's a constant initializer. 14535 HasConstInit = var->checkForConstantInitialization(Notes); 14536 } 14537 14538 if (HasConstInit) { 14539 // FIXME: Consider replacing the initializer with a ConstantExpr. 14540 } else if (var->isConstexpr()) { 14541 SourceLocation DiagLoc = var->getLocation(); 14542 // If the note doesn't add any useful information other than a source 14543 // location, fold it into the primary diagnostic. 14544 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14545 diag::note_invalid_subexpr_in_const_expr) { 14546 DiagLoc = Notes[0].first; 14547 Notes.clear(); 14548 } 14549 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 14550 << var << Init->getSourceRange(); 14551 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14552 Diag(Notes[I].first, Notes[I].second); 14553 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 14554 auto *Attr = var->getAttr<ConstInitAttr>(); 14555 Diag(var->getLocation(), diag::err_require_constant_init_failed) 14556 << Init->getSourceRange(); 14557 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 14558 << Attr->getRange() << Attr->isConstinit(); 14559 for (auto &it : Notes) 14560 Diag(it.first, it.second); 14561 } else if (IsGlobal && 14562 !getDiagnostics().isIgnored(diag::warn_global_constructor, 14563 var->getLocation())) { 14564 // Warn about globals which don't have a constant initializer. Don't 14565 // warn about globals with a non-trivial destructor because we already 14566 // warned about them. 14567 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 14568 if (!(RD && !RD->hasTrivialDestructor())) { 14569 // checkConstInit() here permits trivial default initialization even in 14570 // C++11 onwards, where such an initializer is not a constant initializer 14571 // but nonetheless doesn't require a global constructor. 14572 if (!checkConstInit()) 14573 Diag(var->getLocation(), diag::warn_global_constructor) 14574 << Init->getSourceRange(); 14575 } 14576 } 14577 } 14578 14579 // Apply section attributes and pragmas to global variables. 14580 if (GlobalStorage && var->isThisDeclarationADefinition() && 14581 !inTemplateInstantiation()) { 14582 PragmaStack<StringLiteral *> *Stack = nullptr; 14583 int SectionFlags = ASTContext::PSF_Read; 14584 bool MSVCEnv = 14585 Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment(); 14586 std::optional<QualType::NonConstantStorageReason> Reason; 14587 if (HasConstInit && 14588 !(Reason = var->getType().isNonConstantStorage(Context, true, false))) { 14589 Stack = &ConstSegStack; 14590 } else { 14591 SectionFlags |= ASTContext::PSF_Write; 14592 Stack = var->hasInit() && HasConstInit ? &DataSegStack : &BSSSegStack; 14593 } 14594 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 14595 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 14596 SectionFlags |= ASTContext::PSF_Implicit; 14597 UnifySection(SA->getName(), SectionFlags, var); 14598 } else if (Stack->CurrentValue) { 14599 if (Stack != &ConstSegStack && MSVCEnv && 14600 ConstSegStack.CurrentValue != ConstSegStack.DefaultValue && 14601 var->getType().isConstQualified()) { 14602 assert((!Reason || Reason != QualType::NonConstantStorageReason:: 14603 NonConstNonReferenceType) && 14604 "This case should've already been handled elsewhere"); 14605 Diag(var->getLocation(), diag::warn_section_msvc_compat) 14606 << var << ConstSegStack.CurrentValue << (int)(!HasConstInit 14607 ? QualType::NonConstantStorageReason::NonTrivialCtor 14608 : *Reason); 14609 } 14610 SectionFlags |= ASTContext::PSF_Implicit; 14611 auto SectionName = Stack->CurrentValue->getString(); 14612 var->addAttr(SectionAttr::CreateImplicit(Context, SectionName, 14613 Stack->CurrentPragmaLocation, 14614 SectionAttr::Declspec_allocate)); 14615 if (UnifySection(SectionName, SectionFlags, var)) 14616 var->dropAttr<SectionAttr>(); 14617 } 14618 14619 // Apply the init_seg attribute if this has an initializer. If the 14620 // initializer turns out to not be dynamic, we'll end up ignoring this 14621 // attribute. 14622 if (CurInitSeg && var->getInit()) 14623 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 14624 CurInitSegLoc)); 14625 } 14626 14627 // All the following checks are C++ only. 14628 if (!getLangOpts().CPlusPlus) { 14629 // If this variable must be emitted, add it as an initializer for the 14630 // current module. 14631 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14632 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14633 return; 14634 } 14635 14636 // Require the destructor. 14637 if (!type->isDependentType()) 14638 if (const RecordType *recordType = baseType->getAs<RecordType>()) 14639 FinalizeVarWithDestructor(var, recordType); 14640 14641 // If this variable must be emitted, add it as an initializer for the current 14642 // module. 14643 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 14644 Context.addModuleInitializer(ModuleScopes.back().Module, var); 14645 14646 // Build the bindings if this is a structured binding declaration. 14647 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 14648 CheckCompleteDecompositionDeclaration(DD); 14649 } 14650 14651 /// Check if VD needs to be dllexport/dllimport due to being in a 14652 /// dllexport/import function. 14653 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 14654 assert(VD->isStaticLocal()); 14655 14656 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14657 14658 // Find outermost function when VD is in lambda function. 14659 while (FD && !getDLLAttr(FD) && 14660 !FD->hasAttr<DLLExportStaticLocalAttr>() && 14661 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 14662 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 14663 } 14664 14665 if (!FD) 14666 return; 14667 14668 // Static locals inherit dll attributes from their function. 14669 if (Attr *A = getDLLAttr(FD)) { 14670 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 14671 NewAttr->setInherited(true); 14672 VD->addAttr(NewAttr); 14673 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 14674 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 14675 NewAttr->setInherited(true); 14676 VD->addAttr(NewAttr); 14677 14678 // Export this function to enforce exporting this static variable even 14679 // if it is not used in this compilation unit. 14680 if (!FD->hasAttr<DLLExportAttr>()) 14681 FD->addAttr(NewAttr); 14682 14683 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 14684 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 14685 NewAttr->setInherited(true); 14686 VD->addAttr(NewAttr); 14687 } 14688 } 14689 14690 void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) { 14691 assert(VD->getTLSKind()); 14692 14693 // Perform TLS alignment check here after attributes attached to the variable 14694 // which may affect the alignment have been processed. Only perform the check 14695 // if the target has a maximum TLS alignment (zero means no constraints). 14696 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 14697 // Protect the check so that it's not performed on dependent types and 14698 // dependent alignments (we can't determine the alignment in that case). 14699 if (!VD->hasDependentAlignment()) { 14700 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 14701 if (Context.getDeclAlign(VD) > MaxAlignChars) { 14702 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 14703 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 14704 << (unsigned)MaxAlignChars.getQuantity(); 14705 } 14706 } 14707 } 14708 } 14709 14710 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 14711 /// any semantic actions necessary after any initializer has been attached. 14712 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 14713 // Note that we are no longer parsing the initializer for this declaration. 14714 ParsingInitForAutoVars.erase(ThisDecl); 14715 14716 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 14717 if (!VD) 14718 return; 14719 14720 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 14721 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 14722 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 14723 if (PragmaClangBSSSection.Valid) 14724 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 14725 Context, PragmaClangBSSSection.SectionName, 14726 PragmaClangBSSSection.PragmaLocation)); 14727 if (PragmaClangDataSection.Valid) 14728 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 14729 Context, PragmaClangDataSection.SectionName, 14730 PragmaClangDataSection.PragmaLocation)); 14731 if (PragmaClangRodataSection.Valid) 14732 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 14733 Context, PragmaClangRodataSection.SectionName, 14734 PragmaClangRodataSection.PragmaLocation)); 14735 if (PragmaClangRelroSection.Valid) 14736 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 14737 Context, PragmaClangRelroSection.SectionName, 14738 PragmaClangRelroSection.PragmaLocation)); 14739 } 14740 14741 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 14742 for (auto *BD : DD->bindings()) { 14743 FinalizeDeclaration(BD); 14744 } 14745 } 14746 14747 checkAttributesAfterMerging(*this, *VD); 14748 14749 if (VD->isStaticLocal()) 14750 CheckStaticLocalForDllExport(VD); 14751 14752 if (VD->getTLSKind()) 14753 CheckThreadLocalForLargeAlignment(VD); 14754 14755 // Perform check for initializers of device-side global variables. 14756 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 14757 // 7.5). We must also apply the same checks to all __shared__ 14758 // variables whether they are local or not. CUDA also allows 14759 // constant initializers for __constant__ and __device__ variables. 14760 if (getLangOpts().CUDA) 14761 checkAllowedCUDAInitializer(VD); 14762 14763 // Grab the dllimport or dllexport attribute off of the VarDecl. 14764 const InheritableAttr *DLLAttr = getDLLAttr(VD); 14765 14766 // Imported static data members cannot be defined out-of-line. 14767 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 14768 if (VD->isStaticDataMember() && VD->isOutOfLine() && 14769 VD->isThisDeclarationADefinition()) { 14770 // We allow definitions of dllimport class template static data members 14771 // with a warning. 14772 CXXRecordDecl *Context = 14773 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 14774 bool IsClassTemplateMember = 14775 isa<ClassTemplatePartialSpecializationDecl>(Context) || 14776 Context->getDescribedClassTemplate(); 14777 14778 Diag(VD->getLocation(), 14779 IsClassTemplateMember 14780 ? diag::warn_attribute_dllimport_static_field_definition 14781 : diag::err_attribute_dllimport_static_field_definition); 14782 Diag(IA->getLocation(), diag::note_attribute); 14783 if (!IsClassTemplateMember) 14784 VD->setInvalidDecl(); 14785 } 14786 } 14787 14788 // dllimport/dllexport variables cannot be thread local, their TLS index 14789 // isn't exported with the variable. 14790 if (DLLAttr && VD->getTLSKind()) { 14791 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 14792 if (F && getDLLAttr(F)) { 14793 assert(VD->isStaticLocal()); 14794 // But if this is a static local in a dlimport/dllexport function, the 14795 // function will never be inlined, which means the var would never be 14796 // imported, so having it marked import/export is safe. 14797 } else { 14798 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 14799 << DLLAttr; 14800 VD->setInvalidDecl(); 14801 } 14802 } 14803 14804 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 14805 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14806 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14807 << Attr; 14808 VD->dropAttr<UsedAttr>(); 14809 } 14810 } 14811 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 14812 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 14813 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 14814 << Attr; 14815 VD->dropAttr<RetainAttr>(); 14816 } 14817 } 14818 14819 const DeclContext *DC = VD->getDeclContext(); 14820 // If there's a #pragma GCC visibility in scope, and this isn't a class 14821 // member, set the visibility of this variable. 14822 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 14823 AddPushedVisibilityAttribute(VD); 14824 14825 // FIXME: Warn on unused var template partial specializations. 14826 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 14827 MarkUnusedFileScopedDecl(VD); 14828 14829 // Now we have parsed the initializer and can update the table of magic 14830 // tag values. 14831 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 14832 !VD->getType()->isIntegralOrEnumerationType()) 14833 return; 14834 14835 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 14836 const Expr *MagicValueExpr = VD->getInit(); 14837 if (!MagicValueExpr) { 14838 continue; 14839 } 14840 std::optional<llvm::APSInt> MagicValueInt; 14841 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 14842 Diag(I->getRange().getBegin(), 14843 diag::err_type_tag_for_datatype_not_ice) 14844 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14845 continue; 14846 } 14847 if (MagicValueInt->getActiveBits() > 64) { 14848 Diag(I->getRange().getBegin(), 14849 diag::err_type_tag_for_datatype_too_large) 14850 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 14851 continue; 14852 } 14853 uint64_t MagicValue = MagicValueInt->getZExtValue(); 14854 RegisterTypeTagForDatatype(I->getArgumentKind(), 14855 MagicValue, 14856 I->getMatchingCType(), 14857 I->getLayoutCompatible(), 14858 I->getMustBeNull()); 14859 } 14860 } 14861 14862 static bool hasDeducedAuto(DeclaratorDecl *DD) { 14863 auto *VD = dyn_cast<VarDecl>(DD); 14864 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 14865 } 14866 14867 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 14868 ArrayRef<Decl *> Group) { 14869 SmallVector<Decl*, 8> Decls; 14870 14871 if (DS.isTypeSpecOwned()) 14872 Decls.push_back(DS.getRepAsDecl()); 14873 14874 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 14875 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 14876 bool DiagnosedMultipleDecomps = false; 14877 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 14878 bool DiagnosedNonDeducedAuto = false; 14879 14880 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14881 if (Decl *D = Group[i]) { 14882 // Check if the Decl has been declared in '#pragma omp declare target' 14883 // directive and has static storage duration. 14884 if (auto *VD = dyn_cast<VarDecl>(D); 14885 LangOpts.OpenMP && VD && VD->hasAttr<OMPDeclareTargetDeclAttr>() && 14886 VD->hasGlobalStorage()) 14887 ActOnOpenMPDeclareTargetInitializer(D); 14888 // For declarators, there are some additional syntactic-ish checks we need 14889 // to perform. 14890 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 14891 if (!FirstDeclaratorInGroup) 14892 FirstDeclaratorInGroup = DD; 14893 if (!FirstDecompDeclaratorInGroup) 14894 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 14895 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 14896 !hasDeducedAuto(DD)) 14897 FirstNonDeducedAutoInGroup = DD; 14898 14899 if (FirstDeclaratorInGroup != DD) { 14900 // A decomposition declaration cannot be combined with any other 14901 // declaration in the same group. 14902 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 14903 Diag(FirstDecompDeclaratorInGroup->getLocation(), 14904 diag::err_decomp_decl_not_alone) 14905 << FirstDeclaratorInGroup->getSourceRange() 14906 << DD->getSourceRange(); 14907 DiagnosedMultipleDecomps = true; 14908 } 14909 14910 // A declarator that uses 'auto' in any way other than to declare a 14911 // variable with a deduced type cannot be combined with any other 14912 // declarator in the same group. 14913 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 14914 Diag(FirstNonDeducedAutoInGroup->getLocation(), 14915 diag::err_auto_non_deduced_not_alone) 14916 << FirstNonDeducedAutoInGroup->getType() 14917 ->hasAutoForTrailingReturnType() 14918 << FirstDeclaratorInGroup->getSourceRange() 14919 << DD->getSourceRange(); 14920 DiagnosedNonDeducedAuto = true; 14921 } 14922 } 14923 } 14924 14925 Decls.push_back(D); 14926 } 14927 } 14928 14929 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 14930 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 14931 handleTagNumbering(Tag, S); 14932 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 14933 getLangOpts().CPlusPlus) 14934 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 14935 } 14936 } 14937 14938 return BuildDeclaratorGroup(Decls); 14939 } 14940 14941 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 14942 /// group, performing any necessary semantic checking. 14943 Sema::DeclGroupPtrTy 14944 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 14945 // C++14 [dcl.spec.auto]p7: (DR1347) 14946 // If the type that replaces the placeholder type is not the same in each 14947 // deduction, the program is ill-formed. 14948 if (Group.size() > 1) { 14949 QualType Deduced; 14950 VarDecl *DeducedDecl = nullptr; 14951 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14952 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 14953 if (!D || D->isInvalidDecl()) 14954 break; 14955 DeducedType *DT = D->getType()->getContainedDeducedType(); 14956 if (!DT || DT->getDeducedType().isNull()) 14957 continue; 14958 if (Deduced.isNull()) { 14959 Deduced = DT->getDeducedType(); 14960 DeducedDecl = D; 14961 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 14962 auto *AT = dyn_cast<AutoType>(DT); 14963 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 14964 diag::err_auto_different_deductions) 14965 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 14966 << DeducedDecl->getDeclName() << DT->getDeducedType() 14967 << D->getDeclName(); 14968 if (DeducedDecl->hasInit()) 14969 Dia << DeducedDecl->getInit()->getSourceRange(); 14970 if (D->getInit()) 14971 Dia << D->getInit()->getSourceRange(); 14972 D->setInvalidDecl(); 14973 break; 14974 } 14975 } 14976 } 14977 14978 ActOnDocumentableDecls(Group); 14979 14980 return DeclGroupPtrTy::make( 14981 DeclGroupRef::Create(Context, Group.data(), Group.size())); 14982 } 14983 14984 void Sema::ActOnDocumentableDecl(Decl *D) { 14985 ActOnDocumentableDecls(D); 14986 } 14987 14988 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 14989 // Don't parse the comment if Doxygen diagnostics are ignored. 14990 if (Group.empty() || !Group[0]) 14991 return; 14992 14993 if (Diags.isIgnored(diag::warn_doc_param_not_found, 14994 Group[0]->getLocation()) && 14995 Diags.isIgnored(diag::warn_unknown_comment_command_name, 14996 Group[0]->getLocation())) 14997 return; 14998 14999 if (Group.size() >= 2) { 15000 // This is a decl group. Normally it will contain only declarations 15001 // produced from declarator list. But in case we have any definitions or 15002 // additional declaration references: 15003 // 'typedef struct S {} S;' 15004 // 'typedef struct S *S;' 15005 // 'struct S *pS;' 15006 // FinalizeDeclaratorGroup adds these as separate declarations. 15007 Decl *MaybeTagDecl = Group[0]; 15008 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 15009 Group = Group.slice(1); 15010 } 15011 } 15012 15013 // FIMXE: We assume every Decl in the group is in the same file. 15014 // This is false when preprocessor constructs the group from decls in 15015 // different files (e. g. macros or #include). 15016 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 15017 } 15018 15019 /// Common checks for a parameter-declaration that should apply to both function 15020 /// parameters and non-type template parameters. 15021 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 15022 // Check that there are no default arguments inside the type of this 15023 // parameter. 15024 if (getLangOpts().CPlusPlus) 15025 CheckExtraCXXDefaultArguments(D); 15026 15027 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 15028 if (D.getCXXScopeSpec().isSet()) { 15029 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 15030 << D.getCXXScopeSpec().getRange(); 15031 } 15032 15033 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 15034 // simple identifier except [...irrelevant cases...]. 15035 switch (D.getName().getKind()) { 15036 case UnqualifiedIdKind::IK_Identifier: 15037 break; 15038 15039 case UnqualifiedIdKind::IK_OperatorFunctionId: 15040 case UnqualifiedIdKind::IK_ConversionFunctionId: 15041 case UnqualifiedIdKind::IK_LiteralOperatorId: 15042 case UnqualifiedIdKind::IK_ConstructorName: 15043 case UnqualifiedIdKind::IK_DestructorName: 15044 case UnqualifiedIdKind::IK_ImplicitSelfParam: 15045 case UnqualifiedIdKind::IK_DeductionGuideName: 15046 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 15047 << GetNameForDeclarator(D).getName(); 15048 break; 15049 15050 case UnqualifiedIdKind::IK_TemplateId: 15051 case UnqualifiedIdKind::IK_ConstructorTemplateId: 15052 // GetNameForDeclarator would not produce a useful name in this case. 15053 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 15054 break; 15055 } 15056 } 15057 15058 static void CheckExplicitObjectParameter(Sema &S, ParmVarDecl *P, 15059 SourceLocation ExplicitThisLoc) { 15060 if (!ExplicitThisLoc.isValid()) 15061 return; 15062 assert(S.getLangOpts().CPlusPlus && 15063 "explicit parameter in non-cplusplus mode"); 15064 if (!S.getLangOpts().CPlusPlus23) 15065 S.Diag(ExplicitThisLoc, diag::err_cxx20_deducing_this) 15066 << P->getSourceRange(); 15067 15068 // C++2b [dcl.fct/7] An explicit object parameter shall not be a function 15069 // parameter pack. 15070 if (P->isParameterPack()) { 15071 S.Diag(P->getBeginLoc(), diag::err_explicit_object_parameter_pack) 15072 << P->getSourceRange(); 15073 return; 15074 } 15075 P->setExplicitObjectParameterLoc(ExplicitThisLoc); 15076 if (LambdaScopeInfo *LSI = S.getCurLambda()) 15077 LSI->ExplicitObjectParameter = P; 15078 } 15079 15080 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 15081 /// to introduce parameters into function prototype scope. 15082 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D, 15083 SourceLocation ExplicitThisLoc) { 15084 const DeclSpec &DS = D.getDeclSpec(); 15085 15086 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 15087 15088 // C++03 [dcl.stc]p2 also permits 'auto'. 15089 StorageClass SC = SC_None; 15090 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 15091 SC = SC_Register; 15092 // In C++11, the 'register' storage class specifier is deprecated. 15093 // In C++17, it is not allowed, but we tolerate it as an extension. 15094 if (getLangOpts().CPlusPlus11) { 15095 Diag(DS.getStorageClassSpecLoc(), 15096 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 15097 : diag::warn_deprecated_register) 15098 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 15099 } 15100 } else if (getLangOpts().CPlusPlus && 15101 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 15102 SC = SC_Auto; 15103 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 15104 Diag(DS.getStorageClassSpecLoc(), 15105 diag::err_invalid_storage_class_in_func_decl); 15106 D.getMutableDeclSpec().ClearStorageClassSpecs(); 15107 } 15108 15109 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 15110 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 15111 << DeclSpec::getSpecifierName(TSCS); 15112 if (DS.isInlineSpecified()) 15113 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 15114 << getLangOpts().CPlusPlus17; 15115 if (DS.hasConstexprSpecifier()) 15116 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 15117 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 15118 15119 DiagnoseFunctionSpecifiers(DS); 15120 15121 CheckFunctionOrTemplateParamDeclarator(S, D); 15122 15123 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 15124 QualType parmDeclType = TInfo->getType(); 15125 15126 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 15127 IdentifierInfo *II = D.getIdentifier(); 15128 if (II) { 15129 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 15130 ForVisibleRedeclaration); 15131 LookupName(R, S); 15132 if (!R.empty()) { 15133 NamedDecl *PrevDecl = *R.begin(); 15134 if (R.isSingleResult() && PrevDecl->isTemplateParameter()) { 15135 // Maybe we will complain about the shadowed template parameter. 15136 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15137 // Just pretend that we didn't see the previous declaration. 15138 PrevDecl = nullptr; 15139 } 15140 if (PrevDecl && S->isDeclScope(PrevDecl)) { 15141 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 15142 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15143 // Recover by removing the name 15144 II = nullptr; 15145 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 15146 D.setInvalidType(true); 15147 } 15148 } 15149 } 15150 15151 // Temporarily put parameter variables in the translation unit, not 15152 // the enclosing context. This prevents them from accidentally 15153 // looking like class members in C++. 15154 ParmVarDecl *New = 15155 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 15156 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 15157 15158 if (D.isInvalidType()) 15159 New->setInvalidDecl(); 15160 15161 CheckExplicitObjectParameter(*this, New, ExplicitThisLoc); 15162 15163 assert(S->isFunctionPrototypeScope()); 15164 assert(S->getFunctionPrototypeDepth() >= 1); 15165 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 15166 S->getNextFunctionPrototypeIndex()); 15167 15168 // Add the parameter declaration into this scope. 15169 S->AddDecl(New); 15170 if (II) 15171 IdResolver.AddDecl(New); 15172 15173 ProcessDeclAttributes(S, New, D); 15174 15175 if (D.getDeclSpec().isModulePrivateSpecified()) 15176 Diag(New->getLocation(), diag::err_module_private_local) 15177 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15178 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 15179 15180 if (New->hasAttr<BlocksAttr>()) { 15181 Diag(New->getLocation(), diag::err_block_on_nonlocal); 15182 } 15183 15184 if (getLangOpts().OpenCL) 15185 deduceOpenCLAddressSpace(New); 15186 15187 return New; 15188 } 15189 15190 /// Synthesizes a variable for a parameter arising from a 15191 /// typedef. 15192 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 15193 SourceLocation Loc, 15194 QualType T) { 15195 /* FIXME: setting StartLoc == Loc. 15196 Would it be worth to modify callers so as to provide proper source 15197 location for the unnamed parameters, embedding the parameter's type? */ 15198 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 15199 T, Context.getTrivialTypeSourceInfo(T, Loc), 15200 SC_None, nullptr); 15201 Param->setImplicit(); 15202 return Param; 15203 } 15204 15205 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 15206 // Don't diagnose unused-parameter errors in template instantiations; we 15207 // will already have done so in the template itself. 15208 if (inTemplateInstantiation()) 15209 return; 15210 15211 for (const ParmVarDecl *Parameter : Parameters) { 15212 if (!Parameter->isReferenced() && Parameter->getDeclName() && 15213 !Parameter->hasAttr<UnusedAttr>() && 15214 !Parameter->getIdentifier()->isPlaceholder()) { 15215 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 15216 << Parameter->getDeclName(); 15217 } 15218 } 15219 } 15220 15221 void Sema::DiagnoseSizeOfParametersAndReturnValue( 15222 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 15223 if (LangOpts.NumLargeByValueCopy == 0) // No check. 15224 return; 15225 15226 // Warn if the return value is pass-by-value and larger than the specified 15227 // threshold. 15228 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 15229 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 15230 if (Size > LangOpts.NumLargeByValueCopy) 15231 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 15232 } 15233 15234 // Warn if any parameter is pass-by-value and larger than the specified 15235 // threshold. 15236 for (const ParmVarDecl *Parameter : Parameters) { 15237 QualType T = Parameter->getType(); 15238 if (T->isDependentType() || !T.isPODType(Context)) 15239 continue; 15240 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 15241 if (Size > LangOpts.NumLargeByValueCopy) 15242 Diag(Parameter->getLocation(), diag::warn_parameter_size) 15243 << Parameter << Size; 15244 } 15245 } 15246 15247 QualType Sema::AdjustParameterTypeForObjCAutoRefCount(QualType T, 15248 SourceLocation NameLoc, 15249 TypeSourceInfo *TSInfo) { 15250 // In ARC, infer a lifetime qualifier for appropriate parameter types. 15251 if (!getLangOpts().ObjCAutoRefCount || 15252 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType()) 15253 return T; 15254 15255 Qualifiers::ObjCLifetime Lifetime; 15256 15257 // Special cases for arrays: 15258 // - if it's const, use __unsafe_unretained 15259 // - otherwise, it's an error 15260 if (T->isArrayType()) { 15261 if (!T.isConstQualified()) { 15262 if (DelayedDiagnostics.shouldDelayDiagnostics()) 15263 DelayedDiagnostics.add(sema::DelayedDiagnostic::makeForbiddenType( 15264 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 15265 else 15266 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 15267 << TSInfo->getTypeLoc().getSourceRange(); 15268 } 15269 Lifetime = Qualifiers::OCL_ExplicitNone; 15270 } else { 15271 Lifetime = T->getObjCARCImplicitLifetime(); 15272 } 15273 T = Context.getLifetimeQualifiedType(T, Lifetime); 15274 15275 return T; 15276 } 15277 15278 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 15279 SourceLocation NameLoc, IdentifierInfo *Name, 15280 QualType T, TypeSourceInfo *TSInfo, 15281 StorageClass SC) { 15282 // In ARC, infer a lifetime qualifier for appropriate parameter types. 15283 if (getLangOpts().ObjCAutoRefCount && 15284 T.getObjCLifetime() == Qualifiers::OCL_None && 15285 T->isObjCLifetimeType()) { 15286 15287 Qualifiers::ObjCLifetime lifetime; 15288 15289 // Special cases for arrays: 15290 // - if it's const, use __unsafe_unretained 15291 // - otherwise, it's an error 15292 if (T->isArrayType()) { 15293 if (!T.isConstQualified()) { 15294 if (DelayedDiagnostics.shouldDelayDiagnostics()) 15295 DelayedDiagnostics.add( 15296 sema::DelayedDiagnostic::makeForbiddenType( 15297 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 15298 else 15299 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 15300 << TSInfo->getTypeLoc().getSourceRange(); 15301 } 15302 lifetime = Qualifiers::OCL_ExplicitNone; 15303 } else { 15304 lifetime = T->getObjCARCImplicitLifetime(); 15305 } 15306 T = Context.getLifetimeQualifiedType(T, lifetime); 15307 } 15308 15309 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 15310 Context.getAdjustedParameterType(T), 15311 TSInfo, SC, nullptr); 15312 15313 // Make a note if we created a new pack in the scope of a lambda, so that 15314 // we know that references to that pack must also be expanded within the 15315 // lambda scope. 15316 if (New->isParameterPack()) 15317 if (auto *LSI = getEnclosingLambda()) 15318 LSI->LocalPacks.push_back(New); 15319 15320 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 15321 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 15322 checkNonTrivialCUnion(New->getType(), New->getLocation(), 15323 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 15324 15325 // Parameter declarators cannot be interface types. All ObjC objects are 15326 // passed by reference. 15327 if (T->isObjCObjectType()) { 15328 SourceLocation TypeEndLoc = 15329 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 15330 Diag(NameLoc, 15331 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 15332 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 15333 T = Context.getObjCObjectPointerType(T); 15334 New->setType(T); 15335 } 15336 15337 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 15338 // duration shall not be qualified by an address-space qualifier." 15339 // Since all parameters have automatic store duration, they can not have 15340 // an address space. 15341 if (T.getAddressSpace() != LangAS::Default && 15342 // OpenCL allows function arguments declared to be an array of a type 15343 // to be qualified with an address space. 15344 !(getLangOpts().OpenCL && 15345 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private)) && 15346 // WebAssembly allows reference types as parameters. Funcref in particular 15347 // lives in a different address space. 15348 !(T->isFunctionPointerType() && 15349 T.getAddressSpace() == LangAS::wasm_funcref)) { 15350 Diag(NameLoc, diag::err_arg_with_address_space); 15351 New->setInvalidDecl(); 15352 } 15353 15354 // PPC MMA non-pointer types are not allowed as function argument types. 15355 if (Context.getTargetInfo().getTriple().isPPC64() && 15356 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 15357 New->setInvalidDecl(); 15358 } 15359 15360 return New; 15361 } 15362 15363 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 15364 SourceLocation LocAfterDecls) { 15365 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 15366 15367 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration 15368 // in the declaration list shall have at least one declarator, those 15369 // declarators shall only declare identifiers from the identifier list, and 15370 // every identifier in the identifier list shall be declared. 15371 // 15372 // C89 3.7.1p5 "If a declarator includes an identifier list, only the 15373 // identifiers it names shall be declared in the declaration list." 15374 // 15375 // This is why we only diagnose in C99 and later. Note, the other conditions 15376 // listed are checked elsewhere. 15377 if (!FTI.hasPrototype) { 15378 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 15379 --i; 15380 if (FTI.Params[i].Param == nullptr) { 15381 if (getLangOpts().C99) { 15382 SmallString<256> Code; 15383 llvm::raw_svector_ostream(Code) 15384 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 15385 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 15386 << FTI.Params[i].Ident 15387 << FixItHint::CreateInsertion(LocAfterDecls, Code); 15388 } 15389 15390 // Implicitly declare the argument as type 'int' for lack of a better 15391 // type. 15392 AttributeFactory attrs; 15393 DeclSpec DS(attrs); 15394 const char* PrevSpec; // unused 15395 unsigned DiagID; // unused 15396 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 15397 DiagID, Context.getPrintingPolicy()); 15398 // Use the identifier location for the type source range. 15399 DS.SetRangeStart(FTI.Params[i].IdentLoc); 15400 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 15401 Declarator ParamD(DS, ParsedAttributesView::none(), 15402 DeclaratorContext::KNRTypeList); 15403 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 15404 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 15405 } 15406 } 15407 } 15408 } 15409 15410 Decl * 15411 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 15412 MultiTemplateParamsArg TemplateParameterLists, 15413 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 15414 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 15415 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 15416 Scope *ParentScope = FnBodyScope->getParent(); 15417 15418 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 15419 // we define a non-templated function definition, we will create a declaration 15420 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 15421 // The base function declaration will have the equivalent of an `omp declare 15422 // variant` annotation which specifies the mangled definition as a 15423 // specialization function under the OpenMP context defined as part of the 15424 // `omp begin declare variant`. 15425 SmallVector<FunctionDecl *, 4> Bases; 15426 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 15427 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 15428 ParentScope, D, TemplateParameterLists, Bases); 15429 15430 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 15431 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 15432 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 15433 15434 if (!Bases.empty()) 15435 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 15436 15437 return Dcl; 15438 } 15439 15440 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 15441 Consumer.HandleInlineFunctionDefinition(D); 15442 } 15443 15444 static bool FindPossiblePrototype(const FunctionDecl *FD, 15445 const FunctionDecl *&PossiblePrototype) { 15446 for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev; 15447 Prev = Prev->getPreviousDecl()) { 15448 // Ignore any declarations that occur in function or method 15449 // scope, because they aren't visible from the header. 15450 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 15451 continue; 15452 15453 PossiblePrototype = Prev; 15454 return Prev->getType()->isFunctionProtoType(); 15455 } 15456 return false; 15457 } 15458 15459 static bool 15460 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 15461 const FunctionDecl *&PossiblePrototype) { 15462 // Don't warn about invalid declarations. 15463 if (FD->isInvalidDecl()) 15464 return false; 15465 15466 // Or declarations that aren't global. 15467 if (!FD->isGlobal()) 15468 return false; 15469 15470 // Don't warn about C++ member functions. 15471 if (isa<CXXMethodDecl>(FD)) 15472 return false; 15473 15474 // Don't warn about 'main'. 15475 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 15476 if (IdentifierInfo *II = FD->getIdentifier()) 15477 if (II->isStr("main") || II->isStr("efi_main")) 15478 return false; 15479 15480 // Don't warn about inline functions. 15481 if (FD->isInlined()) 15482 return false; 15483 15484 // Don't warn about function templates. 15485 if (FD->getDescribedFunctionTemplate()) 15486 return false; 15487 15488 // Don't warn about function template specializations. 15489 if (FD->isFunctionTemplateSpecialization()) 15490 return false; 15491 15492 // Don't warn for OpenCL kernels. 15493 if (FD->hasAttr<OpenCLKernelAttr>()) 15494 return false; 15495 15496 // Don't warn on explicitly deleted functions. 15497 if (FD->isDeleted()) 15498 return false; 15499 15500 // Don't warn on implicitly local functions (such as having local-typed 15501 // parameters). 15502 if (!FD->isExternallyVisible()) 15503 return false; 15504 15505 // If we were able to find a potential prototype, don't warn. 15506 if (FindPossiblePrototype(FD, PossiblePrototype)) 15507 return false; 15508 15509 return true; 15510 } 15511 15512 void 15513 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 15514 const FunctionDecl *EffectiveDefinition, 15515 SkipBodyInfo *SkipBody) { 15516 const FunctionDecl *Definition = EffectiveDefinition; 15517 if (!Definition && 15518 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 15519 return; 15520 15521 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 15522 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 15523 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 15524 // A merged copy of the same function, instantiated as a member of 15525 // the same class, is OK. 15526 if (declaresSameEntity(OrigFD, OrigDef) && 15527 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 15528 cast<Decl>(FD->getLexicalDeclContext()))) 15529 return; 15530 } 15531 } 15532 } 15533 15534 if (canRedefineFunction(Definition, getLangOpts())) 15535 return; 15536 15537 // Don't emit an error when this is redefinition of a typo-corrected 15538 // definition. 15539 if (TypoCorrectedFunctionDefinitions.count(Definition)) 15540 return; 15541 15542 // If we don't have a visible definition of the function, and it's inline or 15543 // a template, skip the new definition. 15544 if (SkipBody && !hasVisibleDefinition(Definition) && 15545 (Definition->getFormalLinkage() == Linkage::Internal || 15546 Definition->isInlined() || Definition->getDescribedFunctionTemplate() || 15547 Definition->getNumTemplateParameterLists())) { 15548 SkipBody->ShouldSkip = true; 15549 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 15550 if (auto *TD = Definition->getDescribedFunctionTemplate()) 15551 makeMergedDefinitionVisible(TD); 15552 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 15553 return; 15554 } 15555 15556 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 15557 Definition->getStorageClass() == SC_Extern) 15558 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 15559 << FD << getLangOpts().CPlusPlus; 15560 else 15561 Diag(FD->getLocation(), diag::err_redefinition) << FD; 15562 15563 Diag(Definition->getLocation(), diag::note_previous_definition); 15564 FD->setInvalidDecl(); 15565 } 15566 15567 LambdaScopeInfo *Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) { 15568 CXXRecordDecl *LambdaClass = CallOperator->getParent(); 15569 15570 LambdaScopeInfo *LSI = PushLambdaScope(); 15571 LSI->CallOperator = CallOperator; 15572 LSI->Lambda = LambdaClass; 15573 LSI->ReturnType = CallOperator->getReturnType(); 15574 // This function in calls in situation where the context of the call operator 15575 // is not entered, so we set AfterParameterList to false, so that 15576 // `tryCaptureVariable` finds explicit captures in the appropriate context. 15577 LSI->AfterParameterList = false; 15578 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 15579 15580 if (LCD == LCD_None) 15581 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 15582 else if (LCD == LCD_ByCopy) 15583 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 15584 else if (LCD == LCD_ByRef) 15585 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 15586 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 15587 15588 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 15589 LSI->Mutable = !CallOperator->isConst(); 15590 if (CallOperator->isExplicitObjectMemberFunction()) 15591 LSI->ExplicitObjectParameter = CallOperator->getParamDecl(0); 15592 15593 // Add the captures to the LSI so they can be noted as already 15594 // captured within tryCaptureVar. 15595 auto I = LambdaClass->field_begin(); 15596 for (const auto &C : LambdaClass->captures()) { 15597 if (C.capturesVariable()) { 15598 ValueDecl *VD = C.getCapturedVar(); 15599 if (VD->isInitCapture()) 15600 CurrentInstantiationScope->InstantiatedLocal(VD, VD); 15601 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 15602 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 15603 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 15604 /*EllipsisLoc*/C.isPackExpansion() 15605 ? C.getEllipsisLoc() : SourceLocation(), 15606 I->getType(), /*Invalid*/false); 15607 15608 } else if (C.capturesThis()) { 15609 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 15610 C.getCaptureKind() == LCK_StarThis); 15611 } else { 15612 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 15613 I->getType()); 15614 } 15615 ++I; 15616 } 15617 return LSI; 15618 } 15619 15620 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 15621 SkipBodyInfo *SkipBody, 15622 FnBodyKind BodyKind) { 15623 if (!D) { 15624 // Parsing the function declaration failed in some way. Push on a fake scope 15625 // anyway so we can try to parse the function body. 15626 PushFunctionScope(); 15627 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 15628 return D; 15629 } 15630 15631 FunctionDecl *FD = nullptr; 15632 15633 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 15634 FD = FunTmpl->getTemplatedDecl(); 15635 else 15636 FD = cast<FunctionDecl>(D); 15637 15638 // Do not push if it is a lambda because one is already pushed when building 15639 // the lambda in ActOnStartOfLambdaDefinition(). 15640 if (!isLambdaCallOperator(FD)) 15641 // [expr.const]/p14.1 15642 // An expression or conversion is in an immediate function context if it is 15643 // potentially evaluated and either: its innermost enclosing non-block scope 15644 // is a function parameter scope of an immediate function. 15645 PushExpressionEvaluationContext( 15646 FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext 15647 : ExprEvalContexts.back().Context); 15648 15649 // Each ExpressionEvaluationContextRecord also keeps track of whether the 15650 // context is nested in an immediate function context, so smaller contexts 15651 // that appear inside immediate functions (like variable initializers) are 15652 // considered to be inside an immediate function context even though by 15653 // themselves they are not immediate function contexts. But when a new 15654 // function is entered, we need to reset this tracking, since the entered 15655 // function might be not an immediate function. 15656 ExprEvalContexts.back().InImmediateFunctionContext = FD->isConsteval(); 15657 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = 15658 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating(); 15659 15660 // Check for defining attributes before the check for redefinition. 15661 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 15662 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 15663 FD->dropAttr<AliasAttr>(); 15664 FD->setInvalidDecl(); 15665 } 15666 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 15667 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 15668 FD->dropAttr<IFuncAttr>(); 15669 FD->setInvalidDecl(); 15670 } 15671 if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) { 15672 if (!Context.getTargetInfo().hasFeature("fmv") && 15673 !Attr->isDefaultVersion()) { 15674 // If function multi versioning disabled skip parsing function body 15675 // defined with non-default target_version attribute 15676 if (SkipBody) 15677 SkipBody->ShouldSkip = true; 15678 return nullptr; 15679 } 15680 } 15681 15682 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 15683 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 15684 Ctor->isDefaultConstructor() && 15685 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15686 // If this is an MS ABI dllexport default constructor, instantiate any 15687 // default arguments. 15688 InstantiateDefaultCtorDefaultArgs(Ctor); 15689 } 15690 } 15691 15692 // See if this is a redefinition. If 'will have body' (or similar) is already 15693 // set, then these checks were already performed when it was set. 15694 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 15695 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 15696 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 15697 15698 // If we're skipping the body, we're done. Don't enter the scope. 15699 if (SkipBody && SkipBody->ShouldSkip) 15700 return D; 15701 } 15702 15703 // Mark this function as "will have a body eventually". This lets users to 15704 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 15705 // this function. 15706 FD->setWillHaveBody(); 15707 15708 // If we are instantiating a generic lambda call operator, push 15709 // a LambdaScopeInfo onto the function stack. But use the information 15710 // that's already been calculated (ActOnLambdaExpr) to prime the current 15711 // LambdaScopeInfo. 15712 // When the template operator is being specialized, the LambdaScopeInfo, 15713 // has to be properly restored so that tryCaptureVariable doesn't try 15714 // and capture any new variables. In addition when calculating potential 15715 // captures during transformation of nested lambdas, it is necessary to 15716 // have the LSI properly restored. 15717 if (isGenericLambdaCallOperatorSpecialization(FD)) { 15718 assert(inTemplateInstantiation() && 15719 "There should be an active template instantiation on the stack " 15720 "when instantiating a generic lambda!"); 15721 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D)); 15722 } else { 15723 // Enter a new function scope 15724 PushFunctionScope(); 15725 } 15726 15727 // Builtin functions cannot be defined. 15728 if (unsigned BuiltinID = FD->getBuiltinID()) { 15729 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 15730 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 15731 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 15732 FD->setInvalidDecl(); 15733 } 15734 } 15735 15736 // The return type of a function definition must be complete (C99 6.9.1p3). 15737 // C++23 [dcl.fct.def.general]/p2 15738 // The type of [...] the return for a function definition 15739 // shall not be a (possibly cv-qualified) class type that is incomplete 15740 // or abstract within the function body unless the function is deleted. 15741 QualType ResultType = FD->getReturnType(); 15742 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 15743 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 15744 (RequireCompleteType(FD->getLocation(), ResultType, 15745 diag::err_func_def_incomplete_result) || 15746 RequireNonAbstractType(FD->getLocation(), FD->getReturnType(), 15747 diag::err_abstract_type_in_decl, 15748 AbstractReturnType))) 15749 FD->setInvalidDecl(); 15750 15751 if (FnBodyScope) 15752 PushDeclContext(FnBodyScope, FD); 15753 15754 // Check the validity of our function parameters 15755 if (BodyKind != FnBodyKind::Delete) 15756 CheckParmsForFunctionDef(FD->parameters(), 15757 /*CheckParameterNames=*/true); 15758 15759 // Add non-parameter declarations already in the function to the current 15760 // scope. 15761 if (FnBodyScope) { 15762 for (Decl *NPD : FD->decls()) { 15763 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 15764 if (!NonParmDecl) 15765 continue; 15766 assert(!isa<ParmVarDecl>(NonParmDecl) && 15767 "parameters should not be in newly created FD yet"); 15768 15769 // If the decl has a name, make it accessible in the current scope. 15770 if (NonParmDecl->getDeclName()) 15771 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 15772 15773 // Similarly, dive into enums and fish their constants out, making them 15774 // accessible in this scope. 15775 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 15776 for (auto *EI : ED->enumerators()) 15777 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 15778 } 15779 } 15780 } 15781 15782 // Introduce our parameters into the function scope 15783 for (auto *Param : FD->parameters()) { 15784 Param->setOwningFunction(FD); 15785 15786 // If this has an identifier, add it to the scope stack. 15787 if (Param->getIdentifier() && FnBodyScope) { 15788 CheckShadow(FnBodyScope, Param); 15789 15790 PushOnScopeChains(Param, FnBodyScope); 15791 } 15792 } 15793 15794 // C++ [module.import/6] external definitions are not permitted in header 15795 // units. Deleted and Defaulted functions are implicitly inline (but the 15796 // inline state is not set at this point, so check the BodyKind explicitly). 15797 // FIXME: Consider an alternate location for the test where the inlined() 15798 // state is complete. 15799 if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() && 15800 !FD->isInvalidDecl() && !FD->isInlined() && 15801 BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default && 15802 FD->getFormalLinkage() == Linkage::External && !FD->isTemplated() && 15803 !FD->isTemplateInstantiation()) { 15804 assert(FD->isThisDeclarationADefinition()); 15805 Diag(FD->getLocation(), diag::err_extern_def_in_header_unit); 15806 FD->setInvalidDecl(); 15807 } 15808 15809 // Ensure that the function's exception specification is instantiated. 15810 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 15811 ResolveExceptionSpec(D->getLocation(), FPT); 15812 15813 // dllimport cannot be applied to non-inline function definitions. 15814 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 15815 !FD->isTemplateInstantiation()) { 15816 assert(!FD->hasAttr<DLLExportAttr>()); 15817 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 15818 FD->setInvalidDecl(); 15819 return D; 15820 } 15821 // We want to attach documentation to original Decl (which might be 15822 // a function template). 15823 ActOnDocumentableDecl(D); 15824 if (getCurLexicalContext()->isObjCContainer() && 15825 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 15826 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 15827 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 15828 15829 return D; 15830 } 15831 15832 /// Given the set of return statements within a function body, 15833 /// compute the variables that are subject to the named return value 15834 /// optimization. 15835 /// 15836 /// Each of the variables that is subject to the named return value 15837 /// optimization will be marked as NRVO variables in the AST, and any 15838 /// return statement that has a marked NRVO variable as its NRVO candidate can 15839 /// use the named return value optimization. 15840 /// 15841 /// This function applies a very simplistic algorithm for NRVO: if every return 15842 /// statement in the scope of a variable has the same NRVO candidate, that 15843 /// candidate is an NRVO variable. 15844 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 15845 ReturnStmt **Returns = Scope->Returns.data(); 15846 15847 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 15848 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 15849 if (!NRVOCandidate->isNRVOVariable()) 15850 Returns[I]->setNRVOCandidate(nullptr); 15851 } 15852 } 15853 } 15854 15855 bool Sema::canDelayFunctionBody(const Declarator &D) { 15856 // We can't delay parsing the body of a constexpr function template (yet). 15857 if (D.getDeclSpec().hasConstexprSpecifier()) 15858 return false; 15859 15860 // We can't delay parsing the body of a function template with a deduced 15861 // return type (yet). 15862 if (D.getDeclSpec().hasAutoTypeSpec()) { 15863 // If the placeholder introduces a non-deduced trailing return type, 15864 // we can still delay parsing it. 15865 if (D.getNumTypeObjects()) { 15866 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 15867 if (Outer.Kind == DeclaratorChunk::Function && 15868 Outer.Fun.hasTrailingReturnType()) { 15869 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 15870 return Ty.isNull() || !Ty->isUndeducedType(); 15871 } 15872 } 15873 return false; 15874 } 15875 15876 return true; 15877 } 15878 15879 bool Sema::canSkipFunctionBody(Decl *D) { 15880 // We cannot skip the body of a function (or function template) which is 15881 // constexpr, since we may need to evaluate its body in order to parse the 15882 // rest of the file. 15883 // We cannot skip the body of a function with an undeduced return type, 15884 // because any callers of that function need to know the type. 15885 if (const FunctionDecl *FD = D->getAsFunction()) { 15886 if (FD->isConstexpr()) 15887 return false; 15888 // We can't simply call Type::isUndeducedType here, because inside template 15889 // auto can be deduced to a dependent type, which is not considered 15890 // "undeduced". 15891 if (FD->getReturnType()->getContainedDeducedType()) 15892 return false; 15893 } 15894 return Consumer.shouldSkipFunctionBody(D); 15895 } 15896 15897 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 15898 if (!Decl) 15899 return nullptr; 15900 if (FunctionDecl *FD = Decl->getAsFunction()) 15901 FD->setHasSkippedBody(); 15902 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 15903 MD->setHasSkippedBody(); 15904 return Decl; 15905 } 15906 15907 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 15908 return ActOnFinishFunctionBody(D, BodyArg, /*IsInstantiation=*/false); 15909 } 15910 15911 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 15912 /// body. 15913 class ExitFunctionBodyRAII { 15914 public: 15915 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 15916 ~ExitFunctionBodyRAII() { 15917 if (!IsLambda) 15918 S.PopExpressionEvaluationContext(); 15919 } 15920 15921 private: 15922 Sema &S; 15923 bool IsLambda = false; 15924 }; 15925 15926 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 15927 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 15928 15929 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 15930 if (EscapeInfo.count(BD)) 15931 return EscapeInfo[BD]; 15932 15933 bool R = false; 15934 const BlockDecl *CurBD = BD; 15935 15936 do { 15937 R = !CurBD->doesNotEscape(); 15938 if (R) 15939 break; 15940 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 15941 } while (CurBD); 15942 15943 return EscapeInfo[BD] = R; 15944 }; 15945 15946 // If the location where 'self' is implicitly retained is inside a escaping 15947 // block, emit a diagnostic. 15948 for (const std::pair<SourceLocation, const BlockDecl *> &P : 15949 S.ImplicitlyRetainedSelfLocs) 15950 if (IsOrNestedInEscapingBlock(P.second)) 15951 S.Diag(P.first, diag::warn_implicitly_retains_self) 15952 << FixItHint::CreateInsertion(P.first, "self->"); 15953 } 15954 15955 static bool methodHasName(const FunctionDecl *FD, StringRef Name) { 15956 return isa<CXXMethodDecl>(FD) && FD->param_empty() && 15957 FD->getDeclName().isIdentifier() && FD->getName().equals(Name); 15958 } 15959 15960 bool Sema::CanBeGetReturnObject(const FunctionDecl *FD) { 15961 return methodHasName(FD, "get_return_object"); 15962 } 15963 15964 bool Sema::CanBeGetReturnTypeOnAllocFailure(const FunctionDecl *FD) { 15965 return FD->isStatic() && 15966 methodHasName(FD, "get_return_object_on_allocation_failure"); 15967 } 15968 15969 void Sema::CheckCoroutineWrapper(FunctionDecl *FD) { 15970 RecordDecl *RD = FD->getReturnType()->getAsRecordDecl(); 15971 if (!RD || !RD->getUnderlyingDecl()->hasAttr<CoroReturnTypeAttr>()) 15972 return; 15973 // Allow some_promise_type::get_return_object(). 15974 if (CanBeGetReturnObject(FD) || CanBeGetReturnTypeOnAllocFailure(FD)) 15975 return; 15976 if (!FD->hasAttr<CoroWrapperAttr>()) 15977 Diag(FD->getLocation(), diag::err_coroutine_return_type) << RD; 15978 } 15979 15980 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 15981 bool IsInstantiation) { 15982 FunctionScopeInfo *FSI = getCurFunction(); 15983 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 15984 15985 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 15986 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 15987 15988 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 15989 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 15990 15991 // If we skip function body, we can't tell if a function is a coroutine. 15992 if (getLangOpts().Coroutines && FD && !FD->hasSkippedBody()) { 15993 if (FSI->isCoroutine()) 15994 CheckCompletedCoroutineBody(FD, Body); 15995 else 15996 CheckCoroutineWrapper(FD); 15997 } 15998 15999 { 16000 // Do not call PopExpressionEvaluationContext() if it is a lambda because 16001 // one is already popped when finishing the lambda in BuildLambdaExpr(). 16002 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 16003 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 16004 if (FD) { 16005 FD->setBody(Body); 16006 FD->setWillHaveBody(false); 16007 CheckImmediateEscalatingFunctionDefinition(FD, FSI); 16008 16009 if (getLangOpts().CPlusPlus14) { 16010 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 16011 FD->getReturnType()->isUndeducedType()) { 16012 // For a function with a deduced result type to return void, 16013 // the result type as written must be 'auto' or 'decltype(auto)', 16014 // possibly cv-qualified or constrained, but not ref-qualified. 16015 if (!FD->getReturnType()->getAs<AutoType>()) { 16016 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 16017 << FD->getReturnType(); 16018 FD->setInvalidDecl(); 16019 } else { 16020 // Falling off the end of the function is the same as 'return;'. 16021 Expr *Dummy = nullptr; 16022 if (DeduceFunctionTypeFromReturnExpr( 16023 FD, dcl->getLocation(), Dummy, 16024 FD->getReturnType()->getAs<AutoType>())) 16025 FD->setInvalidDecl(); 16026 } 16027 } 16028 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 16029 // In C++11, we don't use 'auto' deduction rules for lambda call 16030 // operators because we don't support return type deduction. 16031 auto *LSI = getCurLambda(); 16032 if (LSI->HasImplicitReturnType) { 16033 deduceClosureReturnType(*LSI); 16034 16035 // C++11 [expr.prim.lambda]p4: 16036 // [...] if there are no return statements in the compound-statement 16037 // [the deduced type is] the type void 16038 QualType RetType = 16039 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 16040 16041 // Update the return type to the deduced type. 16042 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 16043 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 16044 Proto->getExtProtoInfo())); 16045 } 16046 } 16047 16048 // If the function implicitly returns zero (like 'main') or is naked, 16049 // don't complain about missing return statements. 16050 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 16051 WP.disableCheckFallThrough(); 16052 16053 // MSVC permits the use of pure specifier (=0) on function definition, 16054 // defined at class scope, warn about this non-standard construct. 16055 if (getLangOpts().MicrosoftExt && FD->isPureVirtual() && 16056 !FD->isOutOfLine()) 16057 Diag(FD->getLocation(), diag::ext_pure_function_definition); 16058 16059 if (!FD->isInvalidDecl()) { 16060 // Don't diagnose unused parameters of defaulted, deleted or naked 16061 // functions. 16062 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 16063 !FD->hasAttr<NakedAttr>()) 16064 DiagnoseUnusedParameters(FD->parameters()); 16065 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 16066 FD->getReturnType(), FD); 16067 16068 // If this is a structor, we need a vtable. 16069 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 16070 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 16071 else if (CXXDestructorDecl *Destructor = 16072 dyn_cast<CXXDestructorDecl>(FD)) 16073 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 16074 16075 // Try to apply the named return value optimization. We have to check 16076 // if we can do this here because lambdas keep return statements around 16077 // to deduce an implicit return type. 16078 if (FD->getReturnType()->isRecordType() && 16079 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 16080 computeNRVO(Body, FSI); 16081 } 16082 16083 // GNU warning -Wmissing-prototypes: 16084 // Warn if a global function is defined without a previous 16085 // prototype declaration. This warning is issued even if the 16086 // definition itself provides a prototype. The aim is to detect 16087 // global functions that fail to be declared in header files. 16088 const FunctionDecl *PossiblePrototype = nullptr; 16089 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 16090 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 16091 16092 if (PossiblePrototype) { 16093 // We found a declaration that is not a prototype, 16094 // but that could be a zero-parameter prototype 16095 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 16096 TypeLoc TL = TI->getTypeLoc(); 16097 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 16098 Diag(PossiblePrototype->getLocation(), 16099 diag::note_declaration_not_a_prototype) 16100 << (FD->getNumParams() != 0) 16101 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 16102 FTL.getRParenLoc(), "void") 16103 : FixItHint{}); 16104 } 16105 } else { 16106 // Returns true if the token beginning at this Loc is `const`. 16107 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 16108 const LangOptions &LangOpts) { 16109 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 16110 if (LocInfo.first.isInvalid()) 16111 return false; 16112 16113 bool Invalid = false; 16114 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 16115 if (Invalid) 16116 return false; 16117 16118 if (LocInfo.second > Buffer.size()) 16119 return false; 16120 16121 const char *LexStart = Buffer.data() + LocInfo.second; 16122 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 16123 16124 return StartTok.consume_front("const") && 16125 (StartTok.empty() || isWhitespace(StartTok[0]) || 16126 StartTok.starts_with("/*") || StartTok.starts_with("//")); 16127 }; 16128 16129 auto findBeginLoc = [&]() { 16130 // If the return type has `const` qualifier, we want to insert 16131 // `static` before `const` (and not before the typename). 16132 if ((FD->getReturnType()->isAnyPointerType() && 16133 FD->getReturnType()->getPointeeType().isConstQualified()) || 16134 FD->getReturnType().isConstQualified()) { 16135 // But only do this if we can determine where the `const` is. 16136 16137 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 16138 getLangOpts())) 16139 16140 return FD->getBeginLoc(); 16141 } 16142 return FD->getTypeSpecStartLoc(); 16143 }; 16144 Diag(FD->getTypeSpecStartLoc(), 16145 diag::note_static_for_internal_linkage) 16146 << /* function */ 1 16147 << (FD->getStorageClass() == SC_None 16148 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 16149 : FixItHint{}); 16150 } 16151 } 16152 16153 // We might not have found a prototype because we didn't wish to warn on 16154 // the lack of a missing prototype. Try again without the checks for 16155 // whether we want to warn on the missing prototype. 16156 if (!PossiblePrototype) 16157 (void)FindPossiblePrototype(FD, PossiblePrototype); 16158 16159 // If the function being defined does not have a prototype, then we may 16160 // need to diagnose it as changing behavior in C23 because we now know 16161 // whether the function accepts arguments or not. This only handles the 16162 // case where the definition has no prototype but does have parameters 16163 // and either there is no previous potential prototype, or the previous 16164 // potential prototype also has no actual prototype. This handles cases 16165 // like: 16166 // void f(); void f(a) int a; {} 16167 // void g(a) int a; {} 16168 // See MergeFunctionDecl() for other cases of the behavior change 16169 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 16170 // type without a prototype. 16171 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 16172 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 16173 !PossiblePrototype->isImplicit()))) { 16174 // The function definition has parameters, so this will change behavior 16175 // in C23. If there is a possible prototype, it comes before the 16176 // function definition. 16177 // FIXME: The declaration may have already been diagnosed as being 16178 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 16179 // there's no way to test for the "changes behavior" condition in 16180 // SemaType.cpp when forming the declaration's function type. So, we do 16181 // this awkward dance instead. 16182 // 16183 // If we have a possible prototype and it declares a function with a 16184 // prototype, we don't want to diagnose it; if we have a possible 16185 // prototype and it has no prototype, it may have already been 16186 // diagnosed in SemaType.cpp as deprecated depending on whether 16187 // -Wstrict-prototypes is enabled. If we already warned about it being 16188 // deprecated, add a note that it also changes behavior. If we didn't 16189 // warn about it being deprecated (because the diagnostic is not 16190 // enabled), warn now that it is deprecated and changes behavior. 16191 16192 // This K&R C function definition definitely changes behavior in C23, 16193 // so diagnose it. 16194 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior) 16195 << /*definition*/ 1 << /* not supported in C23 */ 0; 16196 16197 // If we have a possible prototype for the function which is a user- 16198 // visible declaration, we already tested that it has no prototype. 16199 // This will change behavior in C23. This gets a warning rather than a 16200 // note because it's the same behavior-changing problem as with the 16201 // definition. 16202 if (PossiblePrototype) 16203 Diag(PossiblePrototype->getLocation(), 16204 diag::warn_non_prototype_changes_behavior) 16205 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 16206 << /*definition*/ 1; 16207 } 16208 16209 // Warn on CPUDispatch with an actual body. 16210 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 16211 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 16212 if (!CmpndBody->body_empty()) 16213 Diag(CmpndBody->body_front()->getBeginLoc(), 16214 diag::warn_dispatch_body_ignored); 16215 16216 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 16217 const CXXMethodDecl *KeyFunction; 16218 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 16219 MD->isVirtual() && 16220 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 16221 MD == KeyFunction->getCanonicalDecl()) { 16222 // Update the key-function state if necessary for this ABI. 16223 if (FD->isInlined() && 16224 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 16225 Context.setNonKeyFunction(MD); 16226 16227 // If the newly-chosen key function is already defined, then we 16228 // need to mark the vtable as used retroactively. 16229 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 16230 const FunctionDecl *Definition; 16231 if (KeyFunction && KeyFunction->isDefined(Definition)) 16232 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 16233 } else { 16234 // We just defined they key function; mark the vtable as used. 16235 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 16236 } 16237 } 16238 } 16239 16240 assert( 16241 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 16242 "Function parsing confused"); 16243 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 16244 assert(MD == getCurMethodDecl() && "Method parsing confused"); 16245 MD->setBody(Body); 16246 if (!MD->isInvalidDecl()) { 16247 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 16248 MD->getReturnType(), MD); 16249 16250 if (Body) 16251 computeNRVO(Body, FSI); 16252 } 16253 if (FSI->ObjCShouldCallSuper) { 16254 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 16255 << MD->getSelector().getAsString(); 16256 FSI->ObjCShouldCallSuper = false; 16257 } 16258 if (FSI->ObjCWarnForNoDesignatedInitChain) { 16259 const ObjCMethodDecl *InitMethod = nullptr; 16260 bool isDesignated = 16261 MD->isDesignatedInitializerForTheInterface(&InitMethod); 16262 assert(isDesignated && InitMethod); 16263 (void)isDesignated; 16264 16265 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 16266 auto IFace = MD->getClassInterface(); 16267 if (!IFace) 16268 return false; 16269 auto SuperD = IFace->getSuperClass(); 16270 if (!SuperD) 16271 return false; 16272 return SuperD->getIdentifier() == 16273 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 16274 }; 16275 // Don't issue this warning for unavailable inits or direct subclasses 16276 // of NSObject. 16277 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 16278 Diag(MD->getLocation(), 16279 diag::warn_objc_designated_init_missing_super_call); 16280 Diag(InitMethod->getLocation(), 16281 diag::note_objc_designated_init_marked_here); 16282 } 16283 FSI->ObjCWarnForNoDesignatedInitChain = false; 16284 } 16285 if (FSI->ObjCWarnForNoInitDelegation) { 16286 // Don't issue this warning for unavaialable inits. 16287 if (!MD->isUnavailable()) 16288 Diag(MD->getLocation(), 16289 diag::warn_objc_secondary_init_missing_init_call); 16290 FSI->ObjCWarnForNoInitDelegation = false; 16291 } 16292 16293 diagnoseImplicitlyRetainedSelf(*this); 16294 } else { 16295 // Parsing the function declaration failed in some way. Pop the fake scope 16296 // we pushed on. 16297 PopFunctionScopeInfo(ActivePolicy, dcl); 16298 return nullptr; 16299 } 16300 16301 if (Body && FSI->HasPotentialAvailabilityViolations) 16302 DiagnoseUnguardedAvailabilityViolations(dcl); 16303 16304 assert(!FSI->ObjCShouldCallSuper && 16305 "This should only be set for ObjC methods, which should have been " 16306 "handled in the block above."); 16307 16308 // Verify and clean out per-function state. 16309 if (Body && (!FD || !FD->isDefaulted())) { 16310 // C++ constructors that have function-try-blocks can't have return 16311 // statements in the handlers of that block. (C++ [except.handle]p14) 16312 // Verify this. 16313 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 16314 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 16315 16316 // Verify that gotos and switch cases don't jump into scopes illegally. 16317 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 16318 DiagnoseInvalidJumps(Body); 16319 16320 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 16321 if (!Destructor->getParent()->isDependentType()) 16322 CheckDestructor(Destructor); 16323 16324 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 16325 Destructor->getParent()); 16326 } 16327 16328 // If any errors have occurred, clear out any temporaries that may have 16329 // been leftover. This ensures that these temporaries won't be picked up 16330 // for deletion in some later function. 16331 if (hasUncompilableErrorOccurred() || 16332 hasAnyUnrecoverableErrorsInThisFunction() || 16333 getDiagnostics().getSuppressAllDiagnostics()) { 16334 DiscardCleanupsInEvaluationContext(); 16335 } 16336 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 16337 // Since the body is valid, issue any analysis-based warnings that are 16338 // enabled. 16339 ActivePolicy = &WP; 16340 } 16341 16342 if (!IsInstantiation && FD && 16343 (FD->isConstexpr() || FD->hasAttr<MSConstexprAttr>()) && 16344 !FD->isInvalidDecl() && 16345 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 16346 FD->setInvalidDecl(); 16347 16348 if (FD && FD->hasAttr<NakedAttr>()) { 16349 for (const Stmt *S : Body->children()) { 16350 // Allow local register variables without initializer as they don't 16351 // require prologue. 16352 bool RegisterVariables = false; 16353 if (auto *DS = dyn_cast<DeclStmt>(S)) { 16354 for (const auto *Decl : DS->decls()) { 16355 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 16356 RegisterVariables = 16357 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 16358 if (!RegisterVariables) 16359 break; 16360 } 16361 } 16362 } 16363 if (RegisterVariables) 16364 continue; 16365 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 16366 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 16367 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 16368 FD->setInvalidDecl(); 16369 break; 16370 } 16371 } 16372 } 16373 16374 assert(ExprCleanupObjects.size() == 16375 ExprEvalContexts.back().NumCleanupObjects && 16376 "Leftover temporaries in function"); 16377 assert(!Cleanup.exprNeedsCleanups() && 16378 "Unaccounted cleanups in function"); 16379 assert(MaybeODRUseExprs.empty() && 16380 "Leftover expressions for odr-use checking"); 16381 } 16382 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 16383 // the declaration context below. Otherwise, we're unable to transform 16384 // 'this' expressions when transforming immediate context functions. 16385 16386 if (!IsInstantiation) 16387 PopDeclContext(); 16388 16389 PopFunctionScopeInfo(ActivePolicy, dcl); 16390 // If any errors have occurred, clear out any temporaries that may have 16391 // been leftover. This ensures that these temporaries won't be picked up for 16392 // deletion in some later function. 16393 if (hasUncompilableErrorOccurred()) { 16394 DiscardCleanupsInEvaluationContext(); 16395 } 16396 16397 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsTargetDevice || 16398 !LangOpts.OMPTargetTriples.empty())) || 16399 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 16400 auto ES = getEmissionStatus(FD); 16401 if (ES == Sema::FunctionEmissionStatus::Emitted || 16402 ES == Sema::FunctionEmissionStatus::Unknown) 16403 DeclsToCheckForDeferredDiags.insert(FD); 16404 } 16405 16406 if (FD && !FD->isDeleted()) 16407 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 16408 16409 return dcl; 16410 } 16411 16412 /// When we finish delayed parsing of an attribute, we must attach it to the 16413 /// relevant Decl. 16414 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 16415 ParsedAttributes &Attrs) { 16416 // Always attach attributes to the underlying decl. 16417 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 16418 D = TD->getTemplatedDecl(); 16419 ProcessDeclAttributeList(S, D, Attrs); 16420 16421 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 16422 if (Method->isStatic()) 16423 checkThisInStaticMemberFunctionAttributes(Method); 16424 } 16425 16426 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 16427 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 16428 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 16429 IdentifierInfo &II, Scope *S) { 16430 // It is not valid to implicitly define a function in C23. 16431 assert(LangOpts.implicitFunctionsAllowed() && 16432 "Implicit function declarations aren't allowed in this language mode"); 16433 16434 // Find the scope in which the identifier is injected and the corresponding 16435 // DeclContext. 16436 // FIXME: C89 does not say what happens if there is no enclosing block scope. 16437 // In that case, we inject the declaration into the translation unit scope 16438 // instead. 16439 Scope *BlockScope = S; 16440 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 16441 BlockScope = BlockScope->getParent(); 16442 16443 // Loop until we find a DeclContext that is either a function/method or the 16444 // translation unit, which are the only two valid places to implicitly define 16445 // a function. This avoids accidentally defining the function within a tag 16446 // declaration, for example. 16447 Scope *ContextScope = BlockScope; 16448 while (!ContextScope->getEntity() || 16449 (!ContextScope->getEntity()->isFunctionOrMethod() && 16450 !ContextScope->getEntity()->isTranslationUnit())) 16451 ContextScope = ContextScope->getParent(); 16452 ContextRAII SavedContext(*this, ContextScope->getEntity()); 16453 16454 // Before we produce a declaration for an implicitly defined 16455 // function, see whether there was a locally-scoped declaration of 16456 // this name as a function or variable. If so, use that 16457 // (non-visible) declaration, and complain about it. 16458 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 16459 if (ExternCPrev) { 16460 // We still need to inject the function into the enclosing block scope so 16461 // that later (non-call) uses can see it. 16462 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 16463 16464 // C89 footnote 38: 16465 // If in fact it is not defined as having type "function returning int", 16466 // the behavior is undefined. 16467 if (!isa<FunctionDecl>(ExternCPrev) || 16468 !Context.typesAreCompatible( 16469 cast<FunctionDecl>(ExternCPrev)->getType(), 16470 Context.getFunctionNoProtoType(Context.IntTy))) { 16471 Diag(Loc, diag::ext_use_out_of_scope_declaration) 16472 << ExternCPrev << !getLangOpts().C99; 16473 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 16474 return ExternCPrev; 16475 } 16476 } 16477 16478 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 16479 unsigned diag_id; 16480 if (II.getName().starts_with("__builtin_")) 16481 diag_id = diag::warn_builtin_unknown; 16482 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 16483 else if (getLangOpts().C99) 16484 diag_id = diag::ext_implicit_function_decl_c99; 16485 else 16486 diag_id = diag::warn_implicit_function_decl; 16487 16488 TypoCorrection Corrected; 16489 // Because typo correction is expensive, only do it if the implicit 16490 // function declaration is going to be treated as an error. 16491 // 16492 // Perform the correction before issuing the main diagnostic, as some 16493 // consumers use typo-correction callbacks to enhance the main diagnostic. 16494 if (S && !ExternCPrev && 16495 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 16496 DeclFilterCCC<FunctionDecl> CCC{}; 16497 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 16498 S, nullptr, CCC, CTK_NonError); 16499 } 16500 16501 Diag(Loc, diag_id) << &II; 16502 if (Corrected) { 16503 // If the correction is going to suggest an implicitly defined function, 16504 // skip the correction as not being a particularly good idea. 16505 bool Diagnose = true; 16506 if (const auto *D = Corrected.getCorrectionDecl()) 16507 Diagnose = !D->isImplicit(); 16508 if (Diagnose) 16509 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 16510 /*ErrorRecovery*/ false); 16511 } 16512 16513 // If we found a prior declaration of this function, don't bother building 16514 // another one. We've already pushed that one into scope, so there's nothing 16515 // more to do. 16516 if (ExternCPrev) 16517 return ExternCPrev; 16518 16519 // Set a Declarator for the implicit definition: int foo(); 16520 const char *Dummy; 16521 AttributeFactory attrFactory; 16522 DeclSpec DS(attrFactory); 16523 unsigned DiagID; 16524 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 16525 Context.getPrintingPolicy()); 16526 (void)Error; // Silence warning. 16527 assert(!Error && "Error setting up implicit decl!"); 16528 SourceLocation NoLoc; 16529 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); 16530 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 16531 /*IsAmbiguous=*/false, 16532 /*LParenLoc=*/NoLoc, 16533 /*Params=*/nullptr, 16534 /*NumParams=*/0, 16535 /*EllipsisLoc=*/NoLoc, 16536 /*RParenLoc=*/NoLoc, 16537 /*RefQualifierIsLvalueRef=*/true, 16538 /*RefQualifierLoc=*/NoLoc, 16539 /*MutableLoc=*/NoLoc, EST_None, 16540 /*ESpecRange=*/SourceRange(), 16541 /*Exceptions=*/nullptr, 16542 /*ExceptionRanges=*/nullptr, 16543 /*NumExceptions=*/0, 16544 /*NoexceptExpr=*/nullptr, 16545 /*ExceptionSpecTokens=*/nullptr, 16546 /*DeclsInPrototype=*/std::nullopt, 16547 Loc, Loc, D), 16548 std::move(DS.getAttributes()), SourceLocation()); 16549 D.SetIdentifier(&II, Loc); 16550 16551 // Insert this function into the enclosing block scope. 16552 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 16553 FD->setImplicit(); 16554 16555 AddKnownFunctionAttributes(FD); 16556 16557 return FD; 16558 } 16559 16560 /// If this function is a C++ replaceable global allocation function 16561 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 16562 /// adds any function attributes that we know a priori based on the standard. 16563 /// 16564 /// We need to check for duplicate attributes both here and where user-written 16565 /// attributes are applied to declarations. 16566 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 16567 FunctionDecl *FD) { 16568 if (FD->isInvalidDecl()) 16569 return; 16570 16571 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 16572 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 16573 return; 16574 16575 std::optional<unsigned> AlignmentParam; 16576 bool IsNothrow = false; 16577 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 16578 return; 16579 16580 // C++2a [basic.stc.dynamic.allocation]p4: 16581 // An allocation function that has a non-throwing exception specification 16582 // indicates failure by returning a null pointer value. Any other allocation 16583 // function never returns a null pointer value and indicates failure only by 16584 // throwing an exception [...] 16585 // 16586 // However, -fcheck-new invalidates this possible assumption, so don't add 16587 // NonNull when that is enabled. 16588 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>() && 16589 !getLangOpts().CheckNew) 16590 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 16591 16592 // C++2a [basic.stc.dynamic.allocation]p2: 16593 // An allocation function attempts to allocate the requested amount of 16594 // storage. [...] If the request succeeds, the value returned by a 16595 // replaceable allocation function is a [...] pointer value p0 different 16596 // from any previously returned value p1 [...] 16597 // 16598 // However, this particular information is being added in codegen, 16599 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 16600 16601 // C++2a [basic.stc.dynamic.allocation]p2: 16602 // An allocation function attempts to allocate the requested amount of 16603 // storage. If it is successful, it returns the address of the start of a 16604 // block of storage whose length in bytes is at least as large as the 16605 // requested size. 16606 if (!FD->hasAttr<AllocSizeAttr>()) { 16607 FD->addAttr(AllocSizeAttr::CreateImplicit( 16608 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 16609 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 16610 } 16611 16612 // C++2a [basic.stc.dynamic.allocation]p3: 16613 // For an allocation function [...], the pointer returned on a successful 16614 // call shall represent the address of storage that is aligned as follows: 16615 // (3.1) If the allocation function takes an argument of type 16616 // std::align_val_t, the storage will have the alignment 16617 // specified by the value of this argument. 16618 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { 16619 FD->addAttr(AllocAlignAttr::CreateImplicit( 16620 Context, ParamIdx(*AlignmentParam, FD), FD->getLocation())); 16621 } 16622 16623 // FIXME: 16624 // C++2a [basic.stc.dynamic.allocation]p3: 16625 // For an allocation function [...], the pointer returned on a successful 16626 // call shall represent the address of storage that is aligned as follows: 16627 // (3.2) Otherwise, if the allocation function is named operator new[], 16628 // the storage is aligned for any object that does not have 16629 // new-extended alignment ([basic.align]) and is no larger than the 16630 // requested size. 16631 // (3.3) Otherwise, the storage is aligned for any object that does not 16632 // have new-extended alignment and is of the requested size. 16633 } 16634 16635 /// Adds any function attributes that we know a priori based on 16636 /// the declaration of this function. 16637 /// 16638 /// These attributes can apply both to implicitly-declared builtins 16639 /// (like __builtin___printf_chk) or to library-declared functions 16640 /// like NSLog or printf. 16641 /// 16642 /// We need to check for duplicate attributes both here and where user-written 16643 /// attributes are applied to declarations. 16644 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 16645 if (FD->isInvalidDecl()) 16646 return; 16647 16648 // If this is a built-in function, map its builtin attributes to 16649 // actual attributes. 16650 if (unsigned BuiltinID = FD->getBuiltinID()) { 16651 // Handle printf-formatting attributes. 16652 unsigned FormatIdx; 16653 bool HasVAListArg; 16654 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 16655 if (!FD->hasAttr<FormatAttr>()) { 16656 const char *fmt = "printf"; 16657 unsigned int NumParams = FD->getNumParams(); 16658 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 16659 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 16660 fmt = "NSString"; 16661 FD->addAttr(FormatAttr::CreateImplicit(Context, 16662 &Context.Idents.get(fmt), 16663 FormatIdx+1, 16664 HasVAListArg ? 0 : FormatIdx+2, 16665 FD->getLocation())); 16666 } 16667 } 16668 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 16669 HasVAListArg)) { 16670 if (!FD->hasAttr<FormatAttr>()) 16671 FD->addAttr(FormatAttr::CreateImplicit(Context, 16672 &Context.Idents.get("scanf"), 16673 FormatIdx+1, 16674 HasVAListArg ? 0 : FormatIdx+2, 16675 FD->getLocation())); 16676 } 16677 16678 // Handle automatically recognized callbacks. 16679 SmallVector<int, 4> Encoding; 16680 if (!FD->hasAttr<CallbackAttr>() && 16681 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 16682 FD->addAttr(CallbackAttr::CreateImplicit( 16683 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 16684 16685 // Mark const if we don't care about errno and/or floating point exceptions 16686 // that are the only thing preventing the function from being const. This 16687 // allows IRgen to use LLVM intrinsics for such functions. 16688 bool NoExceptions = 16689 getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore; 16690 bool ConstWithoutErrnoAndExceptions = 16691 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID); 16692 bool ConstWithoutExceptions = 16693 Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID); 16694 if (!FD->hasAttr<ConstAttr>() && 16695 (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) && 16696 (!ConstWithoutErrnoAndExceptions || 16697 (!getLangOpts().MathErrno && NoExceptions)) && 16698 (!ConstWithoutExceptions || NoExceptions)) 16699 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16700 16701 // We make "fma" on GNU or Windows const because we know it does not set 16702 // errno in those environments even though it could set errno based on the 16703 // C standard. 16704 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 16705 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 16706 !FD->hasAttr<ConstAttr>()) { 16707 switch (BuiltinID) { 16708 case Builtin::BI__builtin_fma: 16709 case Builtin::BI__builtin_fmaf: 16710 case Builtin::BI__builtin_fmal: 16711 case Builtin::BIfma: 16712 case Builtin::BIfmaf: 16713 case Builtin::BIfmal: 16714 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16715 break; 16716 default: 16717 break; 16718 } 16719 } 16720 16721 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 16722 !FD->hasAttr<ReturnsTwiceAttr>()) 16723 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 16724 FD->getLocation())); 16725 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 16726 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16727 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 16728 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 16729 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 16730 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 16731 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 16732 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 16733 // Add the appropriate attribute, depending on the CUDA compilation mode 16734 // and which target the builtin belongs to. For example, during host 16735 // compilation, aux builtins are __device__, while the rest are __host__. 16736 if (getLangOpts().CUDAIsDevice != 16737 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 16738 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 16739 else 16740 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 16741 } 16742 16743 // Add known guaranteed alignment for allocation functions. 16744 switch (BuiltinID) { 16745 case Builtin::BImemalign: 16746 case Builtin::BIaligned_alloc: 16747 if (!FD->hasAttr<AllocAlignAttr>()) 16748 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 16749 FD->getLocation())); 16750 break; 16751 default: 16752 break; 16753 } 16754 16755 // Add allocsize attribute for allocation functions. 16756 switch (BuiltinID) { 16757 case Builtin::BIcalloc: 16758 FD->addAttr(AllocSizeAttr::CreateImplicit( 16759 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 16760 break; 16761 case Builtin::BImemalign: 16762 case Builtin::BIaligned_alloc: 16763 case Builtin::BIrealloc: 16764 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 16765 ParamIdx(), FD->getLocation())); 16766 break; 16767 case Builtin::BImalloc: 16768 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 16769 ParamIdx(), FD->getLocation())); 16770 break; 16771 default: 16772 break; 16773 } 16774 16775 // Add lifetime attribute to std::move, std::fowrard et al. 16776 switch (BuiltinID) { 16777 case Builtin::BIaddressof: 16778 case Builtin::BI__addressof: 16779 case Builtin::BI__builtin_addressof: 16780 case Builtin::BIas_const: 16781 case Builtin::BIforward: 16782 case Builtin::BIforward_like: 16783 case Builtin::BImove: 16784 case Builtin::BImove_if_noexcept: 16785 if (ParmVarDecl *P = FD->getParamDecl(0u); 16786 !P->hasAttr<LifetimeBoundAttr>()) 16787 P->addAttr( 16788 LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation())); 16789 break; 16790 default: 16791 break; 16792 } 16793 } 16794 16795 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 16796 16797 // If C++ exceptions are enabled but we are told extern "C" functions cannot 16798 // throw, add an implicit nothrow attribute to any extern "C" function we come 16799 // across. 16800 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 16801 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 16802 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 16803 if (!FPT || FPT->getExceptionSpecType() == EST_None) 16804 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 16805 } 16806 16807 IdentifierInfo *Name = FD->getIdentifier(); 16808 if (!Name) 16809 return; 16810 if ((!getLangOpts().CPlusPlus && FD->getDeclContext()->isTranslationUnit()) || 16811 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 16812 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 16813 LinkageSpecLanguageIDs::C)) { 16814 // Okay: this could be a libc/libm/Objective-C function we know 16815 // about. 16816 } else 16817 return; 16818 16819 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 16820 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 16821 // target-specific builtins, perhaps? 16822 if (!FD->hasAttr<FormatAttr>()) 16823 FD->addAttr(FormatAttr::CreateImplicit(Context, 16824 &Context.Idents.get("printf"), 2, 16825 Name->isStr("vasprintf") ? 0 : 3, 16826 FD->getLocation())); 16827 } 16828 16829 if (Name->isStr("__CFStringMakeConstantString")) { 16830 // We already have a __builtin___CFStringMakeConstantString, 16831 // but builds that use -fno-constant-cfstrings don't go through that. 16832 if (!FD->hasAttr<FormatArgAttr>()) 16833 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 16834 FD->getLocation())); 16835 } 16836 } 16837 16838 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 16839 TypeSourceInfo *TInfo) { 16840 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 16841 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 16842 16843 if (!TInfo) { 16844 assert(D.isInvalidType() && "no declarator info for valid type"); 16845 TInfo = Context.getTrivialTypeSourceInfo(T); 16846 } 16847 16848 // Scope manipulation handled by caller. 16849 TypedefDecl *NewTD = 16850 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 16851 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 16852 16853 // Bail out immediately if we have an invalid declaration. 16854 if (D.isInvalidType()) { 16855 NewTD->setInvalidDecl(); 16856 return NewTD; 16857 } 16858 16859 if (D.getDeclSpec().isModulePrivateSpecified()) { 16860 if (CurContext->isFunctionOrMethod()) 16861 Diag(NewTD->getLocation(), diag::err_module_private_local) 16862 << 2 << NewTD 16863 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 16864 << FixItHint::CreateRemoval( 16865 D.getDeclSpec().getModulePrivateSpecLoc()); 16866 else 16867 NewTD->setModulePrivate(); 16868 } 16869 16870 // C++ [dcl.typedef]p8: 16871 // If the typedef declaration defines an unnamed class (or 16872 // enum), the first typedef-name declared by the declaration 16873 // to be that class type (or enum type) is used to denote the 16874 // class type (or enum type) for linkage purposes only. 16875 // We need to check whether the type was declared in the declaration. 16876 switch (D.getDeclSpec().getTypeSpecType()) { 16877 case TST_enum: 16878 case TST_struct: 16879 case TST_interface: 16880 case TST_union: 16881 case TST_class: { 16882 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 16883 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 16884 break; 16885 } 16886 16887 default: 16888 break; 16889 } 16890 16891 return NewTD; 16892 } 16893 16894 /// Check that this is a valid underlying type for an enum declaration. 16895 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 16896 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 16897 QualType T = TI->getType(); 16898 16899 if (T->isDependentType()) 16900 return false; 16901 16902 // This doesn't use 'isIntegralType' despite the error message mentioning 16903 // integral type because isIntegralType would also allow enum types in C. 16904 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 16905 if (BT->isInteger()) 16906 return false; 16907 16908 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) 16909 << T << T->isBitIntType(); 16910 } 16911 16912 /// Check whether this is a valid redeclaration of a previous enumeration. 16913 /// \return true if the redeclaration was invalid. 16914 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 16915 QualType EnumUnderlyingTy, bool IsFixed, 16916 const EnumDecl *Prev) { 16917 if (IsScoped != Prev->isScoped()) { 16918 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 16919 << Prev->isScoped(); 16920 Diag(Prev->getLocation(), diag::note_previous_declaration); 16921 return true; 16922 } 16923 16924 if (IsFixed && Prev->isFixed()) { 16925 if (!EnumUnderlyingTy->isDependentType() && 16926 !Prev->getIntegerType()->isDependentType() && 16927 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 16928 Prev->getIntegerType())) { 16929 // TODO: Highlight the underlying type of the redeclaration. 16930 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 16931 << EnumUnderlyingTy << Prev->getIntegerType(); 16932 Diag(Prev->getLocation(), diag::note_previous_declaration) 16933 << Prev->getIntegerTypeRange(); 16934 return true; 16935 } 16936 } else if (IsFixed != Prev->isFixed()) { 16937 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 16938 << Prev->isFixed(); 16939 Diag(Prev->getLocation(), diag::note_previous_declaration); 16940 return true; 16941 } 16942 16943 return false; 16944 } 16945 16946 /// Get diagnostic %select index for tag kind for 16947 /// redeclaration diagnostic message. 16948 /// WARNING: Indexes apply to particular diagnostics only! 16949 /// 16950 /// \returns diagnostic %select index. 16951 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 16952 switch (Tag) { 16953 case TagTypeKind::Struct: 16954 return 0; 16955 case TagTypeKind::Interface: 16956 return 1; 16957 case TagTypeKind::Class: 16958 return 2; 16959 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 16960 } 16961 } 16962 16963 /// Determine if tag kind is a class-key compatible with 16964 /// class for redeclaration (class, struct, or __interface). 16965 /// 16966 /// \returns true iff the tag kind is compatible. 16967 static bool isClassCompatTagKind(TagTypeKind Tag) 16968 { 16969 return Tag == TagTypeKind::Struct || Tag == TagTypeKind::Class || 16970 Tag == TagTypeKind::Interface; 16971 } 16972 16973 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 16974 TagTypeKind TTK) { 16975 if (isa<TypedefDecl>(PrevDecl)) 16976 return NTK_Typedef; 16977 else if (isa<TypeAliasDecl>(PrevDecl)) 16978 return NTK_TypeAlias; 16979 else if (isa<ClassTemplateDecl>(PrevDecl)) 16980 return NTK_Template; 16981 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 16982 return NTK_TypeAliasTemplate; 16983 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 16984 return NTK_TemplateTemplateArgument; 16985 switch (TTK) { 16986 case TagTypeKind::Struct: 16987 case TagTypeKind::Interface: 16988 case TagTypeKind::Class: 16989 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 16990 case TagTypeKind::Union: 16991 return NTK_NonUnion; 16992 case TagTypeKind::Enum: 16993 return NTK_NonEnum; 16994 } 16995 llvm_unreachable("invalid TTK"); 16996 } 16997 16998 /// Determine whether a tag with a given kind is acceptable 16999 /// as a redeclaration of the given tag declaration. 17000 /// 17001 /// \returns true if the new tag kind is acceptable, false otherwise. 17002 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 17003 TagTypeKind NewTag, bool isDefinition, 17004 SourceLocation NewTagLoc, 17005 const IdentifierInfo *Name) { 17006 // C++ [dcl.type.elab]p3: 17007 // The class-key or enum keyword present in the 17008 // elaborated-type-specifier shall agree in kind with the 17009 // declaration to which the name in the elaborated-type-specifier 17010 // refers. This rule also applies to the form of 17011 // elaborated-type-specifier that declares a class-name or 17012 // friend class since it can be construed as referring to the 17013 // definition of the class. Thus, in any 17014 // elaborated-type-specifier, the enum keyword shall be used to 17015 // refer to an enumeration (7.2), the union class-key shall be 17016 // used to refer to a union (clause 9), and either the class or 17017 // struct class-key shall be used to refer to a class (clause 9) 17018 // declared using the class or struct class-key. 17019 TagTypeKind OldTag = Previous->getTagKind(); 17020 if (OldTag != NewTag && 17021 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 17022 return false; 17023 17024 // Tags are compatible, but we might still want to warn on mismatched tags. 17025 // Non-class tags can't be mismatched at this point. 17026 if (!isClassCompatTagKind(NewTag)) 17027 return true; 17028 17029 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 17030 // by our warning analysis. We don't want to warn about mismatches with (eg) 17031 // declarations in system headers that are designed to be specialized, but if 17032 // a user asks us to warn, we should warn if their code contains mismatched 17033 // declarations. 17034 auto IsIgnoredLoc = [&](SourceLocation Loc) { 17035 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 17036 Loc); 17037 }; 17038 if (IsIgnoredLoc(NewTagLoc)) 17039 return true; 17040 17041 auto IsIgnored = [&](const TagDecl *Tag) { 17042 return IsIgnoredLoc(Tag->getLocation()); 17043 }; 17044 while (IsIgnored(Previous)) { 17045 Previous = Previous->getPreviousDecl(); 17046 if (!Previous) 17047 return true; 17048 OldTag = Previous->getTagKind(); 17049 } 17050 17051 bool isTemplate = false; 17052 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 17053 isTemplate = Record->getDescribedClassTemplate(); 17054 17055 if (inTemplateInstantiation()) { 17056 if (OldTag != NewTag) { 17057 // In a template instantiation, do not offer fix-its for tag mismatches 17058 // since they usually mess up the template instead of fixing the problem. 17059 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 17060 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17061 << getRedeclDiagFromTagKind(OldTag); 17062 // FIXME: Note previous location? 17063 } 17064 return true; 17065 } 17066 17067 if (isDefinition) { 17068 // On definitions, check all previous tags and issue a fix-it for each 17069 // one that doesn't match the current tag. 17070 if (Previous->getDefinition()) { 17071 // Don't suggest fix-its for redefinitions. 17072 return true; 17073 } 17074 17075 bool previousMismatch = false; 17076 for (const TagDecl *I : Previous->redecls()) { 17077 if (I->getTagKind() != NewTag) { 17078 // Ignore previous declarations for which the warning was disabled. 17079 if (IsIgnored(I)) 17080 continue; 17081 17082 if (!previousMismatch) { 17083 previousMismatch = true; 17084 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 17085 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17086 << getRedeclDiagFromTagKind(I->getTagKind()); 17087 } 17088 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 17089 << getRedeclDiagFromTagKind(NewTag) 17090 << FixItHint::CreateReplacement(I->getInnerLocStart(), 17091 TypeWithKeyword::getTagTypeKindName(NewTag)); 17092 } 17093 } 17094 return true; 17095 } 17096 17097 // Identify the prevailing tag kind: this is the kind of the definition (if 17098 // there is a non-ignored definition), or otherwise the kind of the prior 17099 // (non-ignored) declaration. 17100 const TagDecl *PrevDef = Previous->getDefinition(); 17101 if (PrevDef && IsIgnored(PrevDef)) 17102 PrevDef = nullptr; 17103 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 17104 if (Redecl->getTagKind() != NewTag) { 17105 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 17106 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 17107 << getRedeclDiagFromTagKind(OldTag); 17108 Diag(Redecl->getLocation(), diag::note_previous_use); 17109 17110 // If there is a previous definition, suggest a fix-it. 17111 if (PrevDef) { 17112 Diag(NewTagLoc, diag::note_struct_class_suggestion) 17113 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 17114 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 17115 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 17116 } 17117 } 17118 17119 return true; 17120 } 17121 17122 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 17123 /// from an outer enclosing namespace or file scope inside a friend declaration. 17124 /// This should provide the commented out code in the following snippet: 17125 /// namespace N { 17126 /// struct X; 17127 /// namespace M { 17128 /// struct Y { friend struct /*N::*/ X; }; 17129 /// } 17130 /// } 17131 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 17132 SourceLocation NameLoc) { 17133 // While the decl is in a namespace, do repeated lookup of that name and see 17134 // if we get the same namespace back. If we do not, continue until 17135 // translation unit scope, at which point we have a fully qualified NNS. 17136 SmallVector<IdentifierInfo *, 4> Namespaces; 17137 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17138 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 17139 // This tag should be declared in a namespace, which can only be enclosed by 17140 // other namespaces. Bail if there's an anonymous namespace in the chain. 17141 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 17142 if (!Namespace || Namespace->isAnonymousNamespace()) 17143 return FixItHint(); 17144 IdentifierInfo *II = Namespace->getIdentifier(); 17145 Namespaces.push_back(II); 17146 NamedDecl *Lookup = SemaRef.LookupSingleName( 17147 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 17148 if (Lookup == Namespace) 17149 break; 17150 } 17151 17152 // Once we have all the namespaces, reverse them to go outermost first, and 17153 // build an NNS. 17154 SmallString<64> Insertion; 17155 llvm::raw_svector_ostream OS(Insertion); 17156 if (DC->isTranslationUnit()) 17157 OS << "::"; 17158 std::reverse(Namespaces.begin(), Namespaces.end()); 17159 for (auto *II : Namespaces) 17160 OS << II->getName() << "::"; 17161 return FixItHint::CreateInsertion(NameLoc, Insertion); 17162 } 17163 17164 /// Determine whether a tag originally declared in context \p OldDC can 17165 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 17166 /// found a declaration in \p OldDC as a previous decl, perhaps through a 17167 /// using-declaration). 17168 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 17169 DeclContext *NewDC) { 17170 OldDC = OldDC->getRedeclContext(); 17171 NewDC = NewDC->getRedeclContext(); 17172 17173 if (OldDC->Equals(NewDC)) 17174 return true; 17175 17176 // In MSVC mode, we allow a redeclaration if the contexts are related (either 17177 // encloses the other). 17178 if (S.getLangOpts().MSVCCompat && 17179 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 17180 return true; 17181 17182 return false; 17183 } 17184 17185 /// This is invoked when we see 'struct foo' or 'struct {'. In the 17186 /// former case, Name will be non-null. In the later case, Name will be null. 17187 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 17188 /// reference/declaration/definition of a tag. 17189 /// 17190 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 17191 /// trailing-type-specifier) other than one in an alias-declaration. 17192 /// 17193 /// \param SkipBody If non-null, will be set to indicate if the caller should 17194 /// skip the definition of this tag and treat it as if it were a declaration. 17195 DeclResult 17196 Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 17197 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 17198 const ParsedAttributesView &Attrs, AccessSpecifier AS, 17199 SourceLocation ModulePrivateLoc, 17200 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 17201 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 17202 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 17203 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 17204 OffsetOfKind OOK, SkipBodyInfo *SkipBody) { 17205 // If this is not a definition, it must have a name. 17206 IdentifierInfo *OrigName = Name; 17207 assert((Name != nullptr || TUK == TUK_Definition) && 17208 "Nameless record must be a definition!"); 17209 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 17210 17211 OwnedDecl = false; 17212 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 17213 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 17214 17215 // FIXME: Check member specializations more carefully. 17216 bool isMemberSpecialization = false; 17217 bool Invalid = false; 17218 17219 // We only need to do this matching if we have template parameters 17220 // or a scope specifier, which also conveniently avoids this work 17221 // for non-C++ cases. 17222 if (TemplateParameterLists.size() > 0 || 17223 (SS.isNotEmpty() && TUK != TUK_Reference)) { 17224 if (TemplateParameterList *TemplateParams = 17225 MatchTemplateParametersToScopeSpecifier( 17226 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 17227 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 17228 if (Kind == TagTypeKind::Enum) { 17229 Diag(KWLoc, diag::err_enum_template); 17230 return true; 17231 } 17232 17233 if (TemplateParams->size() > 0) { 17234 // This is a declaration or definition of a class template (which may 17235 // be a member of another template). 17236 17237 if (Invalid) 17238 return true; 17239 17240 OwnedDecl = false; 17241 DeclResult Result = CheckClassTemplate( 17242 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 17243 AS, ModulePrivateLoc, 17244 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 17245 TemplateParameterLists.data(), SkipBody); 17246 return Result.get(); 17247 } else { 17248 // The "template<>" header is extraneous. 17249 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 17250 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 17251 isMemberSpecialization = true; 17252 } 17253 } 17254 17255 if (!TemplateParameterLists.empty() && isMemberSpecialization && 17256 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 17257 return true; 17258 } 17259 17260 // Figure out the underlying type if this a enum declaration. We need to do 17261 // this early, because it's needed to detect if this is an incompatible 17262 // redeclaration. 17263 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 17264 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 17265 17266 if (Kind == TagTypeKind::Enum) { 17267 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 17268 // No underlying type explicitly specified, or we failed to parse the 17269 // type, default to int. 17270 EnumUnderlying = Context.IntTy.getTypePtr(); 17271 } else if (UnderlyingType.get()) { 17272 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 17273 // integral type; any cv-qualification is ignored. 17274 TypeSourceInfo *TI = nullptr; 17275 GetTypeFromParser(UnderlyingType.get(), &TI); 17276 EnumUnderlying = TI; 17277 17278 if (CheckEnumUnderlyingType(TI)) 17279 // Recover by falling back to int. 17280 EnumUnderlying = Context.IntTy.getTypePtr(); 17281 17282 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 17283 UPPC_FixedUnderlyingType)) 17284 EnumUnderlying = Context.IntTy.getTypePtr(); 17285 17286 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 17287 // For MSVC ABI compatibility, unfixed enums must use an underlying type 17288 // of 'int'. However, if this is an unfixed forward declaration, don't set 17289 // the underlying type unless the user enables -fms-compatibility. This 17290 // makes unfixed forward declared enums incomplete and is more conforming. 17291 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 17292 EnumUnderlying = Context.IntTy.getTypePtr(); 17293 } 17294 } 17295 17296 DeclContext *SearchDC = CurContext; 17297 DeclContext *DC = CurContext; 17298 bool isStdBadAlloc = false; 17299 bool isStdAlignValT = false; 17300 17301 RedeclarationKind Redecl = forRedeclarationInCurContext(); 17302 if (TUK == TUK_Friend || TUK == TUK_Reference) 17303 Redecl = NotForRedeclaration; 17304 17305 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 17306 /// implemented asks for structural equivalence checking, the returned decl 17307 /// here is passed back to the parser, allowing the tag body to be parsed. 17308 auto createTagFromNewDecl = [&]() -> TagDecl * { 17309 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 17310 // If there is an identifier, use the location of the identifier as the 17311 // location of the decl, otherwise use the location of the struct/union 17312 // keyword. 17313 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17314 TagDecl *New = nullptr; 17315 17316 if (Kind == TagTypeKind::Enum) { 17317 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 17318 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 17319 // If this is an undefined enum, bail. 17320 if (TUK != TUK_Definition && !Invalid) 17321 return nullptr; 17322 if (EnumUnderlying) { 17323 EnumDecl *ED = cast<EnumDecl>(New); 17324 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 17325 ED->setIntegerTypeSourceInfo(TI); 17326 else 17327 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 17328 QualType EnumTy = ED->getIntegerType(); 17329 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17330 ? Context.getPromotedIntegerType(EnumTy) 17331 : EnumTy); 17332 } 17333 } else { // struct/union 17334 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17335 nullptr); 17336 } 17337 17338 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 17339 // Add alignment attributes if necessary; these attributes are checked 17340 // when the ASTContext lays out the structure. 17341 // 17342 // It is important for implementing the correct semantics that this 17343 // happen here (in ActOnTag). The #pragma pack stack is 17344 // maintained as a result of parser callbacks which can occur at 17345 // many points during the parsing of a struct declaration (because 17346 // the #pragma tokens are effectively skipped over during the 17347 // parsing of the struct). 17348 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 17349 AddAlignmentAttributesForRecord(RD); 17350 AddMsStructLayoutForRecord(RD); 17351 } 17352 } 17353 New->setLexicalDeclContext(CurContext); 17354 return New; 17355 }; 17356 17357 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 17358 if (Name && SS.isNotEmpty()) { 17359 // We have a nested-name tag ('struct foo::bar'). 17360 17361 // Check for invalid 'foo::'. 17362 if (SS.isInvalid()) { 17363 Name = nullptr; 17364 goto CreateNewDecl; 17365 } 17366 17367 // If this is a friend or a reference to a class in a dependent 17368 // context, don't try to make a decl for it. 17369 if (TUK == TUK_Friend || TUK == TUK_Reference) { 17370 DC = computeDeclContext(SS, false); 17371 if (!DC) { 17372 IsDependent = true; 17373 return true; 17374 } 17375 } else { 17376 DC = computeDeclContext(SS, true); 17377 if (!DC) { 17378 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 17379 << SS.getRange(); 17380 return true; 17381 } 17382 } 17383 17384 if (RequireCompleteDeclContext(SS, DC)) 17385 return true; 17386 17387 SearchDC = DC; 17388 // Look-up name inside 'foo::'. 17389 LookupQualifiedName(Previous, DC); 17390 17391 if (Previous.isAmbiguous()) 17392 return true; 17393 17394 if (Previous.empty()) { 17395 // Name lookup did not find anything. However, if the 17396 // nested-name-specifier refers to the current instantiation, 17397 // and that current instantiation has any dependent base 17398 // classes, we might find something at instantiation time: treat 17399 // this as a dependent elaborated-type-specifier. 17400 // But this only makes any sense for reference-like lookups. 17401 if (Previous.wasNotFoundInCurrentInstantiation() && 17402 (TUK == TUK_Reference || TUK == TUK_Friend)) { 17403 IsDependent = true; 17404 return true; 17405 } 17406 17407 // A tag 'foo::bar' must already exist. 17408 Diag(NameLoc, diag::err_not_tag_in_scope) 17409 << llvm::to_underlying(Kind) << Name << DC << SS.getRange(); 17410 Name = nullptr; 17411 Invalid = true; 17412 goto CreateNewDecl; 17413 } 17414 } else if (Name) { 17415 // C++14 [class.mem]p14: 17416 // If T is the name of a class, then each of the following shall have a 17417 // name different from T: 17418 // -- every member of class T that is itself a type 17419 if (TUK != TUK_Reference && TUK != TUK_Friend && 17420 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 17421 return true; 17422 17423 // If this is a named struct, check to see if there was a previous forward 17424 // declaration or definition. 17425 // FIXME: We're looking into outer scopes here, even when we 17426 // shouldn't be. Doing so can result in ambiguities that we 17427 // shouldn't be diagnosing. 17428 LookupName(Previous, S); 17429 17430 // When declaring or defining a tag, ignore ambiguities introduced 17431 // by types using'ed into this scope. 17432 if (Previous.isAmbiguous() && 17433 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 17434 LookupResult::Filter F = Previous.makeFilter(); 17435 while (F.hasNext()) { 17436 NamedDecl *ND = F.next(); 17437 if (!ND->getDeclContext()->getRedeclContext()->Equals( 17438 SearchDC->getRedeclContext())) 17439 F.erase(); 17440 } 17441 F.done(); 17442 } 17443 17444 // C++11 [namespace.memdef]p3: 17445 // If the name in a friend declaration is neither qualified nor 17446 // a template-id and the declaration is a function or an 17447 // elaborated-type-specifier, the lookup to determine whether 17448 // the entity has been previously declared shall not consider 17449 // any scopes outside the innermost enclosing namespace. 17450 // 17451 // MSVC doesn't implement the above rule for types, so a friend tag 17452 // declaration may be a redeclaration of a type declared in an enclosing 17453 // scope. They do implement this rule for friend functions. 17454 // 17455 // Does it matter that this should be by scope instead of by 17456 // semantic context? 17457 if (!Previous.empty() && TUK == TUK_Friend) { 17458 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 17459 LookupResult::Filter F = Previous.makeFilter(); 17460 bool FriendSawTagOutsideEnclosingNamespace = false; 17461 while (F.hasNext()) { 17462 NamedDecl *ND = F.next(); 17463 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 17464 if (DC->isFileContext() && 17465 !EnclosingNS->Encloses(ND->getDeclContext())) { 17466 if (getLangOpts().MSVCCompat) 17467 FriendSawTagOutsideEnclosingNamespace = true; 17468 else 17469 F.erase(); 17470 } 17471 } 17472 F.done(); 17473 17474 // Diagnose this MSVC extension in the easy case where lookup would have 17475 // unambiguously found something outside the enclosing namespace. 17476 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 17477 NamedDecl *ND = Previous.getFoundDecl(); 17478 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 17479 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 17480 } 17481 } 17482 17483 // Note: there used to be some attempt at recovery here. 17484 if (Previous.isAmbiguous()) 17485 return true; 17486 17487 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 17488 // FIXME: This makes sure that we ignore the contexts associated 17489 // with C structs, unions, and enums when looking for a matching 17490 // tag declaration or definition. See the similar lookup tweak 17491 // in Sema::LookupName; is there a better way to deal with this? 17492 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 17493 SearchDC = SearchDC->getParent(); 17494 } else if (getLangOpts().CPlusPlus) { 17495 // Inside ObjCContainer want to keep it as a lexical decl context but go 17496 // past it (most often to TranslationUnit) to find the semantic decl 17497 // context. 17498 while (isa<ObjCContainerDecl>(SearchDC)) 17499 SearchDC = SearchDC->getParent(); 17500 } 17501 } else if (getLangOpts().CPlusPlus) { 17502 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 17503 // TagDecl the same way as we skip it for named TagDecl. 17504 while (isa<ObjCContainerDecl>(SearchDC)) 17505 SearchDC = SearchDC->getParent(); 17506 } 17507 17508 if (Previous.isSingleResult() && 17509 Previous.getFoundDecl()->isTemplateParameter()) { 17510 // Maybe we will complain about the shadowed template parameter. 17511 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 17512 // Just pretend that we didn't see the previous declaration. 17513 Previous.clear(); 17514 } 17515 17516 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 17517 DC->Equals(getStdNamespace())) { 17518 if (Name->isStr("bad_alloc")) { 17519 // This is a declaration of or a reference to "std::bad_alloc". 17520 isStdBadAlloc = true; 17521 17522 // If std::bad_alloc has been implicitly declared (but made invisible to 17523 // name lookup), fill in this implicit declaration as the previous 17524 // declaration, so that the declarations get chained appropriately. 17525 if (Previous.empty() && StdBadAlloc) 17526 Previous.addDecl(getStdBadAlloc()); 17527 } else if (Name->isStr("align_val_t")) { 17528 isStdAlignValT = true; 17529 if (Previous.empty() && StdAlignValT) 17530 Previous.addDecl(getStdAlignValT()); 17531 } 17532 } 17533 17534 // If we didn't find a previous declaration, and this is a reference 17535 // (or friend reference), move to the correct scope. In C++, we 17536 // also need to do a redeclaration lookup there, just in case 17537 // there's a shadow friend decl. 17538 if (Name && Previous.empty() && 17539 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 17540 if (Invalid) goto CreateNewDecl; 17541 assert(SS.isEmpty()); 17542 17543 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 17544 // C++ [basic.scope.pdecl]p5: 17545 // -- for an elaborated-type-specifier of the form 17546 // 17547 // class-key identifier 17548 // 17549 // if the elaborated-type-specifier is used in the 17550 // decl-specifier-seq or parameter-declaration-clause of a 17551 // function defined in namespace scope, the identifier is 17552 // declared as a class-name in the namespace that contains 17553 // the declaration; otherwise, except as a friend 17554 // declaration, the identifier is declared in the smallest 17555 // non-class, non-function-prototype scope that contains the 17556 // declaration. 17557 // 17558 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 17559 // C structs and unions. 17560 // 17561 // It is an error in C++ to declare (rather than define) an enum 17562 // type, including via an elaborated type specifier. We'll 17563 // diagnose that later; for now, declare the enum in the same 17564 // scope as we would have picked for any other tag type. 17565 // 17566 // GNU C also supports this behavior as part of its incomplete 17567 // enum types extension, while GNU C++ does not. 17568 // 17569 // Find the context where we'll be declaring the tag. 17570 // FIXME: We would like to maintain the current DeclContext as the 17571 // lexical context, 17572 SearchDC = getTagInjectionContext(SearchDC); 17573 17574 // Find the scope where we'll be declaring the tag. 17575 S = getTagInjectionScope(S, getLangOpts()); 17576 } else { 17577 assert(TUK == TUK_Friend); 17578 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(SearchDC); 17579 17580 // C++ [namespace.memdef]p3: 17581 // If a friend declaration in a non-local class first declares a 17582 // class or function, the friend class or function is a member of 17583 // the innermost enclosing namespace. 17584 SearchDC = RD->isLocalClass() ? RD->isLocalClass() 17585 : SearchDC->getEnclosingNamespaceContext(); 17586 } 17587 17588 // In C++, we need to do a redeclaration lookup to properly 17589 // diagnose some problems. 17590 // FIXME: redeclaration lookup is also used (with and without C++) to find a 17591 // hidden declaration so that we don't get ambiguity errors when using a 17592 // type declared by an elaborated-type-specifier. In C that is not correct 17593 // and we should instead merge compatible types found by lookup. 17594 if (getLangOpts().CPlusPlus) { 17595 // FIXME: This can perform qualified lookups into function contexts, 17596 // which are meaningless. 17597 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17598 LookupQualifiedName(Previous, SearchDC); 17599 } else { 17600 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 17601 LookupName(Previous, S); 17602 } 17603 } 17604 17605 // If we have a known previous declaration to use, then use it. 17606 if (Previous.empty() && SkipBody && SkipBody->Previous) 17607 Previous.addDecl(SkipBody->Previous); 17608 17609 if (!Previous.empty()) { 17610 NamedDecl *PrevDecl = Previous.getFoundDecl(); 17611 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 17612 17613 // It's okay to have a tag decl in the same scope as a typedef 17614 // which hides a tag decl in the same scope. Finding this 17615 // with a redeclaration lookup can only actually happen in C++. 17616 // 17617 // This is also okay for elaborated-type-specifiers, which is 17618 // technically forbidden by the current standard but which is 17619 // okay according to the likely resolution of an open issue; 17620 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 17621 if (getLangOpts().CPlusPlus) { 17622 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17623 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 17624 TagDecl *Tag = TT->getDecl(); 17625 if (Tag->getDeclName() == Name && 17626 Tag->getDeclContext()->getRedeclContext() 17627 ->Equals(TD->getDeclContext()->getRedeclContext())) { 17628 PrevDecl = Tag; 17629 Previous.clear(); 17630 Previous.addDecl(Tag); 17631 Previous.resolveKind(); 17632 } 17633 } 17634 } 17635 } 17636 17637 // If this is a redeclaration of a using shadow declaration, it must 17638 // declare a tag in the same context. In MSVC mode, we allow a 17639 // redefinition if either context is within the other. 17640 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 17641 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 17642 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 17643 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 17644 !(OldTag && isAcceptableTagRedeclContext( 17645 *this, OldTag->getDeclContext(), SearchDC))) { 17646 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 17647 Diag(Shadow->getTargetDecl()->getLocation(), 17648 diag::note_using_decl_target); 17649 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 17650 << 0; 17651 // Recover by ignoring the old declaration. 17652 Previous.clear(); 17653 goto CreateNewDecl; 17654 } 17655 } 17656 17657 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 17658 // If this is a use of a previous tag, or if the tag is already declared 17659 // in the same scope (so that the definition/declaration completes or 17660 // rementions the tag), reuse the decl. 17661 if (TUK == TUK_Reference || TUK == TUK_Friend || 17662 isDeclInScope(DirectPrevDecl, SearchDC, S, 17663 SS.isNotEmpty() || isMemberSpecialization)) { 17664 // Make sure that this wasn't declared as an enum and now used as a 17665 // struct or something similar. 17666 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 17667 TUK == TUK_Definition, KWLoc, 17668 Name)) { 17669 bool SafeToContinue = 17670 (PrevTagDecl->getTagKind() != TagTypeKind::Enum && 17671 Kind != TagTypeKind::Enum); 17672 if (SafeToContinue) 17673 Diag(KWLoc, diag::err_use_with_wrong_tag) 17674 << Name 17675 << FixItHint::CreateReplacement(SourceRange(KWLoc), 17676 PrevTagDecl->getKindName()); 17677 else 17678 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 17679 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 17680 17681 if (SafeToContinue) 17682 Kind = PrevTagDecl->getTagKind(); 17683 else { 17684 // Recover by making this an anonymous redefinition. 17685 Name = nullptr; 17686 Previous.clear(); 17687 Invalid = true; 17688 } 17689 } 17690 17691 if (Kind == TagTypeKind::Enum && 17692 PrevTagDecl->getTagKind() == TagTypeKind::Enum) { 17693 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 17694 if (TUK == TUK_Reference || TUK == TUK_Friend) 17695 return PrevTagDecl; 17696 17697 QualType EnumUnderlyingTy; 17698 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 17699 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 17700 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 17701 EnumUnderlyingTy = QualType(T, 0); 17702 17703 // All conflicts with previous declarations are recovered by 17704 // returning the previous declaration, unless this is a definition, 17705 // in which case we want the caller to bail out. 17706 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 17707 ScopedEnum, EnumUnderlyingTy, 17708 IsFixed, PrevEnum)) 17709 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 17710 } 17711 17712 // C++11 [class.mem]p1: 17713 // A member shall not be declared twice in the member-specification, 17714 // except that a nested class or member class template can be declared 17715 // and then later defined. 17716 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 17717 S->isDeclScope(PrevDecl)) { 17718 Diag(NameLoc, diag::ext_member_redeclared); 17719 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 17720 } 17721 17722 if (!Invalid) { 17723 // If this is a use, just return the declaration we found, unless 17724 // we have attributes. 17725 if (TUK == TUK_Reference || TUK == TUK_Friend) { 17726 if (!Attrs.empty()) { 17727 // FIXME: Diagnose these attributes. For now, we create a new 17728 // declaration to hold them. 17729 } else if (TUK == TUK_Reference && 17730 (PrevTagDecl->getFriendObjectKind() == 17731 Decl::FOK_Undeclared || 17732 PrevDecl->getOwningModule() != getCurrentModule()) && 17733 SS.isEmpty()) { 17734 // This declaration is a reference to an existing entity, but 17735 // has different visibility from that entity: it either makes 17736 // a friend visible or it makes a type visible in a new module. 17737 // In either case, create a new declaration. We only do this if 17738 // the declaration would have meant the same thing if no prior 17739 // declaration were found, that is, if it was found in the same 17740 // scope where we would have injected a declaration. 17741 if (!getTagInjectionContext(CurContext)->getRedeclContext() 17742 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 17743 return PrevTagDecl; 17744 // This is in the injected scope, create a new declaration in 17745 // that scope. 17746 S = getTagInjectionScope(S, getLangOpts()); 17747 } else { 17748 return PrevTagDecl; 17749 } 17750 } 17751 17752 // Diagnose attempts to redefine a tag. 17753 if (TUK == TUK_Definition) { 17754 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 17755 // If we're defining a specialization and the previous definition 17756 // is from an implicit instantiation, don't emit an error 17757 // here; we'll catch this in the general case below. 17758 bool IsExplicitSpecializationAfterInstantiation = false; 17759 if (isMemberSpecialization) { 17760 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 17761 IsExplicitSpecializationAfterInstantiation = 17762 RD->getTemplateSpecializationKind() != 17763 TSK_ExplicitSpecialization; 17764 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 17765 IsExplicitSpecializationAfterInstantiation = 17766 ED->getTemplateSpecializationKind() != 17767 TSK_ExplicitSpecialization; 17768 } 17769 17770 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 17771 // not keep more that one definition around (merge them). However, 17772 // ensure the decl passes the structural compatibility check in 17773 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 17774 NamedDecl *Hidden = nullptr; 17775 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 17776 // There is a definition of this tag, but it is not visible. We 17777 // explicitly make use of C++'s one definition rule here, and 17778 // assume that this definition is identical to the hidden one 17779 // we already have. Make the existing definition visible and 17780 // use it in place of this one. 17781 if (!getLangOpts().CPlusPlus) { 17782 // Postpone making the old definition visible until after we 17783 // complete parsing the new one and do the structural 17784 // comparison. 17785 SkipBody->CheckSameAsPrevious = true; 17786 SkipBody->New = createTagFromNewDecl(); 17787 SkipBody->Previous = Def; 17788 return Def; 17789 } else { 17790 SkipBody->ShouldSkip = true; 17791 SkipBody->Previous = Def; 17792 makeMergedDefinitionVisible(Hidden); 17793 // Carry on and handle it like a normal definition. We'll 17794 // skip starting the definitiion later. 17795 } 17796 } else if (!IsExplicitSpecializationAfterInstantiation) { 17797 // A redeclaration in function prototype scope in C isn't 17798 // visible elsewhere, so merely issue a warning. 17799 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 17800 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 17801 else 17802 Diag(NameLoc, diag::err_redefinition) << Name; 17803 notePreviousDefinition(Def, 17804 NameLoc.isValid() ? NameLoc : KWLoc); 17805 // If this is a redefinition, recover by making this 17806 // struct be anonymous, which will make any later 17807 // references get the previous definition. 17808 Name = nullptr; 17809 Previous.clear(); 17810 Invalid = true; 17811 } 17812 } else { 17813 // If the type is currently being defined, complain 17814 // about a nested redefinition. 17815 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 17816 if (TD->isBeingDefined()) { 17817 Diag(NameLoc, diag::err_nested_redefinition) << Name; 17818 Diag(PrevTagDecl->getLocation(), 17819 diag::note_previous_definition); 17820 Name = nullptr; 17821 Previous.clear(); 17822 Invalid = true; 17823 } 17824 } 17825 17826 // Okay, this is definition of a previously declared or referenced 17827 // tag. We're going to create a new Decl for it. 17828 } 17829 17830 // Okay, we're going to make a redeclaration. If this is some kind 17831 // of reference, make sure we build the redeclaration in the same DC 17832 // as the original, and ignore the current access specifier. 17833 if (TUK == TUK_Friend || TUK == TUK_Reference) { 17834 SearchDC = PrevTagDecl->getDeclContext(); 17835 AS = AS_none; 17836 } 17837 } 17838 // If we get here we have (another) forward declaration or we 17839 // have a definition. Just create a new decl. 17840 17841 } else { 17842 // If we get here, this is a definition of a new tag type in a nested 17843 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 17844 // new decl/type. We set PrevDecl to NULL so that the entities 17845 // have distinct types. 17846 Previous.clear(); 17847 } 17848 // If we get here, we're going to create a new Decl. If PrevDecl 17849 // is non-NULL, it's a definition of the tag declared by 17850 // PrevDecl. If it's NULL, we have a new definition. 17851 17852 // Otherwise, PrevDecl is not a tag, but was found with tag 17853 // lookup. This is only actually possible in C++, where a few 17854 // things like templates still live in the tag namespace. 17855 } else { 17856 // Use a better diagnostic if an elaborated-type-specifier 17857 // found the wrong kind of type on the first 17858 // (non-redeclaration) lookup. 17859 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 17860 !Previous.isForRedeclaration()) { 17861 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17862 Diag(NameLoc, diag::err_tag_reference_non_tag) 17863 << PrevDecl << NTK << llvm::to_underlying(Kind); 17864 Diag(PrevDecl->getLocation(), diag::note_declared_at); 17865 Invalid = true; 17866 17867 // Otherwise, only diagnose if the declaration is in scope. 17868 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 17869 SS.isNotEmpty() || isMemberSpecialization)) { 17870 // do nothing 17871 17872 // Diagnose implicit declarations introduced by elaborated types. 17873 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 17874 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 17875 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 17876 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17877 Invalid = true; 17878 17879 // Otherwise it's a declaration. Call out a particularly common 17880 // case here. 17881 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 17882 unsigned Kind = 0; 17883 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 17884 Diag(NameLoc, diag::err_tag_definition_of_typedef) 17885 << Name << Kind << TND->getUnderlyingType(); 17886 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 17887 Invalid = true; 17888 17889 // Otherwise, diagnose. 17890 } else { 17891 // The tag name clashes with something else in the target scope, 17892 // issue an error and recover by making this tag be anonymous. 17893 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 17894 notePreviousDefinition(PrevDecl, NameLoc); 17895 Name = nullptr; 17896 Invalid = true; 17897 } 17898 17899 // The existing declaration isn't relevant to us; we're in a 17900 // new scope, so clear out the previous declaration. 17901 Previous.clear(); 17902 } 17903 } 17904 17905 CreateNewDecl: 17906 17907 TagDecl *PrevDecl = nullptr; 17908 if (Previous.isSingleResult()) 17909 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 17910 17911 // If there is an identifier, use the location of the identifier as the 17912 // location of the decl, otherwise use the location of the struct/union 17913 // keyword. 17914 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 17915 17916 // Otherwise, create a new declaration. If there is a previous 17917 // declaration of the same entity, the two will be linked via 17918 // PrevDecl. 17919 TagDecl *New; 17920 17921 if (Kind == TagTypeKind::Enum) { 17922 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17923 // enum X { A, B, C } D; D should chain to X. 17924 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 17925 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 17926 ScopedEnumUsesClassTag, IsFixed); 17927 17928 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 17929 StdAlignValT = cast<EnumDecl>(New); 17930 17931 // If this is an undefined enum, warn. 17932 if (TUK != TUK_Definition && !Invalid) { 17933 TagDecl *Def; 17934 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 17935 // C++0x: 7.2p2: opaque-enum-declaration. 17936 // Conflicts are diagnosed above. Do nothing. 17937 } 17938 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 17939 Diag(Loc, diag::ext_forward_ref_enum_def) 17940 << New; 17941 Diag(Def->getLocation(), diag::note_previous_definition); 17942 } else { 17943 unsigned DiagID = diag::ext_forward_ref_enum; 17944 if (getLangOpts().MSVCCompat) 17945 DiagID = diag::ext_ms_forward_ref_enum; 17946 else if (getLangOpts().CPlusPlus) 17947 DiagID = diag::err_forward_ref_enum; 17948 Diag(Loc, DiagID); 17949 } 17950 } 17951 17952 if (EnumUnderlying) { 17953 EnumDecl *ED = cast<EnumDecl>(New); 17954 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 17955 ED->setIntegerTypeSourceInfo(TI); 17956 else 17957 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 17958 QualType EnumTy = ED->getIntegerType(); 17959 ED->setPromotionType(Context.isPromotableIntegerType(EnumTy) 17960 ? Context.getPromotedIntegerType(EnumTy) 17961 : EnumTy); 17962 assert(ED->isComplete() && "enum with type should be complete"); 17963 } 17964 } else { 17965 // struct/union/class 17966 17967 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 17968 // struct X { int A; } D; D should chain to X. 17969 if (getLangOpts().CPlusPlus) { 17970 // FIXME: Look for a way to use RecordDecl for simple structs. 17971 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17972 cast_or_null<CXXRecordDecl>(PrevDecl)); 17973 17974 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 17975 StdBadAlloc = cast<CXXRecordDecl>(New); 17976 } else 17977 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 17978 cast_or_null<RecordDecl>(PrevDecl)); 17979 } 17980 17981 if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus) 17982 Diag(New->getLocation(), diag::ext_type_defined_in_offsetof) 17983 << (OOK == OOK_Macro) << New->getSourceRange(); 17984 17985 // C++11 [dcl.type]p3: 17986 // A type-specifier-seq shall not define a class or enumeration [...]. 17987 if (!Invalid && getLangOpts().CPlusPlus && 17988 (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) { 17989 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 17990 << Context.getTagDeclType(New); 17991 Invalid = true; 17992 } 17993 17994 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 17995 DC->getDeclKind() == Decl::Enum) { 17996 Diag(New->getLocation(), diag::err_type_defined_in_enum) 17997 << Context.getTagDeclType(New); 17998 Invalid = true; 17999 } 18000 18001 // Maybe add qualifier info. 18002 if (SS.isNotEmpty()) { 18003 if (SS.isSet()) { 18004 // If this is either a declaration or a definition, check the 18005 // nested-name-specifier against the current context. 18006 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 18007 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 18008 isMemberSpecialization)) 18009 Invalid = true; 18010 18011 New->setQualifierInfo(SS.getWithLocInContext(Context)); 18012 if (TemplateParameterLists.size() > 0) { 18013 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 18014 } 18015 } 18016 else 18017 Invalid = true; 18018 } 18019 18020 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 18021 // Add alignment attributes if necessary; these attributes are checked when 18022 // the ASTContext lays out the structure. 18023 // 18024 // It is important for implementing the correct semantics that this 18025 // happen here (in ActOnTag). The #pragma pack stack is 18026 // maintained as a result of parser callbacks which can occur at 18027 // many points during the parsing of a struct declaration (because 18028 // the #pragma tokens are effectively skipped over during the 18029 // parsing of the struct). 18030 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 18031 AddAlignmentAttributesForRecord(RD); 18032 AddMsStructLayoutForRecord(RD); 18033 } 18034 } 18035 18036 if (ModulePrivateLoc.isValid()) { 18037 if (isMemberSpecialization) 18038 Diag(New->getLocation(), diag::err_module_private_specialization) 18039 << 2 18040 << FixItHint::CreateRemoval(ModulePrivateLoc); 18041 // __module_private__ does not apply to local classes. However, we only 18042 // diagnose this as an error when the declaration specifiers are 18043 // freestanding. Here, we just ignore the __module_private__. 18044 else if (!SearchDC->isFunctionOrMethod()) 18045 New->setModulePrivate(); 18046 } 18047 18048 // If this is a specialization of a member class (of a class template), 18049 // check the specialization. 18050 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 18051 Invalid = true; 18052 18053 // If we're declaring or defining a tag in function prototype scope in C, 18054 // note that this type can only be used within the function and add it to 18055 // the list of decls to inject into the function definition scope. 18056 if ((Name || Kind == TagTypeKind::Enum) && 18057 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 18058 if (getLangOpts().CPlusPlus) { 18059 // C++ [dcl.fct]p6: 18060 // Types shall not be defined in return or parameter types. 18061 if (TUK == TUK_Definition && !IsTypeSpecifier) { 18062 Diag(Loc, diag::err_type_defined_in_param_type) 18063 << Name; 18064 Invalid = true; 18065 } 18066 } else if (!PrevDecl) { 18067 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 18068 } 18069 } 18070 18071 if (Invalid) 18072 New->setInvalidDecl(); 18073 18074 // Set the lexical context. If the tag has a C++ scope specifier, the 18075 // lexical context will be different from the semantic context. 18076 New->setLexicalDeclContext(CurContext); 18077 18078 // Mark this as a friend decl if applicable. 18079 // In Microsoft mode, a friend declaration also acts as a forward 18080 // declaration so we always pass true to setObjectOfFriendDecl to make 18081 // the tag name visible. 18082 if (TUK == TUK_Friend) 18083 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 18084 18085 // Set the access specifier. 18086 if (!Invalid && SearchDC->isRecord()) 18087 SetMemberAccessSpecifier(New, PrevDecl, AS); 18088 18089 if (PrevDecl) 18090 CheckRedeclarationInModule(New, PrevDecl); 18091 18092 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 18093 New->startDefinition(); 18094 18095 ProcessDeclAttributeList(S, New, Attrs); 18096 AddPragmaAttributes(S, New); 18097 18098 // If this has an identifier, add it to the scope stack. 18099 if (TUK == TUK_Friend) { 18100 // We might be replacing an existing declaration in the lookup tables; 18101 // if so, borrow its access specifier. 18102 if (PrevDecl) 18103 New->setAccess(PrevDecl->getAccess()); 18104 18105 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 18106 DC->makeDeclVisibleInContext(New); 18107 if (Name) // can be null along some error paths 18108 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 18109 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 18110 } else if (Name) { 18111 S = getNonFieldDeclScope(S); 18112 PushOnScopeChains(New, S, true); 18113 } else { 18114 CurContext->addDecl(New); 18115 } 18116 18117 // If this is the C FILE type, notify the AST context. 18118 if (IdentifierInfo *II = New->getIdentifier()) 18119 if (!New->isInvalidDecl() && 18120 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 18121 II->isStr("FILE")) 18122 Context.setFILEDecl(New); 18123 18124 if (PrevDecl) 18125 mergeDeclAttributes(New, PrevDecl); 18126 18127 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 18128 inferGslOwnerPointerAttribute(CXXRD); 18129 18130 // If there's a #pragma GCC visibility in scope, set the visibility of this 18131 // record. 18132 AddPushedVisibilityAttribute(New); 18133 18134 if (isMemberSpecialization && !New->isInvalidDecl()) 18135 CompleteMemberSpecialization(New, Previous); 18136 18137 OwnedDecl = true; 18138 // In C++, don't return an invalid declaration. We can't recover well from 18139 // the cases where we make the type anonymous. 18140 if (Invalid && getLangOpts().CPlusPlus) { 18141 if (New->isBeingDefined()) 18142 if (auto RD = dyn_cast<RecordDecl>(New)) 18143 RD->completeDefinition(); 18144 return true; 18145 } else if (SkipBody && SkipBody->ShouldSkip) { 18146 return SkipBody->Previous; 18147 } else { 18148 return New; 18149 } 18150 } 18151 18152 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 18153 AdjustDeclIfTemplate(TagD); 18154 TagDecl *Tag = cast<TagDecl>(TagD); 18155 18156 // Enter the tag context. 18157 PushDeclContext(S, Tag); 18158 18159 ActOnDocumentableDecl(TagD); 18160 18161 // If there's a #pragma GCC visibility in scope, set the visibility of this 18162 // record. 18163 AddPushedVisibilityAttribute(Tag); 18164 } 18165 18166 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 18167 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 18168 return false; 18169 18170 // Make the previous decl visible. 18171 makeMergedDefinitionVisible(SkipBody.Previous); 18172 return true; 18173 } 18174 18175 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) { 18176 assert(IDecl->getLexicalParent() == CurContext && 18177 "The next DeclContext should be lexically contained in the current one."); 18178 CurContext = IDecl; 18179 } 18180 18181 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 18182 SourceLocation FinalLoc, 18183 bool IsFinalSpelledSealed, 18184 bool IsAbstract, 18185 SourceLocation LBraceLoc) { 18186 AdjustDeclIfTemplate(TagD); 18187 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 18188 18189 FieldCollector->StartClass(); 18190 18191 if (!Record->getIdentifier()) 18192 return; 18193 18194 if (IsAbstract) 18195 Record->markAbstract(); 18196 18197 if (FinalLoc.isValid()) { 18198 Record->addAttr(FinalAttr::Create(Context, FinalLoc, 18199 IsFinalSpelledSealed 18200 ? FinalAttr::Keyword_sealed 18201 : FinalAttr::Keyword_final)); 18202 } 18203 // C++ [class]p2: 18204 // [...] The class-name is also inserted into the scope of the 18205 // class itself; this is known as the injected-class-name. For 18206 // purposes of access checking, the injected-class-name is treated 18207 // as if it were a public member name. 18208 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 18209 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 18210 Record->getLocation(), Record->getIdentifier(), 18211 /*PrevDecl=*/nullptr, 18212 /*DelayTypeCreation=*/true); 18213 Context.getTypeDeclType(InjectedClassName, Record); 18214 InjectedClassName->setImplicit(); 18215 InjectedClassName->setAccess(AS_public); 18216 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 18217 InjectedClassName->setDescribedClassTemplate(Template); 18218 PushOnScopeChains(InjectedClassName, S); 18219 assert(InjectedClassName->isInjectedClassName() && 18220 "Broken injected-class-name"); 18221 } 18222 18223 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 18224 SourceRange BraceRange) { 18225 AdjustDeclIfTemplate(TagD); 18226 TagDecl *Tag = cast<TagDecl>(TagD); 18227 Tag->setBraceRange(BraceRange); 18228 18229 // Make sure we "complete" the definition even it is invalid. 18230 if (Tag->isBeingDefined()) { 18231 assert(Tag->isInvalidDecl() && "We should already have completed it"); 18232 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18233 RD->completeDefinition(); 18234 } 18235 18236 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 18237 FieldCollector->FinishClass(); 18238 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 18239 auto *Def = RD->getDefinition(); 18240 assert(Def && "The record is expected to have a completed definition"); 18241 unsigned NumInitMethods = 0; 18242 for (auto *Method : Def->methods()) { 18243 if (!Method->getIdentifier()) 18244 continue; 18245 if (Method->getName() == "__init") 18246 NumInitMethods++; 18247 } 18248 if (NumInitMethods > 1 || !Def->hasInitMethod()) 18249 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 18250 } 18251 } 18252 18253 // Exit this scope of this tag's definition. 18254 PopDeclContext(); 18255 18256 if (getCurLexicalContext()->isObjCContainer() && 18257 Tag->getDeclContext()->isFileContext()) 18258 Tag->setTopLevelDeclInObjCContainer(); 18259 18260 // Notify the consumer that we've defined a tag. 18261 if (!Tag->isInvalidDecl()) 18262 Consumer.HandleTagDeclDefinition(Tag); 18263 18264 // Clangs implementation of #pragma align(packed) differs in bitfield layout 18265 // from XLs and instead matches the XL #pragma pack(1) behavior. 18266 if (Context.getTargetInfo().getTriple().isOSAIX() && 18267 AlignPackStack.hasValue()) { 18268 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 18269 // Only diagnose #pragma align(packed). 18270 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 18271 return; 18272 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 18273 if (!RD) 18274 return; 18275 // Only warn if there is at least 1 bitfield member. 18276 if (llvm::any_of(RD->fields(), 18277 [](const FieldDecl *FD) { return FD->isBitField(); })) 18278 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 18279 } 18280 } 18281 18282 void Sema::ActOnObjCContainerFinishDefinition() { 18283 // Exit this scope of this interface definition. 18284 PopDeclContext(); 18285 } 18286 18287 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) { 18288 assert(ObjCCtx == CurContext && "Mismatch of container contexts"); 18289 OriginalLexicalContext = ObjCCtx; 18290 ActOnObjCContainerFinishDefinition(); 18291 } 18292 18293 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) { 18294 ActOnObjCContainerStartDefinition(ObjCCtx); 18295 OriginalLexicalContext = nullptr; 18296 } 18297 18298 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 18299 AdjustDeclIfTemplate(TagD); 18300 TagDecl *Tag = cast<TagDecl>(TagD); 18301 Tag->setInvalidDecl(); 18302 18303 // Make sure we "complete" the definition even it is invalid. 18304 if (Tag->isBeingDefined()) { 18305 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 18306 RD->completeDefinition(); 18307 } 18308 18309 // We're undoing ActOnTagStartDefinition here, not 18310 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 18311 // the FieldCollector. 18312 18313 PopDeclContext(); 18314 } 18315 18316 // Note that FieldName may be null for anonymous bitfields. 18317 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 18318 IdentifierInfo *FieldName, QualType FieldTy, 18319 bool IsMsStruct, Expr *BitWidth) { 18320 assert(BitWidth); 18321 if (BitWidth->containsErrors()) 18322 return ExprError(); 18323 18324 // C99 6.7.2.1p4 - verify the field type. 18325 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 18326 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 18327 // Handle incomplete and sizeless types with a specific error. 18328 if (RequireCompleteSizedType(FieldLoc, FieldTy, 18329 diag::err_field_incomplete_or_sizeless)) 18330 return ExprError(); 18331 if (FieldName) 18332 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 18333 << FieldName << FieldTy << BitWidth->getSourceRange(); 18334 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 18335 << FieldTy << BitWidth->getSourceRange(); 18336 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 18337 UPPC_BitFieldWidth)) 18338 return ExprError(); 18339 18340 // If the bit-width is type- or value-dependent, don't try to check 18341 // it now. 18342 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 18343 return BitWidth; 18344 18345 llvm::APSInt Value; 18346 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 18347 if (ICE.isInvalid()) 18348 return ICE; 18349 BitWidth = ICE.get(); 18350 18351 // Zero-width bitfield is ok for anonymous field. 18352 if (Value == 0 && FieldName) 18353 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) 18354 << FieldName << BitWidth->getSourceRange(); 18355 18356 if (Value.isSigned() && Value.isNegative()) { 18357 if (FieldName) 18358 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 18359 << FieldName << toString(Value, 10); 18360 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 18361 << toString(Value, 10); 18362 } 18363 18364 // The size of the bit-field must not exceed our maximum permitted object 18365 // size. 18366 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 18367 return Diag(FieldLoc, diag::err_bitfield_too_wide) 18368 << !FieldName << FieldName << toString(Value, 10); 18369 } 18370 18371 if (!FieldTy->isDependentType()) { 18372 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 18373 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 18374 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 18375 18376 // Over-wide bitfields are an error in C or when using the MSVC bitfield 18377 // ABI. 18378 bool CStdConstraintViolation = 18379 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 18380 bool MSBitfieldViolation = 18381 Value.ugt(TypeStorageSize) && 18382 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 18383 if (CStdConstraintViolation || MSBitfieldViolation) { 18384 unsigned DiagWidth = 18385 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 18386 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 18387 << (bool)FieldName << FieldName << toString(Value, 10) 18388 << !CStdConstraintViolation << DiagWidth; 18389 } 18390 18391 // Warn on types where the user might conceivably expect to get all 18392 // specified bits as value bits: that's all integral types other than 18393 // 'bool'. 18394 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 18395 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 18396 << FieldName << toString(Value, 10) 18397 << (unsigned)TypeWidth; 18398 } 18399 } 18400 18401 return BitWidth; 18402 } 18403 18404 /// ActOnField - Each field of a C struct/union is passed into this in order 18405 /// to create a FieldDecl object for it. 18406 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 18407 Declarator &D, Expr *BitfieldWidth) { 18408 FieldDecl *Res = HandleField(S, cast_if_present<RecordDecl>(TagD), DeclStart, 18409 D, BitfieldWidth, 18410 /*InitStyle=*/ICIS_NoInit, AS_public); 18411 return Res; 18412 } 18413 18414 /// HandleField - Analyze a field of a C struct or a C++ data member. 18415 /// 18416 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 18417 SourceLocation DeclStart, 18418 Declarator &D, Expr *BitWidth, 18419 InClassInitStyle InitStyle, 18420 AccessSpecifier AS) { 18421 if (D.isDecompositionDeclarator()) { 18422 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 18423 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 18424 << Decomp.getSourceRange(); 18425 return nullptr; 18426 } 18427 18428 IdentifierInfo *II = D.getIdentifier(); 18429 SourceLocation Loc = DeclStart; 18430 if (II) Loc = D.getIdentifierLoc(); 18431 18432 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 18433 QualType T = TInfo->getType(); 18434 if (getLangOpts().CPlusPlus) { 18435 CheckExtraCXXDefaultArguments(D); 18436 18437 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18438 UPPC_DataMemberType)) { 18439 D.setInvalidType(); 18440 T = Context.IntTy; 18441 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18442 } 18443 } 18444 18445 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18446 18447 if (D.getDeclSpec().isInlineSpecified()) 18448 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18449 << getLangOpts().CPlusPlus17; 18450 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18451 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18452 diag::err_invalid_thread) 18453 << DeclSpec::getSpecifierName(TSCS); 18454 18455 // Check to see if this name was declared as a member previously 18456 NamedDecl *PrevDecl = nullptr; 18457 LookupResult Previous(*this, II, Loc, LookupMemberName, 18458 ForVisibleRedeclaration); 18459 LookupName(Previous, S); 18460 switch (Previous.getResultKind()) { 18461 case LookupResult::Found: 18462 case LookupResult::FoundUnresolvedValue: 18463 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18464 break; 18465 18466 case LookupResult::FoundOverloaded: 18467 PrevDecl = Previous.getRepresentativeDecl(); 18468 break; 18469 18470 case LookupResult::NotFound: 18471 case LookupResult::NotFoundInCurrentInstantiation: 18472 case LookupResult::Ambiguous: 18473 break; 18474 } 18475 Previous.suppressDiagnostics(); 18476 18477 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18478 // Maybe we will complain about the shadowed template parameter. 18479 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18480 // Just pretend that we didn't see the previous declaration. 18481 PrevDecl = nullptr; 18482 } 18483 18484 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18485 PrevDecl = nullptr; 18486 18487 bool Mutable 18488 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 18489 SourceLocation TSSL = D.getBeginLoc(); 18490 FieldDecl *NewFD 18491 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 18492 TSSL, AS, PrevDecl, &D); 18493 18494 if (NewFD->isInvalidDecl()) 18495 Record->setInvalidDecl(); 18496 18497 if (D.getDeclSpec().isModulePrivateSpecified()) 18498 NewFD->setModulePrivate(); 18499 18500 if (NewFD->isInvalidDecl() && PrevDecl) { 18501 // Don't introduce NewFD into scope; there's already something 18502 // with the same name in the same scope. 18503 } else if (II) { 18504 PushOnScopeChains(NewFD, S); 18505 } else 18506 Record->addDecl(NewFD); 18507 18508 return NewFD; 18509 } 18510 18511 /// Build a new FieldDecl and check its well-formedness. 18512 /// 18513 /// This routine builds a new FieldDecl given the fields name, type, 18514 /// record, etc. \p PrevDecl should refer to any previous declaration 18515 /// with the same name and in the same scope as the field to be 18516 /// created. 18517 /// 18518 /// \returns a new FieldDecl. 18519 /// 18520 /// \todo The Declarator argument is a hack. It will be removed once 18521 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 18522 TypeSourceInfo *TInfo, 18523 RecordDecl *Record, SourceLocation Loc, 18524 bool Mutable, Expr *BitWidth, 18525 InClassInitStyle InitStyle, 18526 SourceLocation TSSL, 18527 AccessSpecifier AS, NamedDecl *PrevDecl, 18528 Declarator *D) { 18529 IdentifierInfo *II = Name.getAsIdentifierInfo(); 18530 bool InvalidDecl = false; 18531 if (D) InvalidDecl = D->isInvalidType(); 18532 18533 // If we receive a broken type, recover by assuming 'int' and 18534 // marking this declaration as invalid. 18535 if (T.isNull() || T->containsErrors()) { 18536 InvalidDecl = true; 18537 T = Context.IntTy; 18538 } 18539 18540 QualType EltTy = Context.getBaseElementType(T); 18541 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 18542 if (RequireCompleteSizedType(Loc, EltTy, 18543 diag::err_field_incomplete_or_sizeless)) { 18544 // Fields of incomplete type force their record to be invalid. 18545 Record->setInvalidDecl(); 18546 InvalidDecl = true; 18547 } else { 18548 NamedDecl *Def; 18549 EltTy->isIncompleteType(&Def); 18550 if (Def && Def->isInvalidDecl()) { 18551 Record->setInvalidDecl(); 18552 InvalidDecl = true; 18553 } 18554 } 18555 } 18556 18557 // TR 18037 does not allow fields to be declared with address space 18558 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 18559 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 18560 Diag(Loc, diag::err_field_with_address_space); 18561 Record->setInvalidDecl(); 18562 InvalidDecl = true; 18563 } 18564 18565 if (LangOpts.OpenCL) { 18566 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 18567 // used as structure or union field: image, sampler, event or block types. 18568 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 18569 T->isBlockPointerType()) { 18570 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 18571 Record->setInvalidDecl(); 18572 InvalidDecl = true; 18573 } 18574 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 18575 // is enabled. 18576 if (BitWidth && !getOpenCLOptions().isAvailableOption( 18577 "__cl_clang_bitfields", LangOpts)) { 18578 Diag(Loc, diag::err_opencl_bitfields); 18579 InvalidDecl = true; 18580 } 18581 } 18582 18583 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 18584 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 18585 T.hasQualifiers()) { 18586 InvalidDecl = true; 18587 Diag(Loc, diag::err_anon_bitfield_qualifiers); 18588 } 18589 18590 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18591 // than a variably modified type. 18592 if (!InvalidDecl && T->isVariablyModifiedType()) { 18593 if (!tryToFixVariablyModifiedVarType( 18594 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 18595 InvalidDecl = true; 18596 } 18597 18598 // Fields can not have abstract class types 18599 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 18600 diag::err_abstract_type_in_decl, 18601 AbstractFieldType)) 18602 InvalidDecl = true; 18603 18604 if (InvalidDecl) 18605 BitWidth = nullptr; 18606 // If this is declared as a bit-field, check the bit-field. 18607 if (BitWidth) { 18608 BitWidth = 18609 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get(); 18610 if (!BitWidth) { 18611 InvalidDecl = true; 18612 BitWidth = nullptr; 18613 } 18614 } 18615 18616 // Check that 'mutable' is consistent with the type of the declaration. 18617 if (!InvalidDecl && Mutable) { 18618 unsigned DiagID = 0; 18619 if (T->isReferenceType()) 18620 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 18621 : diag::err_mutable_reference; 18622 else if (T.isConstQualified()) 18623 DiagID = diag::err_mutable_const; 18624 18625 if (DiagID) { 18626 SourceLocation ErrLoc = Loc; 18627 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 18628 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 18629 Diag(ErrLoc, DiagID); 18630 if (DiagID != diag::ext_mutable_reference) { 18631 Mutable = false; 18632 InvalidDecl = true; 18633 } 18634 } 18635 } 18636 18637 // C++11 [class.union]p8 (DR1460): 18638 // At most one variant member of a union may have a 18639 // brace-or-equal-initializer. 18640 if (InitStyle != ICIS_NoInit) 18641 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 18642 18643 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 18644 BitWidth, Mutable, InitStyle); 18645 if (InvalidDecl) 18646 NewFD->setInvalidDecl(); 18647 18648 if (PrevDecl && !isa<TagDecl>(PrevDecl) && 18649 !PrevDecl->isPlaceholderVar(getLangOpts())) { 18650 Diag(Loc, diag::err_duplicate_member) << II; 18651 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18652 NewFD->setInvalidDecl(); 18653 } 18654 18655 if (!InvalidDecl && getLangOpts().CPlusPlus) { 18656 if (Record->isUnion()) { 18657 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18658 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18659 if (RDecl->getDefinition()) { 18660 // C++ [class.union]p1: An object of a class with a non-trivial 18661 // constructor, a non-trivial copy constructor, a non-trivial 18662 // destructor, or a non-trivial copy assignment operator 18663 // cannot be a member of a union, nor can an array of such 18664 // objects. 18665 if (CheckNontrivialField(NewFD)) 18666 NewFD->setInvalidDecl(); 18667 } 18668 } 18669 18670 // C++ [class.union]p1: If a union contains a member of reference type, 18671 // the program is ill-formed, except when compiling with MSVC extensions 18672 // enabled. 18673 if (EltTy->isReferenceType()) { 18674 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 18675 diag::ext_union_member_of_reference_type : 18676 diag::err_union_member_of_reference_type) 18677 << NewFD->getDeclName() << EltTy; 18678 if (!getLangOpts().MicrosoftExt) 18679 NewFD->setInvalidDecl(); 18680 } 18681 } 18682 } 18683 18684 // FIXME: We need to pass in the attributes given an AST 18685 // representation, not a parser representation. 18686 if (D) { 18687 // FIXME: The current scope is almost... but not entirely... correct here. 18688 ProcessDeclAttributes(getCurScope(), NewFD, *D); 18689 18690 if (NewFD->hasAttrs()) 18691 CheckAlignasUnderalignment(NewFD); 18692 } 18693 18694 // In auto-retain/release, infer strong retension for fields of 18695 // retainable type. 18696 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 18697 NewFD->setInvalidDecl(); 18698 18699 if (T.isObjCGCWeak()) 18700 Diag(Loc, diag::warn_attribute_weak_on_field); 18701 18702 // PPC MMA non-pointer types are not allowed as field types. 18703 if (Context.getTargetInfo().getTriple().isPPC64() && 18704 CheckPPCMMAType(T, NewFD->getLocation())) 18705 NewFD->setInvalidDecl(); 18706 18707 NewFD->setAccess(AS); 18708 return NewFD; 18709 } 18710 18711 bool Sema::CheckNontrivialField(FieldDecl *FD) { 18712 assert(FD); 18713 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 18714 18715 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 18716 return false; 18717 18718 QualType EltTy = Context.getBaseElementType(FD->getType()); 18719 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 18720 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 18721 if (RDecl->getDefinition()) { 18722 // We check for copy constructors before constructors 18723 // because otherwise we'll never get complaints about 18724 // copy constructors. 18725 18726 CXXSpecialMember member = CXXInvalid; 18727 // We're required to check for any non-trivial constructors. Since the 18728 // implicit default constructor is suppressed if there are any 18729 // user-declared constructors, we just need to check that there is a 18730 // trivial default constructor and a trivial copy constructor. (We don't 18731 // worry about move constructors here, since this is a C++98 check.) 18732 if (RDecl->hasNonTrivialCopyConstructor()) 18733 member = CXXCopyConstructor; 18734 else if (!RDecl->hasTrivialDefaultConstructor()) 18735 member = CXXDefaultConstructor; 18736 else if (RDecl->hasNonTrivialCopyAssignment()) 18737 member = CXXCopyAssignment; 18738 else if (RDecl->hasNonTrivialDestructor()) 18739 member = CXXDestructor; 18740 18741 if (member != CXXInvalid) { 18742 if (!getLangOpts().CPlusPlus11 && 18743 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 18744 // Objective-C++ ARC: it is an error to have a non-trivial field of 18745 // a union. However, system headers in Objective-C programs 18746 // occasionally have Objective-C lifetime objects within unions, 18747 // and rather than cause the program to fail, we make those 18748 // members unavailable. 18749 SourceLocation Loc = FD->getLocation(); 18750 if (getSourceManager().isInSystemHeader(Loc)) { 18751 if (!FD->hasAttr<UnavailableAttr>()) 18752 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 18753 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 18754 return false; 18755 } 18756 } 18757 18758 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 18759 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 18760 diag::err_illegal_union_or_anon_struct_member) 18761 << FD->getParent()->isUnion() << FD->getDeclName() << member; 18762 DiagnoseNontrivial(RDecl, member); 18763 return !getLangOpts().CPlusPlus11; 18764 } 18765 } 18766 } 18767 18768 return false; 18769 } 18770 18771 /// TranslateIvarVisibility - Translate visibility from a token ID to an 18772 /// AST enum value. 18773 static ObjCIvarDecl::AccessControl 18774 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 18775 switch (ivarVisibility) { 18776 default: llvm_unreachable("Unknown visitibility kind"); 18777 case tok::objc_private: return ObjCIvarDecl::Private; 18778 case tok::objc_public: return ObjCIvarDecl::Public; 18779 case tok::objc_protected: return ObjCIvarDecl::Protected; 18780 case tok::objc_package: return ObjCIvarDecl::Package; 18781 } 18782 } 18783 18784 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 18785 /// in order to create an IvarDecl object for it. 18786 Decl *Sema::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, 18787 Expr *BitWidth, tok::ObjCKeywordKind Visibility) { 18788 18789 IdentifierInfo *II = D.getIdentifier(); 18790 SourceLocation Loc = DeclStart; 18791 if (II) Loc = D.getIdentifierLoc(); 18792 18793 // FIXME: Unnamed fields can be handled in various different ways, for 18794 // example, unnamed unions inject all members into the struct namespace! 18795 18796 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 18797 QualType T = TInfo->getType(); 18798 18799 if (BitWidth) { 18800 // 6.7.2.1p3, 6.7.2.1p4 18801 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 18802 if (!BitWidth) 18803 D.setInvalidType(); 18804 } else { 18805 // Not a bitfield. 18806 18807 // validate II. 18808 18809 } 18810 if (T->isReferenceType()) { 18811 Diag(Loc, diag::err_ivar_reference_type); 18812 D.setInvalidType(); 18813 } 18814 // C99 6.7.2.1p8: A member of a structure or union may have any type other 18815 // than a variably modified type. 18816 else if (T->isVariablyModifiedType()) { 18817 if (!tryToFixVariablyModifiedVarType( 18818 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 18819 D.setInvalidType(); 18820 } 18821 18822 // Get the visibility (access control) for this ivar. 18823 ObjCIvarDecl::AccessControl ac = 18824 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 18825 : ObjCIvarDecl::None; 18826 // Must set ivar's DeclContext to its enclosing interface. 18827 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 18828 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 18829 return nullptr; 18830 ObjCContainerDecl *EnclosingContext; 18831 if (ObjCImplementationDecl *IMPDecl = 18832 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18833 if (LangOpts.ObjCRuntime.isFragile()) { 18834 // Case of ivar declared in an implementation. Context is that of its class. 18835 EnclosingContext = IMPDecl->getClassInterface(); 18836 assert(EnclosingContext && "Implementation has no class interface!"); 18837 } 18838 else 18839 EnclosingContext = EnclosingDecl; 18840 } else { 18841 if (ObjCCategoryDecl *CDecl = 18842 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18843 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 18844 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 18845 return nullptr; 18846 } 18847 } 18848 EnclosingContext = EnclosingDecl; 18849 } 18850 18851 // Construct the decl. 18852 ObjCIvarDecl *NewID = ObjCIvarDecl::Create( 18853 Context, EnclosingContext, DeclStart, Loc, II, T, TInfo, ac, BitWidth); 18854 18855 if (T->containsErrors()) 18856 NewID->setInvalidDecl(); 18857 18858 if (II) { 18859 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 18860 ForVisibleRedeclaration); 18861 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 18862 && !isa<TagDecl>(PrevDecl)) { 18863 Diag(Loc, diag::err_duplicate_member) << II; 18864 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 18865 NewID->setInvalidDecl(); 18866 } 18867 } 18868 18869 // Process attributes attached to the ivar. 18870 ProcessDeclAttributes(S, NewID, D); 18871 18872 if (D.isInvalidType()) 18873 NewID->setInvalidDecl(); 18874 18875 // In ARC, infer 'retaining' for ivars of retainable type. 18876 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 18877 NewID->setInvalidDecl(); 18878 18879 if (D.getDeclSpec().isModulePrivateSpecified()) 18880 NewID->setModulePrivate(); 18881 18882 if (II) { 18883 // FIXME: When interfaces are DeclContexts, we'll need to add 18884 // these to the interface. 18885 S->AddDecl(NewID); 18886 IdResolver.AddDecl(NewID); 18887 } 18888 18889 if (LangOpts.ObjCRuntime.isNonFragile() && 18890 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 18891 Diag(Loc, diag::warn_ivars_in_interface); 18892 18893 return NewID; 18894 } 18895 18896 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 18897 /// class and class extensions. For every class \@interface and class 18898 /// extension \@interface, if the last ivar is a bitfield of any type, 18899 /// then add an implicit `char :0` ivar to the end of that interface. 18900 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 18901 SmallVectorImpl<Decl *> &AllIvarDecls) { 18902 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 18903 return; 18904 18905 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 18906 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 18907 18908 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 18909 return; 18910 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 18911 if (!ID) { 18912 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 18913 if (!CD->IsClassExtension()) 18914 return; 18915 } 18916 // No need to add this to end of @implementation. 18917 else 18918 return; 18919 } 18920 // All conditions are met. Add a new bitfield to the tail end of ivars. 18921 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 18922 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 18923 18924 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 18925 DeclLoc, DeclLoc, nullptr, 18926 Context.CharTy, 18927 Context.getTrivialTypeSourceInfo(Context.CharTy, 18928 DeclLoc), 18929 ObjCIvarDecl::Private, BW, 18930 true); 18931 AllIvarDecls.push_back(Ivar); 18932 } 18933 18934 /// [class.dtor]p4: 18935 /// At the end of the definition of a class, overload resolution is 18936 /// performed among the prospective destructors declared in that class with 18937 /// an empty argument list to select the destructor for the class, also 18938 /// known as the selected destructor. 18939 /// 18940 /// We do the overload resolution here, then mark the selected constructor in the AST. 18941 /// Later CXXRecordDecl::getDestructor() will return the selected constructor. 18942 static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { 18943 if (!Record->hasUserDeclaredDestructor()) { 18944 return; 18945 } 18946 18947 SourceLocation Loc = Record->getLocation(); 18948 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); 18949 18950 for (auto *Decl : Record->decls()) { 18951 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) { 18952 if (DD->isInvalidDecl()) 18953 continue; 18954 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {}, 18955 OCS); 18956 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected."); 18957 } 18958 } 18959 18960 if (OCS.empty()) { 18961 return; 18962 } 18963 OverloadCandidateSet::iterator Best; 18964 unsigned Msg = 0; 18965 OverloadCandidateDisplayKind DisplayKind; 18966 18967 switch (OCS.BestViableFunction(S, Loc, Best)) { 18968 case OR_Success: 18969 case OR_Deleted: 18970 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function)); 18971 break; 18972 18973 case OR_Ambiguous: 18974 Msg = diag::err_ambiguous_destructor; 18975 DisplayKind = OCD_AmbiguousCandidates; 18976 break; 18977 18978 case OR_No_Viable_Function: 18979 Msg = diag::err_no_viable_destructor; 18980 DisplayKind = OCD_AllCandidates; 18981 break; 18982 } 18983 18984 if (Msg) { 18985 // OpenCL have got their own thing going with destructors. It's slightly broken, 18986 // but we allow it. 18987 if (!S.LangOpts.OpenCL) { 18988 PartialDiagnostic Diag = S.PDiag(Msg) << Record; 18989 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {}); 18990 Record->setInvalidDecl(); 18991 } 18992 // It's a bit hacky: At this point we've raised an error but we want the 18993 // rest of the compiler to continue somehow working. However almost 18994 // everything we'll try to do with the class will depend on there being a 18995 // destructor. So let's pretend the first one is selected and hope for the 18996 // best. 18997 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function)); 18998 } 18999 } 19000 19001 /// [class.mem.special]p5 19002 /// Two special member functions are of the same kind if: 19003 /// - they are both default constructors, 19004 /// - they are both copy or move constructors with the same first parameter 19005 /// type, or 19006 /// - they are both copy or move assignment operators with the same first 19007 /// parameter type and the same cv-qualifiers and ref-qualifier, if any. 19008 static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context, 19009 CXXMethodDecl *M1, 19010 CXXMethodDecl *M2, 19011 Sema::CXXSpecialMember CSM) { 19012 // We don't want to compare templates to non-templates: See 19013 // https://github.com/llvm/llvm-project/issues/59206 19014 if (CSM == Sema::CXXDefaultConstructor) 19015 return bool(M1->getDescribedFunctionTemplate()) == 19016 bool(M2->getDescribedFunctionTemplate()); 19017 // FIXME: better resolve CWG 19018 // https://cplusplus.github.io/CWG/issues/2787.html 19019 if (!Context.hasSameType(M1->getNonObjectParameter(0)->getType(), 19020 M2->getNonObjectParameter(0)->getType())) 19021 return false; 19022 if (!Context.hasSameType(M1->getFunctionObjectParameterReferenceType(), 19023 M2->getFunctionObjectParameterReferenceType())) 19024 return false; 19025 19026 return true; 19027 } 19028 19029 /// [class.mem.special]p6: 19030 /// An eligible special member function is a special member function for which: 19031 /// - the function is not deleted, 19032 /// - the associated constraints, if any, are satisfied, and 19033 /// - no special member function of the same kind whose associated constraints 19034 /// [CWG2595], if any, are satisfied is more constrained. 19035 static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record, 19036 ArrayRef<CXXMethodDecl *> Methods, 19037 Sema::CXXSpecialMember CSM) { 19038 SmallVector<bool, 4> SatisfactionStatus; 19039 19040 for (CXXMethodDecl *Method : Methods) { 19041 const Expr *Constraints = Method->getTrailingRequiresClause(); 19042 if (!Constraints) 19043 SatisfactionStatus.push_back(true); 19044 else { 19045 ConstraintSatisfaction Satisfaction; 19046 if (S.CheckFunctionConstraints(Method, Satisfaction)) 19047 SatisfactionStatus.push_back(false); 19048 else 19049 SatisfactionStatus.push_back(Satisfaction.IsSatisfied); 19050 } 19051 } 19052 19053 for (size_t i = 0; i < Methods.size(); i++) { 19054 if (!SatisfactionStatus[i]) 19055 continue; 19056 CXXMethodDecl *Method = Methods[i]; 19057 CXXMethodDecl *OrigMethod = Method; 19058 if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction()) 19059 OrigMethod = cast<CXXMethodDecl>(MF); 19060 19061 const Expr *Constraints = OrigMethod->getTrailingRequiresClause(); 19062 bool AnotherMethodIsMoreConstrained = false; 19063 for (size_t j = 0; j < Methods.size(); j++) { 19064 if (i == j || !SatisfactionStatus[j]) 19065 continue; 19066 CXXMethodDecl *OtherMethod = Methods[j]; 19067 if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction()) 19068 OtherMethod = cast<CXXMethodDecl>(MF); 19069 19070 if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod, 19071 CSM)) 19072 continue; 19073 19074 const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause(); 19075 if (!OtherConstraints) 19076 continue; 19077 if (!Constraints) { 19078 AnotherMethodIsMoreConstrained = true; 19079 break; 19080 } 19081 if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod, 19082 {Constraints}, 19083 AnotherMethodIsMoreConstrained)) { 19084 // There was an error with the constraints comparison. Exit the loop 19085 // and don't consider this function eligible. 19086 AnotherMethodIsMoreConstrained = true; 19087 } 19088 if (AnotherMethodIsMoreConstrained) 19089 break; 19090 } 19091 // FIXME: Do not consider deleted methods as eligible after implementing 19092 // DR1734 and DR1496. 19093 if (!AnotherMethodIsMoreConstrained) { 19094 Method->setIneligibleOrNotSelected(false); 19095 Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM); 19096 } 19097 } 19098 } 19099 19100 static void ComputeSpecialMemberFunctionsEligiblity(Sema &S, 19101 CXXRecordDecl *Record) { 19102 SmallVector<CXXMethodDecl *, 4> DefaultConstructors; 19103 SmallVector<CXXMethodDecl *, 4> CopyConstructors; 19104 SmallVector<CXXMethodDecl *, 4> MoveConstructors; 19105 SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators; 19106 SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators; 19107 19108 for (auto *Decl : Record->decls()) { 19109 auto *MD = dyn_cast<CXXMethodDecl>(Decl); 19110 if (!MD) { 19111 auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl); 19112 if (FTD) 19113 MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl()); 19114 } 19115 if (!MD) 19116 continue; 19117 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 19118 if (CD->isInvalidDecl()) 19119 continue; 19120 if (CD->isDefaultConstructor()) 19121 DefaultConstructors.push_back(MD); 19122 else if (CD->isCopyConstructor()) 19123 CopyConstructors.push_back(MD); 19124 else if (CD->isMoveConstructor()) 19125 MoveConstructors.push_back(MD); 19126 } else if (MD->isCopyAssignmentOperator()) { 19127 CopyAssignmentOperators.push_back(MD); 19128 } else if (MD->isMoveAssignmentOperator()) { 19129 MoveAssignmentOperators.push_back(MD); 19130 } 19131 } 19132 19133 SetEligibleMethods(S, Record, DefaultConstructors, 19134 Sema::CXXDefaultConstructor); 19135 SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor); 19136 SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor); 19137 SetEligibleMethods(S, Record, CopyAssignmentOperators, 19138 Sema::CXXCopyAssignment); 19139 SetEligibleMethods(S, Record, MoveAssignmentOperators, 19140 Sema::CXXMoveAssignment); 19141 } 19142 19143 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 19144 ArrayRef<Decl *> Fields, SourceLocation LBrac, 19145 SourceLocation RBrac, 19146 const ParsedAttributesView &Attrs) { 19147 assert(EnclosingDecl && "missing record or interface decl"); 19148 19149 // If this is an Objective-C @implementation or category and we have 19150 // new fields here we should reset the layout of the interface since 19151 // it will now change. 19152 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 19153 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 19154 switch (DC->getKind()) { 19155 default: break; 19156 case Decl::ObjCCategory: 19157 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 19158 break; 19159 case Decl::ObjCImplementation: 19160 Context. 19161 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 19162 break; 19163 } 19164 } 19165 19166 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 19167 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 19168 19169 // Start counting up the number of named members; make sure to include 19170 // members of anonymous structs and unions in the total. 19171 unsigned NumNamedMembers = 0; 19172 if (Record) { 19173 for (const auto *I : Record->decls()) { 19174 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 19175 if (IFD->getDeclName()) 19176 ++NumNamedMembers; 19177 } 19178 } 19179 19180 // Verify that all the fields are okay. 19181 SmallVector<FieldDecl*, 32> RecFields; 19182 19183 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 19184 i != end; ++i) { 19185 FieldDecl *FD = cast<FieldDecl>(*i); 19186 19187 // Get the type for the field. 19188 const Type *FDTy = FD->getType().getTypePtr(); 19189 19190 if (!FD->isAnonymousStructOrUnion()) { 19191 // Remember all fields written by the user. 19192 RecFields.push_back(FD); 19193 } 19194 19195 // If the field is already invalid for some reason, don't emit more 19196 // diagnostics about it. 19197 if (FD->isInvalidDecl()) { 19198 EnclosingDecl->setInvalidDecl(); 19199 continue; 19200 } 19201 19202 // C99 6.7.2.1p2: 19203 // A structure or union shall not contain a member with 19204 // incomplete or function type (hence, a structure shall not 19205 // contain an instance of itself, but may contain a pointer to 19206 // an instance of itself), except that the last member of a 19207 // structure with more than one named member may have incomplete 19208 // array type; such a structure (and any union containing, 19209 // possibly recursively, a member that is such a structure) 19210 // shall not be a member of a structure or an element of an 19211 // array. 19212 bool IsLastField = (i + 1 == Fields.end()); 19213 if (FDTy->isFunctionType()) { 19214 // Field declared as a function. 19215 Diag(FD->getLocation(), diag::err_field_declared_as_function) 19216 << FD->getDeclName(); 19217 FD->setInvalidDecl(); 19218 EnclosingDecl->setInvalidDecl(); 19219 continue; 19220 } else if (FDTy->isIncompleteArrayType() && 19221 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 19222 if (Record) { 19223 // Flexible array member. 19224 // Microsoft and g++ is more permissive regarding flexible array. 19225 // It will accept flexible array in union and also 19226 // as the sole element of a struct/class. 19227 unsigned DiagID = 0; 19228 if (!Record->isUnion() && !IsLastField) { 19229 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 19230 << FD->getDeclName() << FD->getType() 19231 << llvm::to_underlying(Record->getTagKind()); 19232 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 19233 FD->setInvalidDecl(); 19234 EnclosingDecl->setInvalidDecl(); 19235 continue; 19236 } else if (Record->isUnion()) 19237 DiagID = getLangOpts().MicrosoftExt 19238 ? diag::ext_flexible_array_union_ms 19239 : getLangOpts().CPlusPlus 19240 ? diag::ext_flexible_array_union_gnu 19241 : diag::err_flexible_array_union; 19242 else if (NumNamedMembers < 1) 19243 DiagID = getLangOpts().MicrosoftExt 19244 ? diag::ext_flexible_array_empty_aggregate_ms 19245 : getLangOpts().CPlusPlus 19246 ? diag::ext_flexible_array_empty_aggregate_gnu 19247 : diag::err_flexible_array_empty_aggregate; 19248 19249 if (DiagID) 19250 Diag(FD->getLocation(), DiagID) 19251 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19252 // While the layout of types that contain virtual bases is not specified 19253 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 19254 // virtual bases after the derived members. This would make a flexible 19255 // array member declared at the end of an object not adjacent to the end 19256 // of the type. 19257 if (CXXRecord && CXXRecord->getNumVBases() != 0) 19258 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 19259 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19260 if (!getLangOpts().C99) 19261 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 19262 << FD->getDeclName() << llvm::to_underlying(Record->getTagKind()); 19263 19264 // If the element type has a non-trivial destructor, we would not 19265 // implicitly destroy the elements, so disallow it for now. 19266 // 19267 // FIXME: GCC allows this. We should probably either implicitly delete 19268 // the destructor of the containing class, or just allow this. 19269 QualType BaseElem = Context.getBaseElementType(FD->getType()); 19270 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 19271 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 19272 << FD->getDeclName() << FD->getType(); 19273 FD->setInvalidDecl(); 19274 EnclosingDecl->setInvalidDecl(); 19275 continue; 19276 } 19277 // Okay, we have a legal flexible array member at the end of the struct. 19278 Record->setHasFlexibleArrayMember(true); 19279 } else { 19280 // In ObjCContainerDecl ivars with incomplete array type are accepted, 19281 // unless they are followed by another ivar. That check is done 19282 // elsewhere, after synthesized ivars are known. 19283 } 19284 } else if (!FDTy->isDependentType() && 19285 RequireCompleteSizedType( 19286 FD->getLocation(), FD->getType(), 19287 diag::err_field_incomplete_or_sizeless)) { 19288 // Incomplete type 19289 FD->setInvalidDecl(); 19290 EnclosingDecl->setInvalidDecl(); 19291 continue; 19292 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 19293 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 19294 // A type which contains a flexible array member is considered to be a 19295 // flexible array member. 19296 Record->setHasFlexibleArrayMember(true); 19297 if (!Record->isUnion()) { 19298 // If this is a struct/class and this is not the last element, reject 19299 // it. Note that GCC supports variable sized arrays in the middle of 19300 // structures. 19301 if (!IsLastField) 19302 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 19303 << FD->getDeclName() << FD->getType(); 19304 else { 19305 // We support flexible arrays at the end of structs in 19306 // other structs as an extension. 19307 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 19308 << FD->getDeclName(); 19309 } 19310 } 19311 } 19312 if (isa<ObjCContainerDecl>(EnclosingDecl) && 19313 RequireNonAbstractType(FD->getLocation(), FD->getType(), 19314 diag::err_abstract_type_in_decl, 19315 AbstractIvarType)) { 19316 // Ivars can not have abstract class types 19317 FD->setInvalidDecl(); 19318 } 19319 if (Record && FDTTy->getDecl()->hasObjectMember()) 19320 Record->setHasObjectMember(true); 19321 if (Record && FDTTy->getDecl()->hasVolatileMember()) 19322 Record->setHasVolatileMember(true); 19323 } else if (FDTy->isObjCObjectType()) { 19324 /// A field cannot be an Objective-c object 19325 Diag(FD->getLocation(), diag::err_statically_allocated_object) 19326 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 19327 QualType T = Context.getObjCObjectPointerType(FD->getType()); 19328 FD->setType(T); 19329 } else if (Record && Record->isUnion() && 19330 FD->getType().hasNonTrivialObjCLifetime() && 19331 getSourceManager().isInSystemHeader(FD->getLocation()) && 19332 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 19333 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 19334 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 19335 // For backward compatibility, fields of C unions declared in system 19336 // headers that have non-trivial ObjC ownership qualifications are marked 19337 // as unavailable unless the qualifier is explicit and __strong. This can 19338 // break ABI compatibility between programs compiled with ARC and MRR, but 19339 // is a better option than rejecting programs using those unions under 19340 // ARC. 19341 FD->addAttr(UnavailableAttr::CreateImplicit( 19342 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 19343 FD->getLocation())); 19344 } else if (getLangOpts().ObjC && 19345 getLangOpts().getGC() != LangOptions::NonGC && Record && 19346 !Record->hasObjectMember()) { 19347 if (FD->getType()->isObjCObjectPointerType() || 19348 FD->getType().isObjCGCStrong()) 19349 Record->setHasObjectMember(true); 19350 else if (Context.getAsArrayType(FD->getType())) { 19351 QualType BaseType = Context.getBaseElementType(FD->getType()); 19352 if (BaseType->isRecordType() && 19353 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 19354 Record->setHasObjectMember(true); 19355 else if (BaseType->isObjCObjectPointerType() || 19356 BaseType.isObjCGCStrong()) 19357 Record->setHasObjectMember(true); 19358 } 19359 } 19360 19361 if (Record && !getLangOpts().CPlusPlus && 19362 !shouldIgnoreForRecordTriviality(FD)) { 19363 QualType FT = FD->getType(); 19364 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 19365 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 19366 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 19367 Record->isUnion()) 19368 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 19369 } 19370 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 19371 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 19372 Record->setNonTrivialToPrimitiveCopy(true); 19373 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 19374 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 19375 } 19376 if (FT.isDestructedType()) { 19377 Record->setNonTrivialToPrimitiveDestroy(true); 19378 Record->setParamDestroyedInCallee(true); 19379 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 19380 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 19381 } 19382 19383 if (const auto *RT = FT->getAs<RecordType>()) { 19384 if (RT->getDecl()->getArgPassingRestrictions() == 19385 RecordArgPassingKind::CanNeverPassInRegs) 19386 Record->setArgPassingRestrictions( 19387 RecordArgPassingKind::CanNeverPassInRegs); 19388 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 19389 Record->setArgPassingRestrictions( 19390 RecordArgPassingKind::CanNeverPassInRegs); 19391 } 19392 19393 if (Record && FD->getType().isVolatileQualified()) 19394 Record->setHasVolatileMember(true); 19395 // Keep track of the number of named members. 19396 if (FD->getIdentifier()) 19397 ++NumNamedMembers; 19398 } 19399 19400 // Okay, we successfully defined 'Record'. 19401 if (Record) { 19402 bool Completed = false; 19403 if (CXXRecord) { 19404 if (!CXXRecord->isInvalidDecl()) { 19405 // Set access bits correctly on the directly-declared conversions. 19406 for (CXXRecordDecl::conversion_iterator 19407 I = CXXRecord->conversion_begin(), 19408 E = CXXRecord->conversion_end(); I != E; ++I) 19409 I.setAccess((*I)->getAccess()); 19410 } 19411 19412 // Add any implicitly-declared members to this class. 19413 AddImplicitlyDeclaredMembersToClass(CXXRecord); 19414 19415 if (!CXXRecord->isDependentType()) { 19416 if (!CXXRecord->isInvalidDecl()) { 19417 // If we have virtual base classes, we may end up finding multiple 19418 // final overriders for a given virtual function. Check for this 19419 // problem now. 19420 if (CXXRecord->getNumVBases()) { 19421 CXXFinalOverriderMap FinalOverriders; 19422 CXXRecord->getFinalOverriders(FinalOverriders); 19423 19424 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 19425 MEnd = FinalOverriders.end(); 19426 M != MEnd; ++M) { 19427 for (OverridingMethods::iterator SO = M->second.begin(), 19428 SOEnd = M->second.end(); 19429 SO != SOEnd; ++SO) { 19430 assert(SO->second.size() > 0 && 19431 "Virtual function without overriding functions?"); 19432 if (SO->second.size() == 1) 19433 continue; 19434 19435 // C++ [class.virtual]p2: 19436 // In a derived class, if a virtual member function of a base 19437 // class subobject has more than one final overrider the 19438 // program is ill-formed. 19439 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 19440 << (const NamedDecl *)M->first << Record; 19441 Diag(M->first->getLocation(), 19442 diag::note_overridden_virtual_function); 19443 for (OverridingMethods::overriding_iterator 19444 OM = SO->second.begin(), 19445 OMEnd = SO->second.end(); 19446 OM != OMEnd; ++OM) 19447 Diag(OM->Method->getLocation(), diag::note_final_overrider) 19448 << (const NamedDecl *)M->first << OM->Method->getParent(); 19449 19450 Record->setInvalidDecl(); 19451 } 19452 } 19453 CXXRecord->completeDefinition(&FinalOverriders); 19454 Completed = true; 19455 } 19456 } 19457 ComputeSelectedDestructor(*this, CXXRecord); 19458 ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord); 19459 } 19460 } 19461 19462 if (!Completed) 19463 Record->completeDefinition(); 19464 19465 // Handle attributes before checking the layout. 19466 ProcessDeclAttributeList(S, Record, Attrs); 19467 19468 // Check to see if a FieldDecl is a pointer to a function. 19469 auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) { 19470 const FieldDecl *FD = dyn_cast<FieldDecl>(D); 19471 if (!FD) { 19472 // Check whether this is a forward declaration that was inserted by 19473 // Clang. This happens when a non-forward declared / defined type is 19474 // used, e.g.: 19475 // 19476 // struct foo { 19477 // struct bar *(*f)(); 19478 // struct bar *(*g)(); 19479 // }; 19480 // 19481 // "struct bar" shows up in the decl AST as a "RecordDecl" with an 19482 // incomplete definition. 19483 if (const auto *TD = dyn_cast<TagDecl>(D)) 19484 return !TD->isCompleteDefinition(); 19485 return false; 19486 } 19487 QualType FieldType = FD->getType().getDesugaredType(Context); 19488 if (isa<PointerType>(FieldType)) { 19489 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); 19490 return PointeeType.getDesugaredType(Context)->isFunctionType(); 19491 } 19492 return false; 19493 }; 19494 19495 // Maybe randomize the record's decls. We automatically randomize a record 19496 // of function pointers, unless it has the "no_randomize_layout" attribute. 19497 if (!getLangOpts().CPlusPlus && 19498 (Record->hasAttr<RandomizeLayoutAttr>() || 19499 (!Record->hasAttr<NoRandomizeLayoutAttr>() && 19500 llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) && 19501 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 19502 !Record->isRandomized()) { 19503 SmallVector<Decl *, 32> NewDeclOrdering; 19504 if (randstruct::randomizeStructureLayout(Context, Record, 19505 NewDeclOrdering)) 19506 Record->reorderDecls(NewDeclOrdering); 19507 } 19508 19509 // We may have deferred checking for a deleted destructor. Check now. 19510 if (CXXRecord) { 19511 auto *Dtor = CXXRecord->getDestructor(); 19512 if (Dtor && Dtor->isImplicit() && 19513 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 19514 CXXRecord->setImplicitDestructorIsDeleted(); 19515 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 19516 } 19517 } 19518 19519 if (Record->hasAttrs()) { 19520 CheckAlignasUnderalignment(Record); 19521 19522 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 19523 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 19524 IA->getRange(), IA->getBestCase(), 19525 IA->getInheritanceModel()); 19526 } 19527 19528 // Check if the structure/union declaration is a type that can have zero 19529 // size in C. For C this is a language extension, for C++ it may cause 19530 // compatibility problems. 19531 bool CheckForZeroSize; 19532 if (!getLangOpts().CPlusPlus) { 19533 CheckForZeroSize = true; 19534 } else { 19535 // For C++ filter out types that cannot be referenced in C code. 19536 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 19537 CheckForZeroSize = 19538 CXXRecord->getLexicalDeclContext()->isExternCContext() && 19539 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 19540 CXXRecord->isCLike(); 19541 } 19542 if (CheckForZeroSize) { 19543 bool ZeroSize = true; 19544 bool IsEmpty = true; 19545 unsigned NonBitFields = 0; 19546 for (RecordDecl::field_iterator I = Record->field_begin(), 19547 E = Record->field_end(); 19548 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 19549 IsEmpty = false; 19550 if (I->isUnnamedBitfield()) { 19551 if (!I->isZeroLengthBitField(Context)) 19552 ZeroSize = false; 19553 } else { 19554 ++NonBitFields; 19555 QualType FieldType = I->getType(); 19556 if (FieldType->isIncompleteType() || 19557 !Context.getTypeSizeInChars(FieldType).isZero()) 19558 ZeroSize = false; 19559 } 19560 } 19561 19562 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 19563 // allowed in C++, but warn if its declaration is inside 19564 // extern "C" block. 19565 if (ZeroSize) { 19566 Diag(RecLoc, getLangOpts().CPlusPlus ? 19567 diag::warn_zero_size_struct_union_in_extern_c : 19568 diag::warn_zero_size_struct_union_compat) 19569 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 19570 } 19571 19572 // Structs without named members are extension in C (C99 6.7.2.1p7), 19573 // but are accepted by GCC. 19574 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 19575 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 19576 diag::ext_no_named_members_in_struct_union) 19577 << Record->isUnion(); 19578 } 19579 } 19580 } else { 19581 ObjCIvarDecl **ClsFields = 19582 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 19583 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 19584 ID->setEndOfDefinitionLoc(RBrac); 19585 // Add ivar's to class's DeclContext. 19586 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19587 ClsFields[i]->setLexicalDeclContext(ID); 19588 ID->addDecl(ClsFields[i]); 19589 } 19590 // Must enforce the rule that ivars in the base classes may not be 19591 // duplicates. 19592 if (ID->getSuperClass()) 19593 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 19594 } else if (ObjCImplementationDecl *IMPDecl = 19595 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 19596 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 19597 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 19598 // Ivar declared in @implementation never belongs to the implementation. 19599 // Only it is in implementation's lexical context. 19600 ClsFields[I]->setLexicalDeclContext(IMPDecl); 19601 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 19602 IMPDecl->setIvarLBraceLoc(LBrac); 19603 IMPDecl->setIvarRBraceLoc(RBrac); 19604 } else if (ObjCCategoryDecl *CDecl = 19605 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 19606 // case of ivars in class extension; all other cases have been 19607 // reported as errors elsewhere. 19608 // FIXME. Class extension does not have a LocEnd field. 19609 // CDecl->setLocEnd(RBrac); 19610 // Add ivar's to class extension's DeclContext. 19611 // Diagnose redeclaration of private ivars. 19612 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 19613 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 19614 if (IDecl) { 19615 if (const ObjCIvarDecl *ClsIvar = 19616 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 19617 Diag(ClsFields[i]->getLocation(), 19618 diag::err_duplicate_ivar_declaration); 19619 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 19620 continue; 19621 } 19622 for (const auto *Ext : IDecl->known_extensions()) { 19623 if (const ObjCIvarDecl *ClsExtIvar 19624 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 19625 Diag(ClsFields[i]->getLocation(), 19626 diag::err_duplicate_ivar_declaration); 19627 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 19628 continue; 19629 } 19630 } 19631 } 19632 ClsFields[i]->setLexicalDeclContext(CDecl); 19633 CDecl->addDecl(ClsFields[i]); 19634 } 19635 CDecl->setIvarLBraceLoc(LBrac); 19636 CDecl->setIvarRBraceLoc(RBrac); 19637 } 19638 } 19639 } 19640 19641 /// Determine whether the given integral value is representable within 19642 /// the given type T. 19643 static bool isRepresentableIntegerValue(ASTContext &Context, 19644 llvm::APSInt &Value, 19645 QualType T) { 19646 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 19647 "Integral type required!"); 19648 unsigned BitWidth = Context.getIntWidth(T); 19649 19650 if (Value.isUnsigned() || Value.isNonNegative()) { 19651 if (T->isSignedIntegerOrEnumerationType()) 19652 --BitWidth; 19653 return Value.getActiveBits() <= BitWidth; 19654 } 19655 return Value.getSignificantBits() <= BitWidth; 19656 } 19657 19658 // Given an integral type, return the next larger integral type 19659 // (or a NULL type of no such type exists). 19660 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 19661 // FIXME: Int128/UInt128 support, which also needs to be introduced into 19662 // enum checking below. 19663 assert((T->isIntegralType(Context) || 19664 T->isEnumeralType()) && "Integral type required!"); 19665 const unsigned NumTypes = 4; 19666 QualType SignedIntegralTypes[NumTypes] = { 19667 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 19668 }; 19669 QualType UnsignedIntegralTypes[NumTypes] = { 19670 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 19671 Context.UnsignedLongLongTy 19672 }; 19673 19674 unsigned BitWidth = Context.getTypeSize(T); 19675 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 19676 : UnsignedIntegralTypes; 19677 for (unsigned I = 0; I != NumTypes; ++I) 19678 if (Context.getTypeSize(Types[I]) > BitWidth) 19679 return Types[I]; 19680 19681 return QualType(); 19682 } 19683 19684 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 19685 EnumConstantDecl *LastEnumConst, 19686 SourceLocation IdLoc, 19687 IdentifierInfo *Id, 19688 Expr *Val) { 19689 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 19690 llvm::APSInt EnumVal(IntWidth); 19691 QualType EltTy; 19692 19693 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 19694 Val = nullptr; 19695 19696 if (Val) 19697 Val = DefaultLvalueConversion(Val).get(); 19698 19699 if (Val) { 19700 if (Enum->isDependentType() || Val->isTypeDependent() || 19701 Val->containsErrors()) 19702 EltTy = Context.DependentTy; 19703 else { 19704 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 19705 // underlying type, but do allow it in all other contexts. 19706 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 19707 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 19708 // constant-expression in the enumerator-definition shall be a converted 19709 // constant expression of the underlying type. 19710 EltTy = Enum->getIntegerType(); 19711 ExprResult Converted = 19712 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 19713 CCEK_Enumerator); 19714 if (Converted.isInvalid()) 19715 Val = nullptr; 19716 else 19717 Val = Converted.get(); 19718 } else if (!Val->isValueDependent() && 19719 !(Val = 19720 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 19721 .get())) { 19722 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 19723 } else { 19724 if (Enum->isComplete()) { 19725 EltTy = Enum->getIntegerType(); 19726 19727 // In Obj-C and Microsoft mode, require the enumeration value to be 19728 // representable in the underlying type of the enumeration. In C++11, 19729 // we perform a non-narrowing conversion as part of converted constant 19730 // expression checking. 19731 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19732 if (Context.getTargetInfo() 19733 .getTriple() 19734 .isWindowsMSVCEnvironment()) { 19735 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 19736 } else { 19737 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 19738 } 19739 } 19740 19741 // Cast to the underlying type. 19742 Val = ImpCastExprToType(Val, EltTy, 19743 EltTy->isBooleanType() ? CK_IntegralToBoolean 19744 : CK_IntegralCast) 19745 .get(); 19746 } else if (getLangOpts().CPlusPlus) { 19747 // C++11 [dcl.enum]p5: 19748 // If the underlying type is not fixed, the type of each enumerator 19749 // is the type of its initializing value: 19750 // - If an initializer is specified for an enumerator, the 19751 // initializing value has the same type as the expression. 19752 EltTy = Val->getType(); 19753 } else { 19754 // C99 6.7.2.2p2: 19755 // The expression that defines the value of an enumeration constant 19756 // shall be an integer constant expression that has a value 19757 // representable as an int. 19758 19759 // Complain if the value is not representable in an int. 19760 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 19761 Diag(IdLoc, diag::ext_enum_value_not_int) 19762 << toString(EnumVal, 10) << Val->getSourceRange() 19763 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 19764 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 19765 // Force the type of the expression to 'int'. 19766 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 19767 } 19768 EltTy = Val->getType(); 19769 } 19770 } 19771 } 19772 } 19773 19774 if (!Val) { 19775 if (Enum->isDependentType()) 19776 EltTy = Context.DependentTy; 19777 else if (!LastEnumConst) { 19778 // C++0x [dcl.enum]p5: 19779 // If the underlying type is not fixed, the type of each enumerator 19780 // is the type of its initializing value: 19781 // - If no initializer is specified for the first enumerator, the 19782 // initializing value has an unspecified integral type. 19783 // 19784 // GCC uses 'int' for its unspecified integral type, as does 19785 // C99 6.7.2.2p3. 19786 if (Enum->isFixed()) { 19787 EltTy = Enum->getIntegerType(); 19788 } 19789 else { 19790 EltTy = Context.IntTy; 19791 } 19792 } else { 19793 // Assign the last value + 1. 19794 EnumVal = LastEnumConst->getInitVal(); 19795 ++EnumVal; 19796 EltTy = LastEnumConst->getType(); 19797 19798 // Check for overflow on increment. 19799 if (EnumVal < LastEnumConst->getInitVal()) { 19800 // C++0x [dcl.enum]p5: 19801 // If the underlying type is not fixed, the type of each enumerator 19802 // is the type of its initializing value: 19803 // 19804 // - Otherwise the type of the initializing value is the same as 19805 // the type of the initializing value of the preceding enumerator 19806 // unless the incremented value is not representable in that type, 19807 // in which case the type is an unspecified integral type 19808 // sufficient to contain the incremented value. If no such type 19809 // exists, the program is ill-formed. 19810 QualType T = getNextLargerIntegralType(Context, EltTy); 19811 if (T.isNull() || Enum->isFixed()) { 19812 // There is no integral type larger enough to represent this 19813 // value. Complain, then allow the value to wrap around. 19814 EnumVal = LastEnumConst->getInitVal(); 19815 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 19816 ++EnumVal; 19817 if (Enum->isFixed()) 19818 // When the underlying type is fixed, this is ill-formed. 19819 Diag(IdLoc, diag::err_enumerator_wrapped) 19820 << toString(EnumVal, 10) 19821 << EltTy; 19822 else 19823 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 19824 << toString(EnumVal, 10); 19825 } else { 19826 EltTy = T; 19827 } 19828 19829 // Retrieve the last enumerator's value, extent that type to the 19830 // type that is supposed to be large enough to represent the incremented 19831 // value, then increment. 19832 EnumVal = LastEnumConst->getInitVal(); 19833 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19834 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 19835 ++EnumVal; 19836 19837 // If we're not in C++, diagnose the overflow of enumerator values, 19838 // which in C99 means that the enumerator value is not representable in 19839 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 19840 // permits enumerator values that are representable in some larger 19841 // integral type. 19842 if (!getLangOpts().CPlusPlus && !T.isNull()) 19843 Diag(IdLoc, diag::warn_enum_value_overflow); 19844 } else if (!getLangOpts().CPlusPlus && 19845 !EltTy->isDependentType() && 19846 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 19847 // Enforce C99 6.7.2.2p2 even when we compute the next value. 19848 Diag(IdLoc, diag::ext_enum_value_not_int) 19849 << toString(EnumVal, 10) << 1; 19850 } 19851 } 19852 } 19853 19854 if (!EltTy->isDependentType()) { 19855 // Make the enumerator value match the signedness and size of the 19856 // enumerator's type. 19857 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 19858 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 19859 } 19860 19861 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 19862 Val, EnumVal); 19863 } 19864 19865 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 19866 SourceLocation IILoc) { 19867 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 19868 !getLangOpts().CPlusPlus) 19869 return SkipBodyInfo(); 19870 19871 // We have an anonymous enum definition. Look up the first enumerator to 19872 // determine if we should merge the definition with an existing one and 19873 // skip the body. 19874 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 19875 forRedeclarationInCurContext()); 19876 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 19877 if (!PrevECD) 19878 return SkipBodyInfo(); 19879 19880 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 19881 NamedDecl *Hidden; 19882 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 19883 SkipBodyInfo Skip; 19884 Skip.Previous = Hidden; 19885 return Skip; 19886 } 19887 19888 return SkipBodyInfo(); 19889 } 19890 19891 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 19892 SourceLocation IdLoc, IdentifierInfo *Id, 19893 const ParsedAttributesView &Attrs, 19894 SourceLocation EqualLoc, Expr *Val) { 19895 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 19896 EnumConstantDecl *LastEnumConst = 19897 cast_or_null<EnumConstantDecl>(lastEnumConst); 19898 19899 // The scope passed in may not be a decl scope. Zip up the scope tree until 19900 // we find one that is. 19901 S = getNonFieldDeclScope(S); 19902 19903 // Verify that there isn't already something declared with this name in this 19904 // scope. 19905 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 19906 LookupName(R, S); 19907 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 19908 19909 if (PrevDecl && PrevDecl->isTemplateParameter()) { 19910 // Maybe we will complain about the shadowed template parameter. 19911 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 19912 // Just pretend that we didn't see the previous declaration. 19913 PrevDecl = nullptr; 19914 } 19915 19916 // C++ [class.mem]p15: 19917 // If T is the name of a class, then each of the following shall have a name 19918 // different from T: 19919 // - every enumerator of every member of class T that is an unscoped 19920 // enumerated type 19921 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 19922 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 19923 DeclarationNameInfo(Id, IdLoc)); 19924 19925 EnumConstantDecl *New = 19926 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 19927 if (!New) 19928 return nullptr; 19929 19930 if (PrevDecl) { 19931 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 19932 // Check for other kinds of shadowing not already handled. 19933 CheckShadow(New, PrevDecl, R); 19934 } 19935 19936 // When in C++, we may get a TagDecl with the same name; in this case the 19937 // enum constant will 'hide' the tag. 19938 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 19939 "Received TagDecl when not in C++!"); 19940 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 19941 if (isa<EnumConstantDecl>(PrevDecl)) 19942 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 19943 else 19944 Diag(IdLoc, diag::err_redefinition) << Id; 19945 notePreviousDefinition(PrevDecl, IdLoc); 19946 return nullptr; 19947 } 19948 } 19949 19950 // Process attributes. 19951 ProcessDeclAttributeList(S, New, Attrs); 19952 AddPragmaAttributes(S, New); 19953 19954 // Register this decl in the current scope stack. 19955 New->setAccess(TheEnumDecl->getAccess()); 19956 PushOnScopeChains(New, S); 19957 19958 ActOnDocumentableDecl(New); 19959 19960 return New; 19961 } 19962 19963 // Returns true when the enum initial expression does not trigger the 19964 // duplicate enum warning. A few common cases are exempted as follows: 19965 // Element2 = Element1 19966 // Element2 = Element1 + 1 19967 // Element2 = Element1 - 1 19968 // Where Element2 and Element1 are from the same enum. 19969 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 19970 Expr *InitExpr = ECD->getInitExpr(); 19971 if (!InitExpr) 19972 return true; 19973 InitExpr = InitExpr->IgnoreImpCasts(); 19974 19975 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 19976 if (!BO->isAdditiveOp()) 19977 return true; 19978 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 19979 if (!IL) 19980 return true; 19981 if (IL->getValue() != 1) 19982 return true; 19983 19984 InitExpr = BO->getLHS(); 19985 } 19986 19987 // This checks if the elements are from the same enum. 19988 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 19989 if (!DRE) 19990 return true; 19991 19992 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 19993 if (!EnumConstant) 19994 return true; 19995 19996 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 19997 Enum) 19998 return true; 19999 20000 return false; 20001 } 20002 20003 // Emits a warning when an element is implicitly set a value that 20004 // a previous element has already been set to. 20005 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 20006 EnumDecl *Enum, QualType EnumType) { 20007 // Avoid anonymous enums 20008 if (!Enum->getIdentifier()) 20009 return; 20010 20011 // Only check for small enums. 20012 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 20013 return; 20014 20015 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 20016 return; 20017 20018 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 20019 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 20020 20021 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 20022 20023 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 20024 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 20025 20026 // Use int64_t as a key to avoid needing special handling for map keys. 20027 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 20028 llvm::APSInt Val = D->getInitVal(); 20029 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 20030 }; 20031 20032 DuplicatesVector DupVector; 20033 ValueToVectorMap EnumMap; 20034 20035 // Populate the EnumMap with all values represented by enum constants without 20036 // an initializer. 20037 for (auto *Element : Elements) { 20038 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 20039 20040 // Null EnumConstantDecl means a previous diagnostic has been emitted for 20041 // this constant. Skip this enum since it may be ill-formed. 20042 if (!ECD) { 20043 return; 20044 } 20045 20046 // Constants with initializers are handled in the next loop. 20047 if (ECD->getInitExpr()) 20048 continue; 20049 20050 // Duplicate values are handled in the next loop. 20051 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 20052 } 20053 20054 if (EnumMap.size() == 0) 20055 return; 20056 20057 // Create vectors for any values that has duplicates. 20058 for (auto *Element : Elements) { 20059 // The last loop returned if any constant was null. 20060 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 20061 if (!ValidDuplicateEnum(ECD, Enum)) 20062 continue; 20063 20064 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 20065 if (Iter == EnumMap.end()) 20066 continue; 20067 20068 DeclOrVector& Entry = Iter->second; 20069 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 20070 // Ensure constants are different. 20071 if (D == ECD) 20072 continue; 20073 20074 // Create new vector and push values onto it. 20075 auto Vec = std::make_unique<ECDVector>(); 20076 Vec->push_back(D); 20077 Vec->push_back(ECD); 20078 20079 // Update entry to point to the duplicates vector. 20080 Entry = Vec.get(); 20081 20082 // Store the vector somewhere we can consult later for quick emission of 20083 // diagnostics. 20084 DupVector.emplace_back(std::move(Vec)); 20085 continue; 20086 } 20087 20088 ECDVector *Vec = Entry.get<ECDVector*>(); 20089 // Make sure constants are not added more than once. 20090 if (*Vec->begin() == ECD) 20091 continue; 20092 20093 Vec->push_back(ECD); 20094 } 20095 20096 // Emit diagnostics. 20097 for (const auto &Vec : DupVector) { 20098 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 20099 20100 // Emit warning for one enum constant. 20101 auto *FirstECD = Vec->front(); 20102 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 20103 << FirstECD << toString(FirstECD->getInitVal(), 10) 20104 << FirstECD->getSourceRange(); 20105 20106 // Emit one note for each of the remaining enum constants with 20107 // the same value. 20108 for (auto *ECD : llvm::drop_begin(*Vec)) 20109 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 20110 << ECD << toString(ECD->getInitVal(), 10) 20111 << ECD->getSourceRange(); 20112 } 20113 } 20114 20115 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 20116 bool AllowMask) const { 20117 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 20118 assert(ED->isCompleteDefinition() && "expected enum definition"); 20119 20120 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 20121 llvm::APInt &FlagBits = R.first->second; 20122 20123 if (R.second) { 20124 for (auto *E : ED->enumerators()) { 20125 const auto &EVal = E->getInitVal(); 20126 // Only single-bit enumerators introduce new flag values. 20127 if (EVal.isPowerOf2()) 20128 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal; 20129 } 20130 } 20131 20132 // A value is in a flag enum if either its bits are a subset of the enum's 20133 // flag bits (the first condition) or we are allowing masks and the same is 20134 // true of its complement (the second condition). When masks are allowed, we 20135 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 20136 // 20137 // While it's true that any value could be used as a mask, the assumption is 20138 // that a mask will have all of the insignificant bits set. Anything else is 20139 // likely a logic error. 20140 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 20141 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 20142 } 20143 20144 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 20145 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 20146 const ParsedAttributesView &Attrs) { 20147 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 20148 QualType EnumType = Context.getTypeDeclType(Enum); 20149 20150 ProcessDeclAttributeList(S, Enum, Attrs); 20151 20152 if (Enum->isDependentType()) { 20153 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20154 EnumConstantDecl *ECD = 20155 cast_or_null<EnumConstantDecl>(Elements[i]); 20156 if (!ECD) continue; 20157 20158 ECD->setType(EnumType); 20159 } 20160 20161 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 20162 return; 20163 } 20164 20165 // TODO: If the result value doesn't fit in an int, it must be a long or long 20166 // long value. ISO C does not support this, but GCC does as an extension, 20167 // emit a warning. 20168 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 20169 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 20170 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 20171 20172 // Verify that all the values are okay, compute the size of the values, and 20173 // reverse the list. 20174 unsigned NumNegativeBits = 0; 20175 unsigned NumPositiveBits = 0; 20176 20177 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 20178 EnumConstantDecl *ECD = 20179 cast_or_null<EnumConstantDecl>(Elements[i]); 20180 if (!ECD) continue; // Already issued a diagnostic. 20181 20182 const llvm::APSInt &InitVal = ECD->getInitVal(); 20183 20184 // Keep track of the size of positive and negative values. 20185 if (InitVal.isUnsigned() || InitVal.isNonNegative()) { 20186 // If the enumerator is zero that should still be counted as a positive 20187 // bit since we need a bit to store the value zero. 20188 unsigned ActiveBits = InitVal.getActiveBits(); 20189 NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u}); 20190 } else { 20191 NumNegativeBits = 20192 std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits()); 20193 } 20194 } 20195 20196 // If we have an empty set of enumerators we still need one bit. 20197 // From [dcl.enum]p8 20198 // If the enumerator-list is empty, the values of the enumeration are as if 20199 // the enumeration had a single enumerator with value 0 20200 if (!NumPositiveBits && !NumNegativeBits) 20201 NumPositiveBits = 1; 20202 20203 // Figure out the type that should be used for this enum. 20204 QualType BestType; 20205 unsigned BestWidth; 20206 20207 // C++0x N3000 [conv.prom]p3: 20208 // An rvalue of an unscoped enumeration type whose underlying 20209 // type is not fixed can be converted to an rvalue of the first 20210 // of the following types that can represent all the values of 20211 // the enumeration: int, unsigned int, long int, unsigned long 20212 // int, long long int, or unsigned long long int. 20213 // C99 6.4.4.3p2: 20214 // An identifier declared as an enumeration constant has type int. 20215 // The C99 rule is modified by a gcc extension 20216 QualType BestPromotionType; 20217 20218 bool Packed = Enum->hasAttr<PackedAttr>(); 20219 // -fshort-enums is the equivalent to specifying the packed attribute on all 20220 // enum definitions. 20221 if (LangOpts.ShortEnums) 20222 Packed = true; 20223 20224 // If the enum already has a type because it is fixed or dictated by the 20225 // target, promote that type instead of analyzing the enumerators. 20226 if (Enum->isComplete()) { 20227 BestType = Enum->getIntegerType(); 20228 if (Context.isPromotableIntegerType(BestType)) 20229 BestPromotionType = Context.getPromotedIntegerType(BestType); 20230 else 20231 BestPromotionType = BestType; 20232 20233 BestWidth = Context.getIntWidth(BestType); 20234 } 20235 else if (NumNegativeBits) { 20236 // If there is a negative value, figure out the smallest integer type (of 20237 // int/long/longlong) that fits. 20238 // If it's packed, check also if it fits a char or a short. 20239 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 20240 BestType = Context.SignedCharTy; 20241 BestWidth = CharWidth; 20242 } else if (Packed && NumNegativeBits <= ShortWidth && 20243 NumPositiveBits < ShortWidth) { 20244 BestType = Context.ShortTy; 20245 BestWidth = ShortWidth; 20246 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 20247 BestType = Context.IntTy; 20248 BestWidth = IntWidth; 20249 } else { 20250 BestWidth = Context.getTargetInfo().getLongWidth(); 20251 20252 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 20253 BestType = Context.LongTy; 20254 } else { 20255 BestWidth = Context.getTargetInfo().getLongLongWidth(); 20256 20257 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 20258 Diag(Enum->getLocation(), diag::ext_enum_too_large); 20259 BestType = Context.LongLongTy; 20260 } 20261 } 20262 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 20263 } else { 20264 // If there is no negative value, figure out the smallest type that fits 20265 // all of the enumerator values. 20266 // If it's packed, check also if it fits a char or a short. 20267 if (Packed && NumPositiveBits <= CharWidth) { 20268 BestType = Context.UnsignedCharTy; 20269 BestPromotionType = Context.IntTy; 20270 BestWidth = CharWidth; 20271 } else if (Packed && NumPositiveBits <= ShortWidth) { 20272 BestType = Context.UnsignedShortTy; 20273 BestPromotionType = Context.IntTy; 20274 BestWidth = ShortWidth; 20275 } else if (NumPositiveBits <= IntWidth) { 20276 BestType = Context.UnsignedIntTy; 20277 BestWidth = IntWidth; 20278 BestPromotionType 20279 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20280 ? Context.UnsignedIntTy : Context.IntTy; 20281 } else if (NumPositiveBits <= 20282 (BestWidth = Context.getTargetInfo().getLongWidth())) { 20283 BestType = Context.UnsignedLongTy; 20284 BestPromotionType 20285 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20286 ? Context.UnsignedLongTy : Context.LongTy; 20287 } else { 20288 BestWidth = Context.getTargetInfo().getLongLongWidth(); 20289 assert(NumPositiveBits <= BestWidth && 20290 "How could an initializer get larger than ULL?"); 20291 BestType = Context.UnsignedLongLongTy; 20292 BestPromotionType 20293 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 20294 ? Context.UnsignedLongLongTy : Context.LongLongTy; 20295 } 20296 } 20297 20298 // Loop over all of the enumerator constants, changing their types to match 20299 // the type of the enum if needed. 20300 for (auto *D : Elements) { 20301 auto *ECD = cast_or_null<EnumConstantDecl>(D); 20302 if (!ECD) continue; // Already issued a diagnostic. 20303 20304 // Standard C says the enumerators have int type, but we allow, as an 20305 // extension, the enumerators to be larger than int size. If each 20306 // enumerator value fits in an int, type it as an int, otherwise type it the 20307 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 20308 // that X has type 'int', not 'unsigned'. 20309 20310 // Determine whether the value fits into an int. 20311 llvm::APSInt InitVal = ECD->getInitVal(); 20312 20313 // If it fits into an integer type, force it. Otherwise force it to match 20314 // the enum decl type. 20315 QualType NewTy; 20316 unsigned NewWidth; 20317 bool NewSign; 20318 if (!getLangOpts().CPlusPlus && 20319 !Enum->isFixed() && 20320 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 20321 NewTy = Context.IntTy; 20322 NewWidth = IntWidth; 20323 NewSign = true; 20324 } else if (ECD->getType() == BestType) { 20325 // Already the right type! 20326 if (getLangOpts().CPlusPlus) 20327 // C++ [dcl.enum]p4: Following the closing brace of an 20328 // enum-specifier, each enumerator has the type of its 20329 // enumeration. 20330 ECD->setType(EnumType); 20331 continue; 20332 } else { 20333 NewTy = BestType; 20334 NewWidth = BestWidth; 20335 NewSign = BestType->isSignedIntegerOrEnumerationType(); 20336 } 20337 20338 // Adjust the APSInt value. 20339 InitVal = InitVal.extOrTrunc(NewWidth); 20340 InitVal.setIsSigned(NewSign); 20341 ECD->setInitVal(Context, InitVal); 20342 20343 // Adjust the Expr initializer and type. 20344 if (ECD->getInitExpr() && 20345 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 20346 ECD->setInitExpr(ImplicitCastExpr::Create( 20347 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 20348 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 20349 if (getLangOpts().CPlusPlus) 20350 // C++ [dcl.enum]p4: Following the closing brace of an 20351 // enum-specifier, each enumerator has the type of its 20352 // enumeration. 20353 ECD->setType(EnumType); 20354 else 20355 ECD->setType(NewTy); 20356 } 20357 20358 Enum->completeDefinition(BestType, BestPromotionType, 20359 NumPositiveBits, NumNegativeBits); 20360 20361 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 20362 20363 if (Enum->isClosedFlag()) { 20364 for (Decl *D : Elements) { 20365 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 20366 if (!ECD) continue; // Already issued a diagnostic. 20367 20368 llvm::APSInt InitVal = ECD->getInitVal(); 20369 if (InitVal != 0 && !InitVal.isPowerOf2() && 20370 !IsValueInFlagEnum(Enum, InitVal, true)) 20371 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 20372 << ECD << Enum; 20373 } 20374 } 20375 20376 // Now that the enum type is defined, ensure it's not been underaligned. 20377 if (Enum->hasAttrs()) 20378 CheckAlignasUnderalignment(Enum); 20379 } 20380 20381 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 20382 SourceLocation StartLoc, 20383 SourceLocation EndLoc) { 20384 StringLiteral *AsmString = cast<StringLiteral>(expr); 20385 20386 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 20387 AsmString, StartLoc, 20388 EndLoc); 20389 CurContext->addDecl(New); 20390 return New; 20391 } 20392 20393 Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) { 20394 auto *New = TopLevelStmtDecl::Create(Context, Statement); 20395 Context.getTranslationUnitDecl()->addDecl(New); 20396 return New; 20397 } 20398 20399 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 20400 IdentifierInfo* AliasName, 20401 SourceLocation PragmaLoc, 20402 SourceLocation NameLoc, 20403 SourceLocation AliasNameLoc) { 20404 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 20405 LookupOrdinaryName); 20406 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 20407 AttributeCommonInfo::Form::Pragma()); 20408 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 20409 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 20410 20411 // If a declaration that: 20412 // 1) declares a function or a variable 20413 // 2) has external linkage 20414 // already exists, add a label attribute to it. 20415 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20416 if (isDeclExternC(PrevDecl)) 20417 PrevDecl->addAttr(Attr); 20418 else 20419 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 20420 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 20421 // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers. 20422 } else 20423 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 20424 } 20425 20426 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 20427 SourceLocation PragmaLoc, 20428 SourceLocation NameLoc) { 20429 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 20430 20431 if (PrevDecl) { 20432 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 20433 } else { 20434 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 20435 } 20436 } 20437 20438 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 20439 IdentifierInfo* AliasName, 20440 SourceLocation PragmaLoc, 20441 SourceLocation NameLoc, 20442 SourceLocation AliasNameLoc) { 20443 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 20444 LookupOrdinaryName); 20445 WeakInfo W = WeakInfo(Name, NameLoc); 20446 20447 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 20448 if (!PrevDecl->hasAttr<AliasAttr>()) 20449 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 20450 DeclApplyPragmaWeak(TUScope, ND, W); 20451 } else { 20452 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 20453 } 20454 } 20455 20456 ObjCContainerDecl *Sema::getObjCDeclContext() const { 20457 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 20458 } 20459 20460 Sema::FunctionEmissionStatus Sema::getEmissionStatus(const FunctionDecl *FD, 20461 bool Final) { 20462 assert(FD && "Expected non-null FunctionDecl"); 20463 20464 // SYCL functions can be template, so we check if they have appropriate 20465 // attribute prior to checking if it is a template. 20466 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 20467 return FunctionEmissionStatus::Emitted; 20468 20469 // Templates are emitted when they're instantiated. 20470 if (FD->isDependentContext()) 20471 return FunctionEmissionStatus::TemplateDiscarded; 20472 20473 // Check whether this function is an externally visible definition. 20474 auto IsEmittedForExternalSymbol = [this, FD]() { 20475 // We have to check the GVA linkage of the function's *definition* -- if we 20476 // only have a declaration, we don't know whether or not the function will 20477 // be emitted, because (say) the definition could include "inline". 20478 const FunctionDecl *Def = FD->getDefinition(); 20479 20480 return Def && !isDiscardableGVALinkage( 20481 getASTContext().GetGVALinkageForFunction(Def)); 20482 }; 20483 20484 if (LangOpts.OpenMPIsTargetDevice) { 20485 // In OpenMP device mode we will not emit host only functions, or functions 20486 // we don't need due to their linkage. 20487 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20488 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20489 // DevTy may be changed later by 20490 // #pragma omp declare target to(*) device_type(*). 20491 // Therefore DevTy having no value does not imply host. The emission status 20492 // will be checked again at the end of compilation unit with Final = true. 20493 if (DevTy) 20494 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 20495 return FunctionEmissionStatus::OMPDiscarded; 20496 // If we have an explicit value for the device type, or we are in a target 20497 // declare context, we need to emit all extern and used symbols. 20498 if (isInOpenMPDeclareTargetContext() || DevTy) 20499 if (IsEmittedForExternalSymbol()) 20500 return FunctionEmissionStatus::Emitted; 20501 // Device mode only emits what it must, if it wasn't tagged yet and needed, 20502 // we'll omit it. 20503 if (Final) 20504 return FunctionEmissionStatus::OMPDiscarded; 20505 } else if (LangOpts.OpenMP > 45) { 20506 // In OpenMP host compilation prior to 5.0 everything was an emitted host 20507 // function. In 5.0, no_host was introduced which might cause a function to 20508 // be ommitted. 20509 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 20510 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 20511 if (DevTy) 20512 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 20513 return FunctionEmissionStatus::OMPDiscarded; 20514 } 20515 20516 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 20517 return FunctionEmissionStatus::Emitted; 20518 20519 if (LangOpts.CUDA) { 20520 // When compiling for device, host functions are never emitted. Similarly, 20521 // when compiling for host, device and global functions are never emitted. 20522 // (Technically, we do emit a host-side stub for global functions, but this 20523 // doesn't count for our purposes here.) 20524 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 20525 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 20526 return FunctionEmissionStatus::CUDADiscarded; 20527 if (!LangOpts.CUDAIsDevice && 20528 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 20529 return FunctionEmissionStatus::CUDADiscarded; 20530 20531 if (IsEmittedForExternalSymbol()) 20532 return FunctionEmissionStatus::Emitted; 20533 } 20534 20535 // Otherwise, the function is known-emitted if it's in our set of 20536 // known-emitted functions. 20537 return FunctionEmissionStatus::Unknown; 20538 } 20539 20540 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 20541 // Host-side references to a __global__ function refer to the stub, so the 20542 // function itself is never emitted and therefore should not be marked. 20543 // If we have host fn calls kernel fn calls host+device, the HD function 20544 // does not get instantiated on the host. We model this by omitting at the 20545 // call to the kernel from the callgraph. This ensures that, when compiling 20546 // for host, only HD functions actually called from the host get marked as 20547 // known-emitted. 20548 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 20549 IdentifyCUDATarget(Callee) == CFT_Global; 20550 } 20551